Skip to content
Merged
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
4 changes: 4 additions & 0 deletions src/NetAnalyzers/Core/AnalyzerReleases.Unshipped.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,9 @@

Rule ID | Category | Severity | Notes
--------|----------|----------|-------
CA1510 | Maintainability | Info | UseExceptionThrowHelpers, [Documentation](https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1510)
CA1511 | Maintainability | Info | UseExceptionThrowHelpers, [Documentation](https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1511)
CA1512 | Maintainability | Info | UseExceptionThrowHelpers, [Documentation](https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1512)
CA1513 | Maintainability | Info | UseExceptionThrowHelpers, [Documentation](https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1513)
CA1856 | Performance | Error | ConstantExpectedAnalyzer, [Documentation](https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1856)
CA1857 | Performance | Warning | ConstantExpectedAnalyzer, [Documentation](https://docs.microsoft.com/dotnet/fundamentals/code-analysis/quality-rules/ca1857)
Original file line number Diff line number Diff line change
Expand Up @@ -2031,4 +2031,26 @@
<data name="PreventNumericIntPtrUIntPtrBehavioralChangesConversionThrowsMessage" xml:space="preserve">
<value>Starting with .NET 7 the explicit conversion '{0}' will throw when overflowing in a checked context. Wrap the expression with an 'unchecked' statement to restore the .NET 6 behavior.</value>
</data>
<data name="UseArgumentNullExceptionThrowHelperTitle" xml:space="preserve">
<value>Use ArgumentNullException throw helper</value>
</data>
<data name="UseArgumentExceptionThrowHelperTitle" xml:space="preserve">
<value>Use ArgumentException throw helper</value>
</data>
<data name="UseArgumentOutOfRangeExceptionThrowHelperTitle" xml:space="preserve">
<value>Use ArgumentOutOfRangeException throw helper</value>
</data>
<data name="UseObjectDisposedExceptionThrowHelperTitle" xml:space="preserve">
<value>Use ObjectDisposedException throw helper</value>
</data>
<data name="UseThrowHelperMessage" xml:space="preserve">
<value>Use '{0}.{1}' instead of explicitly throwing a new exception instance</value>
</data>
<data name="UseThrowHelperDescription" xml:space="preserve">
<value>Throw helpers are simpler and more efficient than an if block constructing a new exception instance.</value>
</data>
<data name="UseThrowHelperFix" xml:space="preserve">
<value>Use '{0}.{1}'</value>
</data>

</root>

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
// 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.Diagnostics.CodeAnalysis;
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.Editing;

namespace Microsoft.NetCore.Analyzers.Runtime
{
/// <summary>Fixer for <see cref="UseExceptionThrowHelpers"/>.</summary>
[ExportCodeFixProvider(LanguageNames.CSharp, LanguageNames.VisualBasic), Shared]
public sealed class UseExceptionThrowHelpersFixer : CodeFixProvider
{
public sealed override ImmutableArray<string> FixableDiagnosticIds { get; } = ImmutableArray.Create(
UseExceptionThrowHelpers.UseArgumentNullExceptionThrowIfNullRuleId,
UseExceptionThrowHelpers.UseArgumentExceptionThrowIfNullOrEmptyRuleId,
UseExceptionThrowHelpers.UseArgumentOutOfRangeExceptionThrowIfRuleId,
UseExceptionThrowHelpers.UseObjectDisposedExceptionThrowIfRuleId);

public sealed override FixAllProvider GetFixAllProvider() => CustomFixAllProvider.Instance;

public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
Document doc = context.Document;
SemanticModel model = await doc.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
SyntaxNode root = await doc.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);

if (TryGetFixInfo(doc, root, model, context.Diagnostics[0], out INamedTypeSymbol? typeSymbol, out string? methodName, out SyntaxNode? node, out SyntaxNode? arg, out SyntaxNode? other))
{
string title = string.Format(MicrosoftNetCoreAnalyzersResources.UseThrowHelperFix, typeSymbol.Name, methodName);
context.RegisterCodeFix(
CodeAction.Create(title, equivalenceKey: title, createChangedDocument: async cancellationToken =>
{
DocumentEditor editor = await DocumentEditor.CreateAsync(doc, cancellationToken).ConfigureAwait(false);
ApplyFix(typeSymbol, methodName, node, arg, other, editor);
return editor.GetChangedDocument();
}),
context.Diagnostics);
}
}

private static bool TryGetFixInfo(
Document doc,
SyntaxNode root,
SemanticModel model,
Diagnostic diagnostic,
[NotNullWhen(true)] out INamedTypeSymbol? typeSymbol,
[NotNullWhen(true)] out string? methodName,
[NotNullWhen(true)] out SyntaxNode? node,
[NotNullWhen(true)] out SyntaxNode? arg,
[NotNullWhen(true)] out SyntaxNode? other)
{
typeSymbol = null;
methodName = null;
arg = null;
other = null;

node = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true);
if (node != null &&
diagnostic.AdditionalLocations.Count != 0 &&
diagnostic.AdditionalLocations[0] is Location argLocation)
{
arg = root.FindNode(argLocation.SourceSpan, getInnermostNodeForTie: true);
string id = diagnostic.Id;

if (diagnostic.AdditionalLocations.Count == 2)
{
Location otherLocation = diagnostic.AdditionalLocations[1];
other = otherLocation == Location.None ? // None is special-cased by the analyzer to mean "this"
SyntaxGenerator.GetGenerator(doc).ThisExpression() :
root.FindNode(otherLocation.SourceSpan, getInnermostNodeForTie: true);
}

switch (id)
{
case UseExceptionThrowHelpers.UseArgumentNullExceptionThrowIfNullRuleId:
typeSymbol = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemArgumentNullException);
methodName = "ThrowIfNull";
break;

case UseExceptionThrowHelpers.UseArgumentExceptionThrowIfNullOrEmptyRuleId:
typeSymbol = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemArgumentException);
methodName = "ThrowIfNullOrEmpty";
break;

case UseExceptionThrowHelpers.UseArgumentOutOfRangeExceptionThrowIfRuleId:
typeSymbol = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemArgumentOutOfRangeException);
diagnostic.Properties.TryGetValue(UseExceptionThrowHelpers.MethodNamePropertyKey, out methodName);
break;

case UseExceptionThrowHelpers.UseObjectDisposedExceptionThrowIfRuleId when other is not null:
typeSymbol = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemObjectDisposedException);
methodName = "ThrowIf";
break;
}
}

return typeSymbol != null && methodName != null && arg != null;
}

private static void ApplyFix(
INamedTypeSymbol typeSymbol,
string methodName,
SyntaxNode node,
SyntaxNode arg,
SyntaxNode other,
SyntaxEditor editor)
{
editor.ReplaceNode(
node,
editor.Generator.ExpressionStatement(
editor.Generator.InvocationExpression(
editor.Generator.MemberAccessExpression(
editor.Generator.TypeExpressionForStaticMemberAccess(typeSymbol), methodName),
other is not null ? new SyntaxNode[] { arg, other } : new SyntaxNode[] { arg })).WithTriviaFrom(node));
}

private sealed class CustomFixAllProvider : DocumentBasedFixAllProvider
{
public static readonly CustomFixAllProvider Instance = new();

protected override string CodeActionTitle => MicrosoftNetCoreAnalyzersResources.UseThrowHelperFix;

protected override async Task<SyntaxNode> FixAllInDocumentAsync(FixAllContext fixAllContext, Document document, ImmutableArray<Diagnostic> diagnostics)
{
DocumentEditor editor = await DocumentEditor.CreateAsync(document, fixAllContext.CancellationToken).ConfigureAwait(false);
SyntaxNode root = editor.OriginalRoot;
SemanticModel model = editor.SemanticModel;

foreach (Diagnostic diagnostic in diagnostics)
{
if (TryGetFixInfo(document, root, model, diagnostic, out INamedTypeSymbol? typeSymbol, out string? methodName, out SyntaxNode? node, out SyntaxNode? arg, out SyntaxNode? other))
{
ApplyFix(typeSymbol, methodName, node, arg, other, editor);
}
}

return editor.GetChangedRoot();
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -2682,6 +2682,21 @@
<target state="translated">ThreadStatic má vliv jenom na statická pole.</target>
<note />
</trans-unit>
<trans-unit id="UseArgumentExceptionThrowHelperTitle">
<source>Use ArgumentException throw helper</source>
<target state="new">Use ArgumentException throw helper</target>
<note />
</trans-unit>
<trans-unit id="UseArgumentNullExceptionThrowHelperTitle">
<source>Use ArgumentNullException throw helper</source>
<target state="new">Use ArgumentNullException throw helper</target>
<note />
</trans-unit>
<trans-unit id="UseArgumentOutOfRangeExceptionThrowHelperTitle">
<source>Use ArgumentOutOfRangeException throw helper</source>
<target state="new">Use ArgumentOutOfRangeException throw helper</target>
<note />
</trans-unit>
<trans-unit id="UseArrayEmpty">
<source>Use Array.Empty</source>
<target state="translated">Použijte Array.Empty</target>
Expand Down Expand Up @@ -2897,6 +2912,11 @@
<target state="translated">Použití spravovaných ekvivalentů rozhraní Win32 API</target>
<note />
</trans-unit>
<trans-unit id="UseObjectDisposedExceptionThrowHelperTitle">
<source>Use ObjectDisposedException throw helper</source>
<target state="new">Use ObjectDisposedException throw helper</target>
<note />
</trans-unit>
<trans-unit id="UseOrdinalStringComparisonDescription">
<source>A string comparison operation that is nonlinguistic does not set the StringComparison parameter to either Ordinal or OrdinalIgnoreCase. By explicitly setting the parameter to either StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase, your code often gains speed, becomes more correct, and becomes more reliable.</source>
<target state="translated">Operace porovnání řetězců, která není jazyková, nenastavuje parametr StringComparison na hodnotu Ordinal nebo OrdinalIgnoreCase. Explicitním nastavením parametru na hodnotu StringComparison.Ordinal nebo StringComparison.OrdinalIgnoreCase se kód často urychlí a bývá správnější a spolehlivější.</target>
Expand Down Expand Up @@ -3042,6 +3062,21 @@
<target state="translated">Použít znakový literál pro vyhledávání s jedním znakem</target>
<note />
</trans-unit>
<trans-unit id="UseThrowHelperDescription">
<source>Throw helpers are simpler and more efficient than an if block constructing a new exception instance.</source>
<target state="new">Throw helpers are simpler and more efficient than an if block constructing a new exception instance.</target>
<note />
</trans-unit>
<trans-unit id="UseThrowHelperFix">
<source>Use '{0}.{1}'</source>
<target state="new">Use '{0}.{1}'</target>
<note />
</trans-unit>
<trans-unit id="UseThrowHelperMessage">
<source>Use '{0}.{1}' instead of explicitly throwing a new exception instance</source>
<target state="new">Use '{0}.{1}' instead of explicitly throwing a new exception instance</target>
<note />
</trans-unit>
<trans-unit id="UseValidPlatformStringDescription">
<source>Platform compatibility analyzer requires a valid platform name and version.</source>
<target state="translated">Analyzátor kompatibility platformy vyžaduje platný název a verzi platformy.</target>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2682,6 +2682,21 @@
<target state="translated">\"ThreadStatic\" wirkt sich nur auf statische Felder aus</target>
<note />
</trans-unit>
<trans-unit id="UseArgumentExceptionThrowHelperTitle">
<source>Use ArgumentException throw helper</source>
<target state="new">Use ArgumentException throw helper</target>
<note />
</trans-unit>
<trans-unit id="UseArgumentNullExceptionThrowHelperTitle">
<source>Use ArgumentNullException throw helper</source>
<target state="new">Use ArgumentNullException throw helper</target>
<note />
</trans-unit>
<trans-unit id="UseArgumentOutOfRangeExceptionThrowHelperTitle">
<source>Use ArgumentOutOfRangeException throw helper</source>
<target state="new">Use ArgumentOutOfRangeException throw helper</target>
<note />
</trans-unit>
<trans-unit id="UseArrayEmpty">
<source>Use Array.Empty</source>
<target state="translated">Array.Empty verwenden</target>
Expand Down Expand Up @@ -2897,6 +2912,11 @@
<target state="translated">Verwaltete Entsprechungen der Win32-API verwenden</target>
<note />
</trans-unit>
<trans-unit id="UseObjectDisposedExceptionThrowHelperTitle">
<source>Use ObjectDisposedException throw helper</source>
<target state="new">Use ObjectDisposedException throw helper</target>
<note />
</trans-unit>
<trans-unit id="UseOrdinalStringComparisonDescription">
<source>A string comparison operation that is nonlinguistic does not set the StringComparison parameter to either Ordinal or OrdinalIgnoreCase. By explicitly setting the parameter to either StringComparison.Ordinal or StringComparison.OrdinalIgnoreCase, your code often gains speed, becomes more correct, and becomes more reliable.</source>
<target state="translated">Bei einem nicht linguistischen Vorgang zum Zeichenfolgenvergleich wird der StringComparison-Parameter nicht auf "Ordinal" oder "OrdinalIgnoreCase" festgelegt. Indem der Parameter explizit auf "StringComparison.Ordinal" oder "StringComparison.OrdinalIgnoreCase" festgelegt wird, gewinnt Ihr Code häufig an Geschwindigkeit und ist zudem korrekter und zuverlässiger.</target>
Expand Down Expand Up @@ -3042,6 +3062,21 @@
<target state="translated">Zeichenliteral für die Suche nach einem einzelnen Zeichen verwenden</target>
<note />
</trans-unit>
<trans-unit id="UseThrowHelperDescription">
<source>Throw helpers are simpler and more efficient than an if block constructing a new exception instance.</source>
<target state="new">Throw helpers are simpler and more efficient than an if block constructing a new exception instance.</target>
<note />
</trans-unit>
<trans-unit id="UseThrowHelperFix">
<source>Use '{0}.{1}'</source>
<target state="new">Use '{0}.{1}'</target>
<note />
</trans-unit>
<trans-unit id="UseThrowHelperMessage">
<source>Use '{0}.{1}' instead of explicitly throwing a new exception instance</source>
<target state="new">Use '{0}.{1}' instead of explicitly throwing a new exception instance</target>
<note />
</trans-unit>
<trans-unit id="UseValidPlatformStringDescription">
<source>Platform compatibility analyzer requires a valid platform name and version.</source>
<target state="translated">Das Analysetool für Plattformkompatibilität erfordert einen gültigen Plattformnamen und eine gültige Version.</target>
Expand Down
Loading