diff --git a/.editorconfig b/.editorconfig index 9ee71022e..8f2bee4af 100644 --- a/.editorconfig +++ b/.editorconfig @@ -443,10 +443,10 @@ dotnet_diagnostic.MA0033.severity = warning dotnet_diagnostic.MA0035.severity = warning dotnet_diagnostic.MA0036.severity = suggestion dotnet_diagnostic.MA0037.severity = error -dotnet_diagnostic.MA0038.severity = suggestion +dotnet_diagnostic.MA0038.severity = none dotnet_diagnostic.MA0039.severity = error dotnet_diagnostic.MA0040.severity = suggestion -dotnet_diagnostic.MA0041.severity = suggestion +dotnet_diagnostic.MA0041.severity = none dotnet_diagnostic.MA0042.severity = suggestion dotnet_diagnostic.MA0043.severity = suggestion dotnet_diagnostic.MA0044.severity = suggestion diff --git a/Directory.Build.props b/Directory.Build.props index 71a8f998e..ec839181c 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -38,7 +38,7 @@ all runtime; build; native; contentfiles; analyzers - + all runtime; build; native; contentfiles; analyzers diff --git a/Directory.Build.targets b/Directory.Build.targets index f933f2471..392662979 100644 --- a/Directory.Build.targets +++ b/Directory.Build.targets @@ -65,9 +65,9 @@ - - - + + + $(DefineConstants);ROSLYN4_4;ROSLYN_4_2_OR_GREATER;ROSLYN_4_4_OR_GREATER;ROSLYN_4_5_OR_GREATER;ROSLYN_4_6_OR_GREATER;ROSLYN_4_8_OR_GREATER diff --git a/global.json b/global.json index 9f283aa43..7da276347 100644 --- a/global.json +++ b/global.json @@ -1,6 +1,6 @@ { "sdk": { - "version": "7.0.400", + "version": "8.0.100", "rollForward": "latestMajor" } } \ No newline at end of file diff --git a/src/DocumentationGenerator/DocumentationGenerator.csproj b/src/DocumentationGenerator/DocumentationGenerator.csproj index 63e55b829..d5024c813 100644 --- a/src/DocumentationGenerator/DocumentationGenerator.csproj +++ b/src/DocumentationGenerator/DocumentationGenerator.csproj @@ -2,7 +2,7 @@ Exe - net7.0 + net8.0 false true enable diff --git a/src/ListDotNetTypes/ListDotNetTypes.csproj b/src/ListDotNetTypes/ListDotNetTypes.csproj index 86eb4d160..ad8e86f05 100644 --- a/src/ListDotNetTypes/ListDotNetTypes.csproj +++ b/src/ListDotNetTypes/ListDotNetTypes.csproj @@ -2,7 +2,7 @@ Exe - net7.0 + net8.0 enable false true diff --git a/src/Meziantou.Analyzer.CodeFixers/Meziantou.Analyzer.CodeFixers.csproj b/src/Meziantou.Analyzer.CodeFixers/Meziantou.Analyzer.CodeFixers.csproj index 17307b016..c9e5cf76f 100644 --- a/src/Meziantou.Analyzer.CodeFixers/Meziantou.Analyzer.CodeFixers.csproj +++ b/src/Meziantou.Analyzer.CodeFixers/Meziantou.Analyzer.CodeFixers.csproj @@ -1,6 +1,6 @@  - net7.0;netstandard2.0 + net8.0;netstandard2.0 false 1.0.1 enable diff --git a/src/Meziantou.Analyzer.CodeFixers/Rules/DoNotUseBlockingCallInAsyncContextFixer.cs b/src/Meziantou.Analyzer.CodeFixers/Rules/DoNotUseBlockingCallInAsyncContextFixer.cs index 07e7ddfe9..727a90f27 100644 --- a/src/Meziantou.Analyzer.CodeFixers/Rules/DoNotUseBlockingCallInAsyncContextFixer.cs +++ b/src/Meziantou.Analyzer.CodeFixers/Rules/DoNotUseBlockingCallInAsyncContextFixer.cs @@ -114,8 +114,7 @@ private static async Task ReplaceWithMethodName(Document document, Syn var generator = editor.Generator; var invocation = (InvocationExpressionSyntax)nodeToFix; - var memberAccess = invocation.Expression as MemberAccessExpressionSyntax; - if (memberAccess == null) + if (invocation.Expression is not MemberAccessExpressionSyntax memberAccess) return document; var newNode = nodeToFix.ReplaceNode(memberAccess.Name, generator.IdentifierName(methodName)); diff --git a/src/Meziantou.Analyzer.CodeFixers/Rules/OptimizeLinqUsageFixer.cs b/src/Meziantou.Analyzer.CodeFixers/Rules/OptimizeLinqUsageFixer.cs index 0e6f98855..f943f4e5f 100644 --- a/src/Meziantou.Analyzer.CodeFixers/Rules/OptimizeLinqUsageFixer.cs +++ b/src/Meziantou.Analyzer.CodeFixers/Rules/OptimizeLinqUsageFixer.cs @@ -321,8 +321,7 @@ private static async Task UseCastInsteadOfSelect(Document document, Sy var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); var generator = editor.Generator; - var operation = editor.SemanticModel.GetOperation(selectInvocationExpression, cancellationToken) as IInvocationOperation; - if (operation == null) + if (editor.SemanticModel.GetOperation(selectInvocationExpression, cancellationToken) is not IInvocationOperation operation) return document; var type = operation.TargetMethod.TypeArguments[1]; @@ -647,7 +646,7 @@ private static SyntaxNode ReplaceParameter(IAnonymousFunctionOperation method, s return invocationExpression.Expression as MemberAccessExpressionSyntax; } - private static SyntaxNode? GetParentMemberExpression(SyntaxNode invocationExpressionSyntax) + private static ExpressionSyntax? GetParentMemberExpression(SyntaxNode invocationExpressionSyntax) { var memberAccessExpression = GetMemberAccessExpression(invocationExpressionSyntax); if (memberAccessExpression == null) @@ -656,25 +655,14 @@ private static SyntaxNode ReplaceParameter(IAnonymousFunctionOperation method, s return memberAccessExpression.Expression; } - private sealed class ParameterRewriter : CSharpSyntaxRewriter + private sealed class ParameterRewriter(SemanticModel semanticModel, IParameterSymbol parameterSymbol, string newParameterName) : CSharpSyntaxRewriter { - private readonly SemanticModel _semanticModel; - private readonly IParameterSymbol _parameterSymbol; - private readonly string _newParameterName; - - public ParameterRewriter(SemanticModel semanticModel, IParameterSymbol parameterSymbol, string newParameterName) - { - _semanticModel = semanticModel; - _parameterSymbol = parameterSymbol; - _newParameterName = newParameterName; - } - public override SyntaxNode? VisitIdentifierName(IdentifierNameSyntax node) { - var symbol = _semanticModel.GetSymbolInfo(node).Symbol; - if (symbol != null && symbol.IsEqualTo(_parameterSymbol)) + var symbol = semanticModel.GetSymbolInfo(node).Symbol; + if (symbol != null && symbol.IsEqualTo(parameterSymbol)) { - return IdentifierName(_newParameterName); + return IdentifierName(newParameterName); } return base.VisitIdentifierName(node); diff --git a/src/Meziantou.Analyzer.CodeFixers/Rules/UseIsPatternInsteadOfSequenceEqualFixer.cs b/src/Meziantou.Analyzer.CodeFixers/Rules/UseIsPatternInsteadOfSequenceEqualFixer.cs index a30290358..99178540d 100644 --- a/src/Meziantou.Analyzer.CodeFixers/Rules/UseIsPatternInsteadOfSequenceEqualFixer.cs +++ b/src/Meziantou.Analyzer.CodeFixers/Rules/UseIsPatternInsteadOfSequenceEqualFixer.cs @@ -36,8 +36,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) private static async Task UseIs(Document document, SyntaxNode nodeToFix, CancellationToken cancellationToken) { var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); - var operation = editor.SemanticModel.GetOperation(nodeToFix, cancellationToken) as IInvocationOperation; - if (operation == null) + if (editor.SemanticModel.GetOperation(nodeToFix, cancellationToken) is not IInvocationOperation operation) return document; var newExpression = SyntaxFactory.IsPatternExpression((ExpressionSyntax)operation.Arguments[0].Value.Syntax, SyntaxFactory.ConstantPattern((ExpressionSyntax)operation.Arguments[1].Value.Syntax)); diff --git a/src/Meziantou.Analyzer.CodeFixers/Rules/UseRegexSourceGeneratorFixer.cs b/src/Meziantou.Analyzer.CodeFixers/Rules/UseRegexSourceGeneratorFixer.cs index 1a50b9e91..76bd641c7 100644 --- a/src/Meziantou.Analyzer.CodeFixers/Rules/UseRegexSourceGeneratorFixer.cs +++ b/src/Meziantou.Analyzer.CodeFixers/Rules/UseRegexSourceGeneratorFixer.cs @@ -165,9 +165,9 @@ private static async Task ConvertToSourceGenerator(Document document, // Extract arguments (pattern,options,timeout) var attributes = generator.Attribute(generator.TypeExpression(regexGeneratorAttributeSymbol), attributeArguments: (patternValue, regexOptionsValue, timeoutValue) switch { - ({ }, null, null) => new[] { patternValue }, - ({ }, { }, null) => new[] { patternValue, regexOptionsValue }, - ({ }, { }, { }) => new[] { patternValue, regexOptionsValue, AttributeArgument((ExpressionSyntax)timeoutValue).WithNameColon(NameColon(IdentifierName("matchTimeoutMilliseconds"))) }, + ({ }, null, null) => [patternValue], + ({ }, { }, null) => [patternValue, regexOptionsValue], + ({ }, { }, { }) => [patternValue, regexOptionsValue, AttributeArgument((ExpressionSyntax)timeoutValue).WithNameColon(NameColon(IdentifierName("matchTimeoutMilliseconds")))], _ => Array.Empty(), }); diff --git a/src/Meziantou.Analyzer.CodeFixers/Rules/ValidateArgumentsCorrectlyFixer.cs b/src/Meziantou.Analyzer.CodeFixers/Rules/ValidateArgumentsCorrectlyFixer.cs index 1b979b12a..9adb47cfb 100644 --- a/src/Meziantou.Analyzer.CodeFixers/Rules/ValidateArgumentsCorrectlyFixer.cs +++ b/src/Meziantou.Analyzer.CodeFixers/Rules/ValidateArgumentsCorrectlyFixer.cs @@ -10,7 +10,6 @@ using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Differencing; using Microsoft.CodeAnalysis.Editing; using Microsoft.CodeAnalysis.Formatting; using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory; diff --git a/src/Meziantou.Analyzer/Internals/AwaitableTypes.cs b/src/Meziantou.Analyzer/Internals/AwaitableTypes.cs index e77c85234..24c71adc7 100644 --- a/src/Meziantou.Analyzer/Internals/AwaitableTypes.cs +++ b/src/Meziantou.Analyzer/Internals/AwaitableTypes.cs @@ -1,5 +1,4 @@ -using System; -using System.Collections.Generic; +using System.Collections.Generic; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Operations; @@ -28,7 +27,7 @@ public AwaitableTypes(Compilation compilation) } else { - _taskOrValueTaskSymbols = Array.Empty(); + _taskOrValueTaskSymbols = []; } } diff --git a/src/Meziantou.Analyzer/Internals/CultureSensitiveFormattingContext.cs b/src/Meziantou.Analyzer/Internals/CultureSensitiveFormattingContext.cs index 29fa7189f..09973478c 100644 --- a/src/Meziantou.Analyzer/Internals/CultureSensitiveFormattingContext.cs +++ b/src/Meziantou.Analyzer/Internals/CultureSensitiveFormattingContext.cs @@ -1,52 +1,29 @@ using System.Linq; -using System.Security.Cryptography; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Operations; namespace Meziantou.Analyzer.Internals; -internal sealed class CultureSensitiveFormattingContext +internal sealed class CultureSensitiveFormattingContext(Compilation compilation) { - public CultureSensitiveFormattingContext(Compilation compilation) - { - FormatProviderSymbol = compilation.GetBestTypeByMetadataName("System.IFormatProvider"); - CultureInfoSymbol = compilation.GetBestTypeByMetadataName("System.Globalization.CultureInfo"); - NumberStyleSymbol = compilation.GetBestTypeByMetadataName("System.Globalization.NumberStyles"); - DateTimeStyleSymbol = compilation.GetBestTypeByMetadataName("System.Globalization.DateTimeStyles"); - StringBuilderSymbol = compilation.GetBestTypeByMetadataName("System.Text.StringBuilder"); - StringBuilder_AppendInterpolatedStringHandlerSymbol = compilation.GetBestTypeByMetadataName("System.Text.StringBuilder+AppendInterpolatedStringHandler"); - GuidSymbol = compilation.GetBestTypeByMetadataName("System.Guid"); - EnumSymbol = compilation.GetBestTypeByMetadataName("System.Enum"); - DateTimeOffsetSymbol = compilation.GetBestTypeByMetadataName("System.DateTimeOffset"); - DateOnlySymbol = compilation.GetBestTypeByMetadataName("System.DateOnly"); - TimeOnlySymbol = compilation.GetBestTypeByMetadataName("System.TimeOnly"); - UInt128Symbol = compilation.GetBestTypeByMetadataName("System.UInt128"); - UriSymbol = compilation.GetBestTypeByMetadataName("System.Uri"); - TimeSpanSymbol = compilation.GetBestTypeByMetadataName("System.TimeSpan"); - VersionSymbol = compilation.GetBestTypeByMetadataName("System.Version"); - SystemIFormattableSymbol = compilation.GetBestTypeByMetadataName("System.IFormattable"); - SystemWindowsFontStretchSymbol = compilation.GetBestTypeByMetadataName("System.Windows.FontStretch"); - SystemWindowsMediaBrushSymbol = compilation.GetBestTypeByMetadataName("System.Windows.Media.Brush"); - } - - public INamedTypeSymbol? FormatProviderSymbol { get; } - public INamedTypeSymbol? CultureInfoSymbol { get; } - public INamedTypeSymbol? NumberStyleSymbol { get; } - public INamedTypeSymbol? DateTimeStyleSymbol { get; } - public INamedTypeSymbol? StringBuilderSymbol { get; } - public INamedTypeSymbol? StringBuilder_AppendInterpolatedStringHandlerSymbol { get; } - public INamedTypeSymbol? GuidSymbol { get; } - public INamedTypeSymbol? EnumSymbol { get; } - public INamedTypeSymbol? DateTimeOffsetSymbol { get; } - public INamedTypeSymbol? DateOnlySymbol { get; } - public INamedTypeSymbol? TimeOnlySymbol { get; } - public INamedTypeSymbol? UInt128Symbol { get; } - public INamedTypeSymbol? UriSymbol { get; } - public INamedTypeSymbol? TimeSpanSymbol { get; } - public INamedTypeSymbol? VersionSymbol { get; } - public INamedTypeSymbol? SystemIFormattableSymbol { get; } - public INamedTypeSymbol? SystemWindowsFontStretchSymbol { get; } - public INamedTypeSymbol? SystemWindowsMediaBrushSymbol { get; } + public INamedTypeSymbol? FormatProviderSymbol { get; } = compilation.GetBestTypeByMetadataName("System.IFormatProvider"); + public INamedTypeSymbol? CultureInfoSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Globalization.CultureInfo"); + public INamedTypeSymbol? NumberStyleSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Globalization.NumberStyles"); + public INamedTypeSymbol? DateTimeStyleSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Globalization.DateTimeStyles"); + public INamedTypeSymbol? StringBuilderSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Text.StringBuilder"); + public INamedTypeSymbol? StringBuilder_AppendInterpolatedStringHandlerSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Text.StringBuilder+AppendInterpolatedStringHandler"); + public INamedTypeSymbol? GuidSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Guid"); + public INamedTypeSymbol? EnumSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Enum"); + public INamedTypeSymbol? DateTimeOffsetSymbol { get; } = compilation.GetBestTypeByMetadataName("System.DateTimeOffset"); + public INamedTypeSymbol? DateOnlySymbol { get; } = compilation.GetBestTypeByMetadataName("System.DateOnly"); + public INamedTypeSymbol? TimeOnlySymbol { get; } = compilation.GetBestTypeByMetadataName("System.TimeOnly"); + public INamedTypeSymbol? UInt128Symbol { get; } = compilation.GetBestTypeByMetadataName("System.UInt128"); + public INamedTypeSymbol? UriSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Uri"); + public INamedTypeSymbol? TimeSpanSymbol { get; } = compilation.GetBestTypeByMetadataName("System.TimeSpan"); + public INamedTypeSymbol? VersionSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Version"); + public INamedTypeSymbol? SystemIFormattableSymbol { get; } = compilation.GetBestTypeByMetadataName("System.IFormattable"); + public INamedTypeSymbol? SystemWindowsFontStretchSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Windows.FontStretch"); + public INamedTypeSymbol? SystemWindowsMediaBrushSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Windows.Media.Brush"); private static bool MustUnwrapNullableOfT(CultureSensitiveOptions options) { diff --git a/src/Meziantou.Analyzer/Internals/MethodSymbolExtensions.cs b/src/Meziantou.Analyzer/Internals/MethodSymbolExtensions.cs index 62f3477e6..bd84b656f 100644 --- a/src/Meziantou.Analyzer/Internals/MethodSymbolExtensions.cs +++ b/src/Meziantou.Analyzer/Internals/MethodSymbolExtensions.cs @@ -5,9 +5,9 @@ namespace Meziantou.Analyzer; internal static class MethodSymbolExtensions { - private static readonly string[] s_msTestNamespaceParts = new[] { "Microsoft", "VisualStudio", "TestTools", "UnitTesting" }; - private static readonly string[] s_nunitNamespaceParts = new[] { "NUnit", "Framework" }; - private static readonly string[] s_xunitNamespaceParts = new[] { "Xunit" }; + private static readonly string[] s_msTestNamespaceParts = ["Microsoft", "VisualStudio", "TestTools", "UnitTesting"]; + private static readonly string[] s_nunitNamespaceParts = ["NUnit", "Framework"]; + private static readonly string[] s_xunitNamespaceParts = ["Xunit"]; public static bool IsInterfaceImplementation(this IMethodSymbol method) { diff --git a/src/Meziantou.Analyzer/Internals/OperationUtilities.cs b/src/Meziantou.Analyzer/Internals/OperationUtilities.cs index bd956d70c..8ca37f6ea 100644 --- a/src/Meziantou.Analyzer/Internals/OperationUtilities.cs +++ b/src/Meziantou.Analyzer/Internals/OperationUtilities.cs @@ -3,14 +3,9 @@ namespace Meziantou.Analyzer; -internal sealed class OperationUtilities +internal sealed class OperationUtilities(Compilation compilation) { - private readonly INamedTypeSymbol? _expressionSymbol; - - public OperationUtilities(Compilation compilation) - { - _expressionSymbol = compilation.GetBestTypeByMetadataName("System.Linq.Expressions.Expression"); - } + private readonly INamedTypeSymbol? _expressionSymbol = compilation.GetBestTypeByMetadataName("System.Linq.Expressions.Expression"); public bool IsInExpressionContext(IOperation operation) { diff --git a/src/Meziantou.Analyzer/Internals/OverloadFinder.cs b/src/Meziantou.Analyzer/Internals/OverloadFinder.cs index cb8c39f92..964128ac1 100644 --- a/src/Meziantou.Analyzer/Internals/OverloadFinder.cs +++ b/src/Meziantou.Analyzer/Internals/OverloadFinder.cs @@ -3,16 +3,9 @@ using Microsoft.CodeAnalysis; namespace Meziantou.Analyzer.Internals; -internal sealed class OverloadFinder +internal sealed class OverloadFinder(Compilation compilation) { - private readonly ITypeSymbol? _obsoleteSymbol; - private readonly Compilation _compilation; - - public OverloadFinder(Compilation compilation) - { - _compilation = compilation; - _obsoleteSymbol = compilation.GetBestTypeByMetadataName("System.ObsoleteAttribute"); - } + private readonly ITypeSymbol? _obsoleteSymbol = compilation.GetBestTypeByMetadataName("System.ObsoleteAttribute"); public bool HasOverloadWithAdditionalParameterOfType( IMethodSymbol methodSymbol, @@ -75,7 +68,7 @@ public bool HasOverloadWithAdditionalParameterOfType( ImmutableArray members; if (syntaxNode != null) { - var semanticModel = _compilation.GetSemanticModel(syntaxNode.SyntaxTree); + var semanticModel = compilation.GetSemanticModel(syntaxNode.SyntaxTree); members = semanticModel.LookupSymbols(syntaxNode.GetLocation().SourceSpan.End, methodSymbol.ContainingType, methodSymbol.Name, includeReducedExtensionMethods: true); } else diff --git a/src/Meziantou.Analyzer/Internals/StringExtensions.cs b/src/Meziantou.Analyzer/Internals/StringExtensions.cs index 44eb66693..9776fe068 100644 --- a/src/Meziantou.Analyzer/Internals/StringExtensions.cs +++ b/src/Meziantou.Analyzer/Internals/StringExtensions.cs @@ -30,8 +30,8 @@ public bool MoveNext() var index = span.IndexOfAny('\r', '\n'); if (index == -1) { - _str = ReadOnlySpan.Empty; - Current = new LineSplitEntry(span, ReadOnlySpan.Empty); + _str = []; + Current = new LineSplitEntry(span, []); return true; } diff --git a/src/Meziantou.Analyzer/Internals/TypeSymbolExtensions.cs b/src/Meziantou.Analyzer/Internals/TypeSymbolExtensions.cs index 7d74ac2d0..5359acadc 100644 --- a/src/Meziantou.Analyzer/Internals/TypeSymbolExtensions.cs +++ b/src/Meziantou.Analyzer/Internals/TypeSymbolExtensions.cs @@ -8,9 +8,9 @@ namespace Meziantou.Analyzer; // http://source.roslyn.io/#Microsoft.CodeAnalysis.Workspaces/Shared/Extensions/ITypeSymbolExtensions.cs,190b4ed0932458fd,references internal static class TypeSymbolExtensions { - private static readonly string[] Microsoft_VisualStudio_TestTools_UnitTesting = { "Microsoft", "VisualStudio", "TestTools", "UnitTesting" }; - private static readonly string[] NUnit_Framework = { "NUnit", "Framework" }; - private static readonly string[] Xunit = { "Xunit" }; + private static readonly string[] Microsoft_VisualStudio_TestTools_UnitTesting = ["Microsoft", "VisualStudio", "TestTools", "UnitTesting"]; + private static readonly string[] NUnit_Framework = ["NUnit", "Framework"]; + private static readonly string[] Xunit = ["Xunit"]; public static IList GetAllInterfacesIncludingThis(this ITypeSymbol type) { diff --git a/src/Meziantou.Analyzer/Meziantou.Analyzer.csproj b/src/Meziantou.Analyzer/Meziantou.Analyzer.csproj index b698f1042..379f8f45a 100644 --- a/src/Meziantou.Analyzer/Meziantou.Analyzer.csproj +++ b/src/Meziantou.Analyzer/Meziantou.Analyzer.csproj @@ -1,6 +1,6 @@  - net7.0;netstandard2.0 + net8.0;netstandard2.0 false 1.0.1 @@ -31,7 +31,7 @@ analyzers - + all analyzers diff --git a/src/Meziantou.Analyzer/Rules/ArgumentExceptionShouldSpecifyArgumentNameAnalyzerCommon.cs b/src/Meziantou.Analyzer/Rules/ArgumentExceptionShouldSpecifyArgumentNameAnalyzerCommon.cs index b354bf9f5..a490a393d 100644 --- a/src/Meziantou.Analyzer/Rules/ArgumentExceptionShouldSpecifyArgumentNameAnalyzerCommon.cs +++ b/src/Meziantou.Analyzer/Rules/ArgumentExceptionShouldSpecifyArgumentNameAnalyzerCommon.cs @@ -1,14 +1,4 @@ -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Linq; -using System.Threading; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Operations; - -namespace Meziantou.Analyzer.Rules; +namespace Meziantou.Analyzer.Rules; internal static class ArgumentExceptionShouldSpecifyArgumentNameAnalyzerCommon { diff --git a/src/Meziantou.Analyzer/Rules/AvoidUsingRedundantElseAnalyzerCommon.cs b/src/Meziantou.Analyzer/Rules/AvoidUsingRedundantElseAnalyzerCommon.cs index cecafd131..d2a756935 100644 --- a/src/Meziantou.Analyzer/Rules/AvoidUsingRedundantElseAnalyzerCommon.cs +++ b/src/Meziantou.Analyzer/Rules/AvoidUsingRedundantElseAnalyzerCommon.cs @@ -1,10 +1,6 @@ using System.Collections.Generic; -using System.Collections.Immutable; -using System.Linq; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using Microsoft.CodeAnalysis.Diagnostics; namespace Meziantou.Analyzer.Rules; diff --git a/src/Meziantou.Analyzer/Rules/AwaitTaskBeforeDisposingResourcesAnalyzer.cs b/src/Meziantou.Analyzer/Rules/AwaitTaskBeforeDisposingResourcesAnalyzer.cs index ba304860d..ecfdfe8eb 100644 --- a/src/Meziantou.Analyzer/Rules/AwaitTaskBeforeDisposingResourcesAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/AwaitTaskBeforeDisposingResourcesAnalyzer.cs @@ -34,24 +34,14 @@ public override void Initialize(AnalysisContext context) }); } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(Compilation compilation) { - private readonly AwaitableTypes _awaitableTypes; + private readonly AwaitableTypes _awaitableTypes = new AwaitableTypes(compilation); - public AnalyzerContext(Compilation compilation) - { - _awaitableTypes = new AwaitableTypes(compilation); - - TaskSymbol = compilation.GetBestTypeByMetadataName("System.Threading.Tasks.Task"); - TaskOfTSymbol = compilation.GetBestTypeByMetadataName("System.Threading.Tasks.Task`1"); - ValueTaskSymbol = compilation.GetBestTypeByMetadataName("System.Threading.Tasks.ValueTask"); - ValueTaskOfTSymbol = compilation.GetBestTypeByMetadataName("System.Threading.Tasks.ValueTask`1"); - } - - public INamedTypeSymbol? TaskSymbol { get; set; } - public INamedTypeSymbol? TaskOfTSymbol { get; set; } - public INamedTypeSymbol? ValueTaskSymbol { get; set; } - public INamedTypeSymbol? ValueTaskOfTSymbol { get; set; } + public INamedTypeSymbol? TaskSymbol { get; set; } = compilation.GetBestTypeByMetadataName("System.Threading.Tasks.Task"); + public INamedTypeSymbol? TaskOfTSymbol { get; set; } = compilation.GetBestTypeByMetadataName("System.Threading.Tasks.Task`1"); + public INamedTypeSymbol? ValueTaskSymbol { get; set; } = compilation.GetBestTypeByMetadataName("System.Threading.Tasks.ValueTask"); + public INamedTypeSymbol? ValueTaskOfTSymbol { get; set; } = compilation.GetBestTypeByMetadataName("System.Threading.Tasks.ValueTask`1"); public void AnalyzeReturn(OperationAnalysisContext context) { diff --git a/src/Meziantou.Analyzer/Rules/ClassMustBeSealedAnalyzer.cs b/src/Meziantou.Analyzer/Rules/ClassMustBeSealedAnalyzer.cs index b8afb3248..19f394a59 100644 --- a/src/Meziantou.Analyzer/Rules/ClassMustBeSealedAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/ClassMustBeSealedAnalyzer.cs @@ -39,21 +39,14 @@ public override void Initialize(AnalysisContext context) }); } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(Compilation compilation) { - private readonly List _potentialClasses = new(); + private readonly List _potentialClasses = []; private readonly ConcurrentHashSet _cannotBeSealedClasses = new(SymbolEqualityComparer.Default); - private INamedTypeSymbol? ExceptionSymbol { get; } - private INamedTypeSymbol? ComImportSymbol { get; } - private INamedTypeSymbol? BenchmarkSymbol { get; } - - public AnalyzerContext(Compilation compilation) - { - ExceptionSymbol = compilation.GetBestTypeByMetadataName("System.Exception"); - ComImportSymbol = compilation.GetBestTypeByMetadataName("System.Runtime.InteropServices.ComImportAttribute"); - BenchmarkSymbol = compilation.GetBestTypeByMetadataName("BenchmarkDotNet.Attributes.BenchmarkAttribute"); - } + private INamedTypeSymbol? ExceptionSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Exception"); + private INamedTypeSymbol? ComImportSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Runtime.InteropServices.ComImportAttribute"); + private INamedTypeSymbol? BenchmarkSymbol { get; } = compilation.GetBestTypeByMetadataName("BenchmarkDotNet.Attributes.BenchmarkAttribute"); public void AnalyzeNamedTypeSymbol(SymbolAnalysisContext context) { diff --git a/src/Meziantou.Analyzer/Rules/ConstructorArgumentParametersShouldExistInConstructorsAnalyzer.cs b/src/Meziantou.Analyzer/Rules/ConstructorArgumentParametersShouldExistInConstructorsAnalyzer.cs index 64bac1b9b..f8afaf76b 100644 --- a/src/Meziantou.Analyzer/Rules/ConstructorArgumentParametersShouldExistInConstructorsAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/ConstructorArgumentParametersShouldExistInConstructorsAnalyzer.cs @@ -36,14 +36,9 @@ public override void Initialize(AnalysisContext context) }); } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(Compilation compilation) { - public ISymbol? ConstructorArgumentSymbol { get; } - - public AnalyzerContext(Compilation compilation) - { - ConstructorArgumentSymbol = compilation.GetBestTypeByMetadataName("System.Windows.Markup.ConstructorArgumentAttribute"); - } + public ISymbol? ConstructorArgumentSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Windows.Markup.ConstructorArgumentAttribute"); public bool IsValid => ConstructorArgumentSymbol != null; diff --git a/src/Meziantou.Analyzer/Rules/DoNotNaNInComparisonsAnalyzer.cs b/src/Meziantou.Analyzer/Rules/DoNotNaNInComparisonsAnalyzer.cs index fd8cfe28b..1b079e161 100644 --- a/src/Meziantou.Analyzer/Rules/DoNotNaNInComparisonsAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/DoNotNaNInComparisonsAnalyzer.cs @@ -33,18 +33,11 @@ public override void Initialize(AnalysisContext context) }); } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(Compilation compilation) { - public ISymbol? DoubleNaN { get; } - public ISymbol? SingleNaN { get; } - public ISymbol? HalfNaN { get; } - - public AnalyzerContext(Compilation compilation) - { - DoubleNaN = compilation.GetBestTypeByMetadataName("System.Double")?.GetMembers("NaN").FirstOrDefault(); - SingleNaN = compilation.GetBestTypeByMetadataName("System.Single")?.GetMembers("NaN").FirstOrDefault(); - HalfNaN = compilation.GetBestTypeByMetadataName("System.Half")?.GetMembers("NaN").FirstOrDefault(); - } + public ISymbol? DoubleNaN { get; } = compilation.GetBestTypeByMetadataName("System.Double")?.GetMembers("NaN").FirstOrDefault(); + public ISymbol? SingleNaN { get; } = compilation.GetBestTypeByMetadataName("System.Single")?.GetMembers("NaN").FirstOrDefault(); + public ISymbol? HalfNaN { get; } = compilation.GetBestTypeByMetadataName("System.Half")?.GetMembers("NaN").FirstOrDefault(); public void AnalyzeBinaryOperator(OperationAnalysisContext context) { diff --git a/src/Meziantou.Analyzer/Rules/DoNotOverwriteRazorComponentParameterValue.cs b/src/Meziantou.Analyzer/Rules/DoNotOverwriteRazorComponentParameterValue.cs index fe1fcf7e8..902cdfd4e 100644 --- a/src/Meziantou.Analyzer/Rules/DoNotOverwriteRazorComponentParameterValue.cs +++ b/src/Meziantou.Analyzer/Rules/DoNotOverwriteRazorComponentParameterValue.cs @@ -91,8 +91,7 @@ internal void OperationBlockStart(OperationBlockStartAnalysisContext context) private void AnalyzeAssignment(OperationAnalysisContext context) { var operation = (IAssignmentOperation)context.Operation; - var property = operation.Target as IPropertyReferenceOperation; - if (property == null) + if (operation.Target is not IPropertyReferenceOperation property) return; // this.Property diff --git a/src/Meziantou.Analyzer/Rules/DoNotUseBlockingCallInAsyncContextAnalyzer.cs b/src/Meziantou.Analyzer/Rules/DoNotUseBlockingCallInAsyncContextAnalyzer.cs index ffbb49748..73883937e 100644 --- a/src/Meziantou.Analyzer/Rules/DoNotUseBlockingCallInAsyncContextAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/DoNotUseBlockingCallInAsyncContextAnalyzer.cs @@ -76,7 +76,7 @@ public Context(Compilation compilation) } else { - ConsoleErrorAndOutSymbols = Array.Empty(); + ConsoleErrorAndOutSymbols = []; } ProcessSymbol = compilation.GetBestTypeByMetadataName("System.Diagnostics.Process"); diff --git a/src/Meziantou.Analyzer/Rules/DoNotUseEqualityOperatorsForSpanOfCharAnalyzer.cs b/src/Meziantou.Analyzer/Rules/DoNotUseEqualityOperatorsForSpanOfCharAnalyzer.cs index ef828046f..28df24e74 100644 --- a/src/Meziantou.Analyzer/Rules/DoNotUseEqualityOperatorsForSpanOfCharAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/DoNotUseEqualityOperatorsForSpanOfCharAnalyzer.cs @@ -37,16 +37,9 @@ public override void Initialize(AnalysisContext context) }); } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(Compilation compilation, params INamedTypeSymbol?[] spanTypes) { - private readonly OperationUtilities _operationUtilities; - private readonly INamedTypeSymbol?[] _spanTypes; - - public AnalyzerContext(Compilation compilation, params INamedTypeSymbol?[] spanTypes) - { - _operationUtilities = new OperationUtilities(compilation); - _spanTypes = spanTypes; - } + private readonly OperationUtilities _operationUtilities = new(compilation); public void AnalyzeBinaryOperator(OperationAnalysisContext context) { @@ -68,7 +61,7 @@ public void AnalyzeBinaryOperator(OperationAnalysisContext context) private bool IsSpanOfString(ITypeSymbol? symbol) { - return symbol != null && symbol.IsEqualToAny(_spanTypes); + return symbol != null && symbol.IsEqualToAny(spanTypes); } } } diff --git a/src/Meziantou.Analyzer/Rules/DoNotUseImplicitCultureSensitiveToStringAnalyzer.cs b/src/Meziantou.Analyzer/Rules/DoNotUseImplicitCultureSensitiveToStringAnalyzer.cs index f3571ab42..4239bc416 100644 --- a/src/Meziantou.Analyzer/Rules/DoNotUseImplicitCultureSensitiveToStringAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/DoNotUseImplicitCultureSensitiveToStringAnalyzer.cs @@ -58,14 +58,9 @@ public override void Initialize(AnalysisContext context) }); } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(Compilation compilation) { - private readonly CultureSensitiveFormattingContext _cultureSensitiveContext; - - public AnalyzerContext(Compilation compilation) - { - _cultureSensitiveContext = new CultureSensitiveFormattingContext(compilation); - } + private readonly CultureSensitiveFormattingContext _cultureSensitiveContext = new CultureSensitiveFormattingContext(compilation); public static void AnalyzeInvocation(OperationAnalysisContext context) { diff --git a/src/Meziantou.Analyzer/Rules/DoNotUseUnknownParameterForRazorComponentAnalyzer.cs b/src/Meziantou.Analyzer/Rules/DoNotUseUnknownParameterForRazorComponentAnalyzer.cs index 538d7be0f..98c1a869c 100644 --- a/src/Meziantou.Analyzer/Rules/DoNotUseUnknownParameterForRazorComponentAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/DoNotUseUnknownParameterForRazorComponentAnalyzer.cs @@ -37,24 +37,16 @@ public override void Initialize(AnalysisContext context) }); } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(Compilation compilation) { private readonly ConcurrentDictionary _componentDescriptors = new(SymbolEqualityComparer.Default); - public AnalyzerContext(Compilation compilation) - { - IComponentSymbol = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Components.IComponent"); - ParameterSymbol = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Components.ParameterAttribute"); - RenderTreeBuilderSymbol = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder"); - ComponentBaseSymbol = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Components.ComponentBase"); - } - public bool IsValid => IComponentSymbol != null && ComponentBaseSymbol != null && ParameterSymbol != null; - public INamedTypeSymbol? IComponentSymbol { get; } - public INamedTypeSymbol? ComponentBaseSymbol { get; } - public INamedTypeSymbol? ParameterSymbol { get; } - public INamedTypeSymbol? RenderTreeBuilderSymbol { get; } + public INamedTypeSymbol? IComponentSymbol { get; } = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Components.IComponent"); + public INamedTypeSymbol? ComponentBaseSymbol { get; } = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Components.ComponentBase"); + public INamedTypeSymbol? ParameterSymbol { get; } = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Components.ParameterAttribute"); + public INamedTypeSymbol? RenderTreeBuilderSymbol { get; } = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder"); public void AnalyzeBlockOptions(OperationAnalysisContext context) { diff --git a/src/Meziantou.Analyzer/Rules/DotNotUseNameFromBCLAnalyzer.cs b/src/Meziantou.Analyzer/Rules/DotNotUseNameFromBCLAnalyzer.cs index 7e1ef8c4a..96f612486 100644 --- a/src/Meziantou.Analyzer/Rules/DotNotUseNameFromBCLAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/DotNotUseNameFromBCLAnalyzer.cs @@ -82,7 +82,7 @@ private static Dictionary> LoadTypes(bool preview) if (!types.TryGetValue(name, out var list)) { - list = new List(); + list = []; types.Add(name, list); } diff --git a/src/Meziantou.Analyzer/Rules/EqualityShouldBeCorrectlyImplementedAnalyzer.cs b/src/Meziantou.Analyzer/Rules/EqualityShouldBeCorrectlyImplementedAnalyzer.cs index 43a55fb3e..987b058da 100644 --- a/src/Meziantou.Analyzer/Rules/EqualityShouldBeCorrectlyImplementedAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/EqualityShouldBeCorrectlyImplementedAnalyzer.cs @@ -79,18 +79,11 @@ public override void Initialize(AnalysisContext context) }); } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(Compilation compilation) { - public AnalyzerContext(Compilation compilation) - { - IComparableSymbol = compilation.GetBestTypeByMetadataName("System.IComparable"); - IComparableOfTSymbol = compilation.GetBestTypeByMetadataName("System.IComparable`1"); - IEquatableOfTSymbol = compilation.GetBestTypeByMetadataName("System.IEquatable`1"); - } - - public INamedTypeSymbol? IComparableSymbol { get; set; } - public INamedTypeSymbol? IComparableOfTSymbol { get; set; } - public INamedTypeSymbol? IEquatableOfTSymbol { get; set; } + public INamedTypeSymbol? IComparableSymbol { get; set; } = compilation.GetBestTypeByMetadataName("System.IComparable"); + public INamedTypeSymbol? IComparableOfTSymbol { get; set; } = compilation.GetBestTypeByMetadataName("System.IComparable`1"); + public INamedTypeSymbol? IEquatableOfTSymbol { get; set; } = compilation.GetBestTypeByMetadataName("System.IEquatable`1"); public void AnalyzeSymbol(SymbolAnalysisContext context) { diff --git a/src/Meziantou.Analyzer/Rules/EqualityShouldBeCorrectlyImplementedAnalyzerCommon.cs b/src/Meziantou.Analyzer/Rules/EqualityShouldBeCorrectlyImplementedAnalyzerCommon.cs index eceb992f2..84e8839e7 100644 --- a/src/Meziantou.Analyzer/Rules/EqualityShouldBeCorrectlyImplementedAnalyzerCommon.cs +++ b/src/Meziantou.Analyzer/Rules/EqualityShouldBeCorrectlyImplementedAnalyzerCommon.cs @@ -1,9 +1,5 @@ using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Linq; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; namespace Meziantou.Analyzer.Rules; diff --git a/src/Meziantou.Analyzer/Rules/FixToDoAnalyzer.cs b/src/Meziantou.Analyzer/Rules/FixToDoAnalyzer.cs index fc2bd9916..991afba32 100644 --- a/src/Meziantou.Analyzer/Rules/FixToDoAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/FixToDoAnalyzer.cs @@ -23,7 +23,7 @@ public sealed class FixToDoAnalyzer : DiagnosticAnalyzer public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(s_rule); - private static readonly char[] TrimStartChars = new[] { ' ', '\t', '*', '-', '/' }; + private static readonly char[] TrimStartChars = [' ', '\t', '*', '-', '/']; public override void Initialize(AnalysisContext context) { diff --git a/src/Meziantou.Analyzer/Rules/IfElseBranchesAreIdenticalAnalyzer.cs b/src/Meziantou.Analyzer/Rules/IfElseBranchesAreIdenticalAnalyzer.cs index 148abef21..f88b21c0b 100644 --- a/src/Meziantou.Analyzer/Rules/IfElseBranchesAreIdenticalAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/IfElseBranchesAreIdenticalAnalyzer.cs @@ -1,6 +1,5 @@ using System.Collections.Immutable; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; diff --git a/src/Meziantou.Analyzer/Rules/JSInvokableMethodsMustBePublicAnalyzer.cs b/src/Meziantou.Analyzer/Rules/JSInvokableMethodsMustBePublicAnalyzer.cs index 0edeb95de..067188b3c 100644 --- a/src/Meziantou.Analyzer/Rules/JSInvokableMethodsMustBePublicAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/JSInvokableMethodsMustBePublicAnalyzer.cs @@ -34,14 +34,9 @@ public override void Initialize(AnalysisContext context) }); } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(Compilation compilation) { - public AnalyzerContext(Compilation compilation) - { - JsInvokableSymbol = compilation.GetBestTypeByMetadataName("Microsoft.JSInterop.JSInvokableAttribute"); - } - - public INamedTypeSymbol? JsInvokableSymbol { get; } + public INamedTypeSymbol? JsInvokableSymbol { get; } = compilation.GetBestTypeByMetadataName("Microsoft.JSInterop.JSInvokableAttribute"); public bool IsValid => JsInvokableSymbol != null; diff --git a/src/Meziantou.Analyzer/Rules/LoggerParameterTypeAnalyzer.cs b/src/Meziantou.Analyzer/Rules/LoggerParameterTypeAnalyzer.cs index 4bafa109d..259c103d0 100644 --- a/src/Meziantou.Analyzer/Rules/LoggerParameterTypeAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/LoggerParameterTypeAnalyzer.cs @@ -88,7 +88,7 @@ public override void Initialize(AnalysisContext context) private sealed class AnalyzerContext { private static readonly HashSet SerilogLogMethodNames = new(StringComparer.Ordinal) { "Debug", "Information", "Error", "Fatal", "Verbose", "Warning", "Write" }; - private static readonly char[] SerilogPrefixes = { '@', '$' }; + private static readonly char[] SerilogPrefixes = ['@', '$']; [SuppressMessage("MicrosoftCodeAnalysisPerformance", "RS1013:Start action has no registered non-end actions", Justification = "")] public AnalyzerContext(CompilationStartAnalysisContext context) @@ -379,7 +379,7 @@ static int FindIndexOfTemplate(ImmutableArray arguments) if (formatExpression is not null && argumentTypes is not null) { var allowNonConstantFormat = context.Options.GetConfigurationValue(formatExpression, s_rule.Id + ".allow_non_constant_formats", defaultValue: true); - var format = AnalyzerContext.TryGetFormatText(formatExpression, allowNonConstantFormat); + var format = TryGetFormatText(formatExpression, allowNonConstantFormat); if (format == null) return; @@ -442,15 +442,15 @@ private static string RemovePrefix(string name, char[]? potentialNamePrefixes) return constantValue; case IBinaryOperation { OperatorKind: BinaryOperatorKind.Add } binary: - var leftText = AnalyzerContext.TryGetFormatText(binary.LeftOperand, allowNonConstantFormat); - var rightText = AnalyzerContext.TryGetFormatText(binary.RightOperand, allowNonConstantFormat); + var leftText = TryGetFormatText(binary.LeftOperand, allowNonConstantFormat); + var rightText = TryGetFormatText(binary.RightOperand, allowNonConstantFormat); return Concat(leftText, rightText, allowNonConstantFormat); case IInterpolatedStringOperation interpolatedString: - string? result = ""; + var result = ""; foreach (var part in interpolatedString.Parts) { - result = Concat(result, AnalyzerContext.TryGetFormatText(part, allowNonConstantFormat), allowNonConstantFormat); + result = Concat(result, TryGetFormatText(part, allowNonConstantFormat), allowNonConstantFormat); if (result == null) return null; } @@ -458,7 +458,7 @@ private static string RemovePrefix(string name, char[]? potentialNamePrefixes) return result; case IInterpolatedStringTextOperation text: - return AnalyzerContext.TryGetFormatText(text.Text, allowNonConstantFormat); + return TryGetFormatText(text.Text, allowNonConstantFormat); default: return null; @@ -504,7 +504,7 @@ methodSymbol.Name is "BeginScope" && } } - private sealed class LoggerConfigurationFile + private sealed class LoggerConfigurationFile(Dictionary configuration) { private static readonly SymbolEqualityComparer Comparer = GetComparer(); @@ -518,10 +518,10 @@ private static SymbolEqualityComparer GetComparer() var ctorParam2 = kindType.GetField("IgnoreTupleNames")?.GetValue(null); if (ctorParam1 != null && ctorParam2 != null) { - var ctor = typeof(SymbolEqualityComparer).GetConstructor(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, binder: null, new[] { kindType }, modifiers: null); + var ctor = typeof(SymbolEqualityComparer).GetConstructor(System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance, binder: null, [kindType], modifiers: null); if (ctor != null) { - return (SymbolEqualityComparer)ctor.Invoke(new object[] { (int)ctorParam1 | (int)ctorParam2 }); + return (SymbolEqualityComparer)ctor.Invoke([(int)ctorParam1 | (int)ctorParam2]); } } } @@ -529,20 +529,13 @@ private static SymbolEqualityComparer GetComparer() return SymbolEqualityComparer.Default; } - private readonly Dictionary _configuration; - - public LoggerConfigurationFile(Dictionary configuration) - { - _configuration = configuration; - } - public static LoggerConfigurationFile Empty { get; } = new LoggerConfigurationFile(new(StringComparer.Ordinal)); - public int Count => _configuration.Count; + public int Count => configuration.Count; public bool IsValid(Compilation compilation, string name, ITypeSymbol? type, out bool hasRule) { - if (_configuration.TryGetValue(name, out var validSymbols)) + if (configuration.TryGetValue(name, out var validSymbols)) { hasRule = true; @@ -568,17 +561,17 @@ public bool IsValid(Compilation compilation, string name, ITypeSymbol? type, out public ISymbol[] GetSymbols(string name) { - if (_configuration.TryGetValue(name, out var symbols)) + if (configuration.TryGetValue(name, out var symbols)) return symbols; - return Array.Empty(); + return []; } } // source: https://github.com/dotnet/roslyn-analyzers/blob/afa566573b7b1a2129d78a26f238a2ac3f8e58ef/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/LogValuesFormatter.cs private sealed class LogValuesFormatter { - private static readonly char[] FormatDelimiters = { ',', ':' }; + private static readonly char[] FormatDelimiters = [',', ':']; public LogValuesFormatter(string format) { @@ -611,7 +604,7 @@ public LogValuesFormatter(string format) } } - public List ValueNames { get; } = new List(); + public List ValueNames { get; } = []; private static int FindBraceIndex(string format, char brace, int startIndex, int endIndex) { diff --git a/src/Meziantou.Analyzer/Rules/MakeClassStaticAnalyzer.cs b/src/Meziantou.Analyzer/Rules/MakeClassStaticAnalyzer.cs index 8fa70b60e..d2eb034d5 100644 --- a/src/Meziantou.Analyzer/Rules/MakeClassStaticAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/MakeClassStaticAnalyzer.cs @@ -56,17 +56,12 @@ bool HasBaseClass() } } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(Compilation compilation) { - private readonly List _potentialClasses = new(); + private readonly List _potentialClasses = []; private readonly HashSet _cannotBeStaticClasses = new(SymbolEqualityComparer.Default); - public AnalyzerContext(Compilation compilation) - { - CoClassAttributeSymbol = compilation.GetBestTypeByMetadataName("System.Runtime.InteropServices.CoClassAttribute"); - } - - public INamedTypeSymbol? CoClassAttributeSymbol { get; } + public INamedTypeSymbol? CoClassAttributeSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Runtime.InteropServices.CoClassAttribute"); public void AnalyzeNamedTypeSymbol(SymbolAnalysisContext context) { diff --git a/src/Meziantou.Analyzer/Rules/MethodsReturningAnAwaitableTypeMustHaveTheAsyncSuffixAnalyzer.cs b/src/Meziantou.Analyzer/Rules/MethodsReturningAnAwaitableTypeMustHaveTheAsyncSuffixAnalyzer.cs index 6b4a61a02..96fbacff7 100644 --- a/src/Meziantou.Analyzer/Rules/MethodsReturningAnAwaitableTypeMustHaveTheAsyncSuffixAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/MethodsReturningAnAwaitableTypeMustHaveTheAsyncSuffixAnalyzer.cs @@ -44,14 +44,9 @@ public override void Initialize(AnalysisContext context) }); } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(Compilation compilation) { - private readonly AwaitableTypes _awaitableTypes; - - public AnalyzerContext(Compilation compilation) - { - _awaitableTypes = new AwaitableTypes(compilation); - } + private readonly AwaitableTypes _awaitableTypes = new(compilation); public void AnalyzeSymbol(SymbolAnalysisContext context) { diff --git a/src/Meziantou.Analyzer/Rules/NamedParameterAnalyzer.cs b/src/Meziantou.Analyzer/Rules/NamedParameterAnalyzer.cs index f21507b52..96a332cc7 100644 --- a/src/Meziantou.Analyzer/Rules/NamedParameterAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/NamedParameterAnalyzer.cs @@ -154,7 +154,7 @@ bool IsParams(SyntaxNode node) if (invokedMethodParameters.Length == 0) return false; - var lastParameter = invokedMethodParameters[invokedMethodParameters.Length - 1]; + var lastParameter = invokedMethodParameters[^1]; if (argumentIndex == invokedMethodParameters.Length - 1 && lastParameter.IsParams) { if (argumentList.Arguments.Count > invokedMethodParameters.Length) diff --git a/src/Meziantou.Analyzer/Rules/OptimizeLinqUsageAnalyzer.cs b/src/Meziantou.Analyzer/Rules/OptimizeLinqUsageAnalyzer.cs index d95c0253e..93f78c46f 100644 --- a/src/Meziantou.Analyzer/Rules/OptimizeLinqUsageAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/OptimizeLinqUsageAnalyzer.cs @@ -140,7 +140,7 @@ public AnalyzerContext(Compilation compilation) public bool IsValid => ExtensionMethodOwnerTypes.Count > 0; - private List ExtensionMethodOwnerTypes { get; } = new List(); + private List ExtensionMethodOwnerTypes { get; } = []; private INamedTypeSymbol? EnumerableSymbol { get; set; } private INamedTypeSymbol? QueryableSymbol { get; set; } diff --git a/src/Meziantou.Analyzer/Rules/OptionalParametersAttributeAnalyzer.cs b/src/Meziantou.Analyzer/Rules/OptionalParametersAttributeAnalyzer.cs index 00f709585..93a9ef863 100644 --- a/src/Meziantou.Analyzer/Rules/OptionalParametersAttributeAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/OptionalParametersAttributeAnalyzer.cs @@ -44,18 +44,11 @@ public override void Initialize(AnalysisContext context) }); } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(Compilation compilation) { - public AnalyzerContext(Compilation compilation) - { - OptionalAttributeSymbol = compilation.GetBestTypeByMetadataName("System.Runtime.InteropServices.OptionalAttribute"); - DefaultParameterValueAttributeSymbol = compilation.GetBestTypeByMetadataName("System.Runtime.InteropServices.DefaultParameterValueAttribute"); - DefaultValueAttributeSymbol = compilation.GetBestTypeByMetadataName("System.ComponentModel.DefaultValueAttribute"); - } - - public INamedTypeSymbol? OptionalAttributeSymbol { get; set; } - public INamedTypeSymbol? DefaultParameterValueAttributeSymbol { get; set; } - public INamedTypeSymbol? DefaultValueAttributeSymbol { get; set; } + public INamedTypeSymbol? OptionalAttributeSymbol { get; set; } = compilation.GetBestTypeByMetadataName("System.Runtime.InteropServices.OptionalAttribute"); + public INamedTypeSymbol? DefaultParameterValueAttributeSymbol { get; set; } = compilation.GetBestTypeByMetadataName("System.Runtime.InteropServices.DefaultParameterValueAttribute"); + public INamedTypeSymbol? DefaultValueAttributeSymbol { get; set; } = compilation.GetBestTypeByMetadataName("System.ComponentModel.DefaultValueAttribute"); public bool IsValid => (OptionalAttributeSymbol != null && DefaultParameterValueAttributeSymbol != null) || (DefaultParameterValueAttributeSymbol != null && DefaultValueAttributeSymbol != null); diff --git a/src/Meziantou.Analyzer/Rules/PreferReturningCollectionAbstractionInsteadOfImplementationAnalyzer.cs b/src/Meziantou.Analyzer/Rules/PreferReturningCollectionAbstractionInsteadOfImplementationAnalyzer.cs index 5819e2a0b..a27825e0a 100644 --- a/src/Meziantou.Analyzer/Rules/PreferReturningCollectionAbstractionInsteadOfImplementationAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/PreferReturningCollectionAbstractionInsteadOfImplementationAnalyzer.cs @@ -64,12 +64,12 @@ public AnalyzerContext(Compilation compilation) XmlPropertyAttributeSymbols.AddIfNotNull(compilation.GetBestTypeByMetadataName("System.Xml.Serialization.XmlTextAttribute")); } - public List ConcreteCollectionSymbols { get; } = new List(); - public List TaskSymbols { get; } = new List(); + public List ConcreteCollectionSymbols { get; } = []; + public List TaskSymbols { get; } = []; public ITypeSymbol? XmlIgnoreAttributeSymbol { get; set; } - public List XmlClassAttributeSymbols { get; } = new List(); - public List XmlPropertyAttributeSymbols { get; } = new List(); + public List XmlClassAttributeSymbols { get; } = []; + public List XmlPropertyAttributeSymbols { get; } = []; public void AnalyzeField(SyntaxNodeAnalysisContext context) { diff --git a/src/Meziantou.Analyzer/Rules/RegexUsageAnalyzerBase.cs b/src/Meziantou.Analyzer/Rules/RegexUsageAnalyzerBase.cs index 4f2a53574..1937d8f20 100644 --- a/src/Meziantou.Analyzer/Rules/RegexUsageAnalyzerBase.cs +++ b/src/Meziantou.Analyzer/Rules/RegexUsageAnalyzerBase.cs @@ -10,7 +10,7 @@ namespace Meziantou.Analyzer.Rules; public abstract class RegexUsageAnalyzerBase : DiagnosticAnalyzer { - private static readonly string[] s_methodNames = { "IsMatch", "Match", "Matches", "Replace", "Split" }; + private static readonly string[] s_methodNames = ["IsMatch", "Match", "Matches", "Replace", "Split"]; private static readonly DiagnosticDescriptor s_timeoutRule = new( RuleIdentifiers.MissingTimeoutParameterForRegex, diff --git a/src/Meziantou.Analyzer/Rules/ReturnTaskFromResultInsteadOfReturningNullAnalyzer.cs b/src/Meziantou.Analyzer/Rules/ReturnTaskFromResultInsteadOfReturningNullAnalyzer.cs index 847b991ff..43ffebebc 100644 --- a/src/Meziantou.Analyzer/Rules/ReturnTaskFromResultInsteadOfReturningNullAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/ReturnTaskFromResultInsteadOfReturningNullAnalyzer.cs @@ -1,9 +1,6 @@ using System.Collections.Immutable; using System.Diagnostics.CodeAnalysis; -using System.Threading; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; @@ -39,16 +36,10 @@ public override void Initialize(AnalysisContext context) }); } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(Compilation compilation) { - public AnalyzerContext(Compilation compilation) - { - TaskSymbol = compilation.GetBestTypeByMetadataName("System.Threading.Tasks.Task"); - TaskOfTSymbol = compilation.GetBestTypeByMetadataName("System.Threading.Tasks.Task`1"); - } - - public INamedTypeSymbol? TaskSymbol { get; } - public INamedTypeSymbol? TaskOfTSymbol { get; } + public INamedTypeSymbol? TaskSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Threading.Tasks.Task"); + public INamedTypeSymbol? TaskOfTSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Threading.Tasks.Task`1"); public void AnalyzeReturnOperation(OperationAnalysisContext context) { diff --git a/src/Meziantou.Analyzer/Rules/SequenceNumberMustBeAConstantAnalyzer.cs b/src/Meziantou.Analyzer/Rules/SequenceNumberMustBeAConstantAnalyzer.cs index ac715b3a7..dd22566d1 100644 --- a/src/Meziantou.Analyzer/Rules/SequenceNumberMustBeAConstantAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/SequenceNumberMustBeAConstantAnalyzer.cs @@ -37,7 +37,7 @@ public override void Initialize(AnalysisContext context) }); } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(Compilation compilation) { private static readonly HashSet s_renderTreeMethodNames = new(StringComparer.Ordinal) { @@ -58,14 +58,8 @@ private sealed class AnalyzerContext "AddEventStopPropagationAttribute", }; - public AnalyzerContext(Compilation compilation) - { - RenderTreeBuilderSymbol = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder"); - WebRenderTreeBuilderExtensionsSymbol = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Components.Web.WebRenderTreeBuilderExtensions"); - } - - public INamedTypeSymbol? RenderTreeBuilderSymbol { get; } - public INamedTypeSymbol? WebRenderTreeBuilderExtensionsSymbol { get; } + public INamedTypeSymbol? RenderTreeBuilderSymbol { get; } = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder"); + public INamedTypeSymbol? WebRenderTreeBuilderExtensionsSymbol { get; } = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Components.Web.WebRenderTreeBuilderExtensions"); public bool IsValid => RenderTreeBuilderSymbol != null; diff --git a/src/Meziantou.Analyzer/Rules/TaskInUsingAnalyzer.cs b/src/Meziantou.Analyzer/Rules/TaskInUsingAnalyzer.cs index 35643d377..e301f0988 100644 --- a/src/Meziantou.Analyzer/Rules/TaskInUsingAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/TaskInUsingAnalyzer.cs @@ -37,15 +37,8 @@ public override void Initialize(AnalysisContext context) }); } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(INamedTypeSymbol taskSymbol) { - private readonly INamedTypeSymbol _taskSymbol; - - public AnalyzerContext(INamedTypeSymbol taskSymbol) - { - _taskSymbol = taskSymbol; - } - public void AnalyzeUsing(OperationAnalysisContext context) { var operation = (IUsingOperation)context.Operation; @@ -83,7 +76,7 @@ private void AnalyzeResource(OperationAnalysisContext context, IOperation? opera } operation = operation.UnwrapImplicitConversionOperations(); - if (operation.Type != null && operation.Type.IsOrInheritFrom(_taskSymbol)) + if (operation.Type != null && operation.Type.IsOrInheritFrom(taskSymbol)) { context.ReportDiagnostic(s_rule, operation); } diff --git a/src/Meziantou.Analyzer/Rules/UseAnOverloadThatHasCancellationTokenAnalyzer.cs b/src/Meziantou.Analyzer/Rules/UseAnOverloadThatHasCancellationTokenAnalyzer.cs index 44877f8be..2d32b217b 100644 --- a/src/Meziantou.Analyzer/Rules/UseAnOverloadThatHasCancellationTokenAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/UseAnOverloadThatHasCancellationTokenAnalyzer.cs @@ -78,31 +78,19 @@ public override void Initialize(AnalysisContext context) }); } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(Compilation compilation) { private readonly ConcurrentDictionary<(ITypeSymbol Symbol, int MaxDepth), List?> _membersByType = new(); - private readonly OverloadFinder _overloadFinder; + private readonly OverloadFinder _overloadFinder = new(compilation); - public AnalyzerContext(Compilation compilation) - { - Compilation = compilation; - _overloadFinder = new OverloadFinder(compilation); - CancellationTokenSymbol = compilation.GetBestTypeByMetadataName("System.Threading.CancellationToken")!; // Not nullable as it is checked before registering the Operation actions - CancellationTokenSourceSymbol = compilation.GetBestTypeByMetadataName("System.Threading.CancellationTokenSource"); - TaskSymbol = compilation.GetBestTypeByMetadataName("System.Threading.Tasks.Task"); - TaskOfTSymbol = compilation.GetBestTypeByMetadataName("System.Threading.Tasks.Task`1"); - ConfiguredCancelableAsyncEnumerableSymbol = compilation.GetBestTypeByMetadataName("System.Runtime.CompilerServices.ConfiguredCancelableAsyncEnumerable`1"); - EnumeratorCancellationAttributeSymbol = compilation.GetBestTypeByMetadataName("System.Runtime.CompilerServices.EnumeratorCancellationAttribute"); - } - - public Compilation Compilation { get; } - public INamedTypeSymbol CancellationTokenSymbol { get; } - public INamedTypeSymbol? CancellationTokenSourceSymbol { get; } - private INamedTypeSymbol? TaskSymbol { get; } - private INamedTypeSymbol? TaskOfTSymbol { get; } - private INamedTypeSymbol? ConfiguredCancelableAsyncEnumerableSymbol { get; } - private INamedTypeSymbol? EnumeratorCancellationAttributeSymbol { get; } + public Compilation Compilation { get; } = compilation; + public INamedTypeSymbol CancellationTokenSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Threading.CancellationToken")!; // Not nullable as it is checked before registering the Operation actions + public INamedTypeSymbol? CancellationTokenSourceSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Threading.CancellationTokenSource"); + private INamedTypeSymbol? TaskSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Threading.Tasks.Task"); + private INamedTypeSymbol? TaskOfTSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Threading.Tasks.Task`1"); + private INamedTypeSymbol? ConfiguredCancelableAsyncEnumerableSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Runtime.CompilerServices.ConfiguredCancelableAsyncEnumerable`1"); + private INamedTypeSymbol? EnumeratorCancellationAttributeSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Runtime.CompilerServices.EnumeratorCancellationAttribute"); private bool HasExplicitCancellationTokenArgument(IInvocationOperation operation) { @@ -273,7 +261,7 @@ public void AnalyzeLoop(OperationAnalysisContext context) return null; if (symbol.IsEqualTo(CancellationTokenSymbol)) - return new List(capacity: 1) { Array.Empty() }; + return [[]]; var result = new List(); var members = symbol.GetAllMembers(); @@ -299,7 +287,7 @@ public void AnalyzeLoop(OperationAnalysisContext context) if (memberTypeSymbol.IsEqualTo(CancellationTokenSymbol)) { - result.Add(new ISymbol[] { member }); + result.Add([member]); } else { @@ -330,7 +318,7 @@ private string[] FindCancellationTokens(IOperation operation, CancellationToken } if (availableSymbols.Count == 0) - return Array.Empty(); + return []; var isInStaticContext = operation.IsInStaticContext(cancellationToken); @@ -359,7 +347,7 @@ private string[] FindCancellationTokens(IOperation operation, CancellationToken } if (paths.Count == 0) - return Array.Empty(); + return []; return paths.OrderBy(value => value.Count(c => c == '.')).ThenBy(value => value, StringComparer.Ordinal).ToArray(); diff --git a/src/Meziantou.Analyzer/Rules/UseConfigureAwaitAnalyzer.cs b/src/Meziantou.Analyzer/Rules/UseConfigureAwaitAnalyzer.cs index 4e55156db..1dd6a30b6 100644 --- a/src/Meziantou.Analyzer/Rules/UseConfigureAwaitAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/UseConfigureAwaitAnalyzer.cs @@ -41,47 +41,25 @@ public override void Initialize(AnalysisContext context) }); } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(Compilation compilation) { - public AnalyzerContext(Compilation compilation) - { - ConfiguredAsyncDisposableSymbol = compilation.GetBestTypeByMetadataName("System.Runtime.CompilerServices.ConfiguredAsyncDisposable"); - - IAsyncEnumerableSymbol = compilation.GetBestTypeByMetadataName("System.Collections.Generic.IAsyncEnumerable`1"); - ConfiguredCancelableAsyncEnumerableSymbol = compilation.GetBestTypeByMetadataName("System.Runtime.CompilerServices.ConfiguredCancelableAsyncEnumerable`1"); - ConfiguredTaskAwaitableSymbol = compilation.GetBestTypeByMetadataName("System.Runtime.CompilerServices.ConfiguredTaskAwaitable"); - ConfiguredTaskAwaitableOfTSymbol = compilation.GetBestTypeByMetadataName("System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1"); - - WPF_DispatcherObject = compilation.GetBestTypeByMetadataName("System.Windows.Threading.DispatcherObject"); - WPF_ICommand = compilation.GetBestTypeByMetadataName("System.Windows.Input.ICommand"); - - WinForms_Control = compilation.GetBestTypeByMetadataName("System.Windows.Forms.Control"); - WebForms_WebControl = compilation.GetBestTypeByMetadataName("System.Web.UI.WebControls.WebControl"); - AspNetCore_ControllerBase = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Mvc.ControllerBase"); - AspNetCore_IRazorPage = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Mvc.Razor.IRazorPage"); - AspNetCore_ITagHelper = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Razor.TagHelpers.ITagHelper"); - AspNetCore_ITagHelperComponent = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Razor.TagHelpers.ITagHelperComponent"); - AspNetCore_IFilterMetadata = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Mvc.Filters.IFilterMetadata"); - AspNetCore_IComponent = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Components.IComponent"); - } - - private INamedTypeSymbol? ConfiguredAsyncDisposableSymbol { get; } - - private INamedTypeSymbol? IAsyncEnumerableSymbol { get; } - private INamedTypeSymbol? ConfiguredCancelableAsyncEnumerableSymbol { get; } - private INamedTypeSymbol? ConfiguredTaskAwaitableSymbol { get; } - private INamedTypeSymbol? ConfiguredTaskAwaitableOfTSymbol { get; } - - private INamedTypeSymbol? WPF_DispatcherObject { get; } - private INamedTypeSymbol? WPF_ICommand { get; } - private INamedTypeSymbol? WinForms_Control { get; } - private INamedTypeSymbol? WebForms_WebControl { get; } - private INamedTypeSymbol? AspNetCore_ControllerBase { get; } - private INamedTypeSymbol? AspNetCore_IRazorPage { get; } - private INamedTypeSymbol? AspNetCore_ITagHelper { get; } - private INamedTypeSymbol? AspNetCore_ITagHelperComponent { get; } - private INamedTypeSymbol? AspNetCore_IFilterMetadata { get; } - private INamedTypeSymbol? AspNetCore_IComponent { get; } + private INamedTypeSymbol? ConfiguredAsyncDisposableSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Runtime.CompilerServices.ConfiguredAsyncDisposable"); + + private INamedTypeSymbol? IAsyncEnumerableSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Collections.Generic.IAsyncEnumerable`1"); + private INamedTypeSymbol? ConfiguredCancelableAsyncEnumerableSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Runtime.CompilerServices.ConfiguredCancelableAsyncEnumerable`1"); + private INamedTypeSymbol? ConfiguredTaskAwaitableSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Runtime.CompilerServices.ConfiguredTaskAwaitable"); + private INamedTypeSymbol? ConfiguredTaskAwaitableOfTSymbol { get; } = compilation.GetBestTypeByMetadataName("System.Runtime.CompilerServices.ConfiguredTaskAwaitable`1"); + + private INamedTypeSymbol? WPF_DispatcherObject { get; } = compilation.GetBestTypeByMetadataName("System.Windows.Threading.DispatcherObject"); + private INamedTypeSymbol? WPF_ICommand { get; } = compilation.GetBestTypeByMetadataName("System.Windows.Input.ICommand"); + private INamedTypeSymbol? WinForms_Control { get; } = compilation.GetBestTypeByMetadataName("System.Windows.Forms.Control"); + private INamedTypeSymbol? WebForms_WebControl { get; } = compilation.GetBestTypeByMetadataName("System.Web.UI.WebControls.WebControl"); + private INamedTypeSymbol? AspNetCore_ControllerBase { get; } = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Mvc.ControllerBase"); + private INamedTypeSymbol? AspNetCore_IRazorPage { get; } = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Mvc.Razor.IRazorPage"); + private INamedTypeSymbol? AspNetCore_ITagHelper { get; } = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Razor.TagHelpers.ITagHelper"); + private INamedTypeSymbol? AspNetCore_ITagHelperComponent { get; } = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Razor.TagHelpers.ITagHelperComponent"); + private INamedTypeSymbol? AspNetCore_IFilterMetadata { get; } = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Mvc.Filters.IFilterMetadata"); + private INamedTypeSymbol? AspNetCore_IComponent { get; } = compilation.GetBestTypeByMetadataName("Microsoft.AspNetCore.Components.IComponent"); public void AnalyzeAwaitExpression(SyntaxNodeAnalysisContext context) { diff --git a/src/Meziantou.Analyzer/Rules/UseDateTimeUnixEpochAnalyzer.cs b/src/Meziantou.Analyzer/Rules/UseDateTimeUnixEpochAnalyzer.cs index 1bdc1f36d..795f6e323 100644 --- a/src/Meziantou.Analyzer/Rules/UseDateTimeUnixEpochAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/UseDateTimeUnixEpochAnalyzer.cs @@ -77,7 +77,7 @@ bool IsDateTimeOffsetUnixEpoch() if (operation.Arguments.Length == 1) { - if (ArgumentsEquals(operation.Arguments.AsSpan(), new object[] { 621355968000000000L })) + if (ArgumentsEquals(operation.Arguments.AsSpan(), [621355968000000000L])) return true; if (IsUnixEpochProperty(operation.Arguments[0])) @@ -85,7 +85,7 @@ bool IsDateTimeOffsetUnixEpoch() } else if (operation.Arguments.Length == 2) { - if (ArgumentsEquals(operation.Arguments.AsSpan(0, 1), new object[] { 621355968000000000L }) && IsTimeSpanZero(operation.Arguments[1])) + if (ArgumentsEquals(operation.Arguments.AsSpan(0, 1), [621355968000000000L]) && IsTimeSpanZero(operation.Arguments[1])) return true; if (IsUnixEpochProperty(operation.Arguments[0]) && IsTimeSpanZero(operation.Arguments[1])) @@ -93,17 +93,17 @@ bool IsDateTimeOffsetUnixEpoch() } else if (operation.Arguments.Length == 7) { - if (ArgumentsEquals(operation.Arguments.AsSpan(0, 6), new object[] { 1970, 1, 1, 0, 0, 0 }) && IsTimeSpanZero(operation.Arguments[6])) + if (ArgumentsEquals(operation.Arguments.AsSpan(0, 6), [1970, 1, 1, 0, 0, 0]) && IsTimeSpanZero(operation.Arguments[6])) return true; } else if (operation.Arguments.Length == 8) { - if (ArgumentsEquals(operation.Arguments.AsSpan(0, 7), new object[] { 1970, 1, 1, 0, 0, 0, 0 }) && IsTimeSpanZero(operation.Arguments[7])) + if (ArgumentsEquals(operation.Arguments.AsSpan(0, 7), [1970, 1, 1, 0, 0, 0, 0]) && IsTimeSpanZero(operation.Arguments[7])) return true; } else if (operation.Arguments.Length == 9) { - if (ArgumentsEquals(operation.Arguments.AsSpan(0, 8), new object[] { 1970, 1, 1, 0, 0, 0, 0, 0 }) && IsTimeSpanZero(operation.Arguments[8])) + if (ArgumentsEquals(operation.Arguments.AsSpan(0, 8), [1970, 1, 1, 0, 0, 0, 0, 0]) && IsTimeSpanZero(operation.Arguments[8])) return true; } @@ -129,27 +129,27 @@ private static bool IsDateTimeUnixEpoch(IObjectCreationOperation operation, Comp if (operation.Arguments.Length == 1) { - if (ArgumentsEquals(operation.Arguments.AsSpan(), new object[] { 621355968000000000L })) + if (ArgumentsEquals(operation.Arguments.AsSpan(), [621355968000000000L])) return true; } else if (operation.Arguments.Length == 2) { - if (ArgumentsEquals(operation.Arguments.AsSpan(0, 1), new object[] { 621355968000000000L }) && IsDateTimeKindUtc(compilation, operation.Arguments[1])) + if (ArgumentsEquals(operation.Arguments.AsSpan(0, 1), [621355968000000000L]) && IsDateTimeKindUtc(compilation, operation.Arguments[1])) return true; } else if (operation.Arguments.Length == 3) { - if (ArgumentsEquals(operation.Arguments.AsSpan(), new object[] { 1970, 1, 1 })) + if (ArgumentsEquals(operation.Arguments.AsSpan(), [1970, 1, 1])) return true; } else if (operation.Arguments.Length == 6) { - if (ArgumentsEquals(operation.Arguments.AsSpan(), new object[] { 1970, 1, 1, 0, 0, 0 })) + if (ArgumentsEquals(operation.Arguments.AsSpan(), [1970, 1, 1, 0, 0, 0])) return true; } else if (operation.Arguments.Length == 7) { - if (ArgumentsEquals(operation.Arguments.AsSpan(0, 6), new object[] { 1970, 1, 1, 0, 0, 0 }) && IsDateTimeKindUtc(compilation, operation.Arguments[6])) + if (ArgumentsEquals(operation.Arguments.AsSpan(0, 6), [1970, 1, 1, 0, 0, 0]) && IsDateTimeKindUtc(compilation, operation.Arguments[6])) return true; } diff --git a/src/Meziantou.Analyzer/Rules/UseEventHandlerOfTAnalyzer.cs b/src/Meziantou.Analyzer/Rules/UseEventHandlerOfTAnalyzer.cs index 163b447c2..0db32e4fd 100644 --- a/src/Meziantou.Analyzer/Rules/UseEventHandlerOfTAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/UseEventHandlerOfTAnalyzer.cs @@ -32,14 +32,9 @@ public override void Initialize(AnalysisContext context) }); } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(Compilation compilation) { - public AnalyzerContext(Compilation compilation) - { - EventArgsSymbol = compilation.GetBestTypeByMetadataName("System.EventArgs"); - } - - public INamedTypeSymbol? EventArgsSymbol { get; } + public INamedTypeSymbol? EventArgsSymbol { get; } = compilation.GetBestTypeByMetadataName("System.EventArgs"); public void AnalyzeSymbol(SymbolAnalysisContext context) { diff --git a/src/Meziantou.Analyzer/Rules/UseIFormatProviderAnalyzer.cs b/src/Meziantou.Analyzer/Rules/UseIFormatProviderAnalyzer.cs index 60132d0bd..63971a270 100644 --- a/src/Meziantou.Analyzer/Rules/UseIFormatProviderAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/UseIFormatProviderAnalyzer.cs @@ -33,16 +33,10 @@ public override void Initialize(AnalysisContext context) }); } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(Compilation compilation) { - private readonly CultureSensitiveFormattingContext _cultureSensitiveContext; - private readonly OverloadFinder _overloadFinder; - - public AnalyzerContext(Compilation compilation) - { - _cultureSensitiveContext = new CultureSensitiveFormattingContext(compilation); - _overloadFinder = new OverloadFinder(compilation); - } + private readonly CultureSensitiveFormattingContext _cultureSensitiveContext = new(compilation); + private readonly OverloadFinder _overloadFinder = new(compilation); public void AnalyzeInvocation(OperationAnalysisContext context) { diff --git a/src/Meziantou.Analyzer/Rules/UseJSRuntimeInvokeVoidAsyncWhenReturnValueIsNotUsedAnalyzer.cs b/src/Meziantou.Analyzer/Rules/UseJSRuntimeInvokeVoidAsyncWhenReturnValueIsNotUsedAnalyzer.cs index 4792f7ef7..030c5bb93 100644 --- a/src/Meziantou.Analyzer/Rules/UseJSRuntimeInvokeVoidAsyncWhenReturnValueIsNotUsedAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/UseJSRuntimeInvokeVoidAsyncWhenReturnValueIsNotUsedAnalyzer.cs @@ -34,21 +34,13 @@ public override void Initialize(AnalysisContext context) }); } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(Compilation compilation) { - public AnalyzerContext(Compilation compilation) - { - IJSRuntimeSymbol = compilation.GetBestTypeByMetadataName("Microsoft.JSInterop.IJSRuntime"); - JSRuntimeExtensionsSymbol = compilation.GetBestTypeByMetadataName("Microsoft.JSInterop.JSRuntimeExtensions"); - IJSInProcessRuntimeSymbol = compilation.GetBestTypeByMetadataName("Microsoft.JSInterop.IJSInProcessRuntime"); - JSInProcessRuntimeExtensionsSymbol = compilation.GetBestTypeByMetadataName("Microsoft.JSInterop.JSInProcessRuntimeExtensions"); - } - - public INamedTypeSymbol? IJSRuntimeSymbol { get; } - public INamedTypeSymbol? JSRuntimeExtensionsSymbol { get; } + public INamedTypeSymbol? IJSRuntimeSymbol { get; } = compilation.GetBestTypeByMetadataName("Microsoft.JSInterop.IJSRuntime"); + public INamedTypeSymbol? JSRuntimeExtensionsSymbol { get; } = compilation.GetBestTypeByMetadataName("Microsoft.JSInterop.JSRuntimeExtensions"); - public INamedTypeSymbol? IJSInProcessRuntimeSymbol { get; } - public INamedTypeSymbol? JSInProcessRuntimeExtensionsSymbol { get; } + public INamedTypeSymbol? IJSInProcessRuntimeSymbol { get; } = compilation.GetBestTypeByMetadataName("Microsoft.JSInterop.IJSInProcessRuntime"); + public INamedTypeSymbol? JSInProcessRuntimeExtensionsSymbol { get; } = compilation.GetBestTypeByMetadataName("Microsoft.JSInterop.JSInProcessRuntimeExtensions"); public bool IsValid => IJSInProcessRuntimeSymbol != null || IJSRuntimeSymbol != null; diff --git a/src/Meziantou.Analyzer/Rules/UsePatternMatchingForNullCheckAnalyzer.cs b/src/Meziantou.Analyzer/Rules/UsePatternMatchingForNullCheckAnalyzer.cs index c2c115d4a..8a10949c8 100644 --- a/src/Meziantou.Analyzer/Rules/UsePatternMatchingForNullCheckAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/UsePatternMatchingForNullCheckAnalyzer.cs @@ -37,7 +37,7 @@ public override void Initialize(AnalysisContext context) context.RegisterOperationAction(AnalyzeBinary, OperationKind.Binary); } - private void AnalyzeBinary(OperationAnalysisContext context) + private static void AnalyzeBinary(OperationAnalysisContext context) { var operation = (IBinaryOperation)context.Operation; if (operation is { OperatorKind: BinaryOperatorKind.Equals or BinaryOperatorKind.NotEquals, OperatorMethod: null }) diff --git a/src/Meziantou.Analyzer/Rules/UseRegexSourceGeneratorAnalyzerCommon.cs b/src/Meziantou.Analyzer/Rules/UseRegexSourceGeneratorAnalyzerCommon.cs index 1364bff9d..5b8bf6476 100644 --- a/src/Meziantou.Analyzer/Rules/UseRegexSourceGeneratorAnalyzerCommon.cs +++ b/src/Meziantou.Analyzer/Rules/UseRegexSourceGeneratorAnalyzerCommon.cs @@ -1,12 +1,4 @@ -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Globalization; -using Meziantou.Analyzer.Internals; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Operations; - -namespace Meziantou.Analyzer.Rules; +namespace Meziantou.Analyzer.Rules; internal static class UseRegexSourceGeneratorAnalyzerCommon { diff --git a/src/Meziantou.Analyzer/Rules/UseStringComparerAnalyzer.cs b/src/Meziantou.Analyzer/Rules/UseStringComparerAnalyzer.cs index 0958158f1..a222c1a29 100644 --- a/src/Meziantou.Analyzer/Rules/UseStringComparerAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/UseStringComparerAnalyzer.cs @@ -15,7 +15,7 @@ namespace Meziantou.Analyzer.Rules; public sealed class UseStringComparerAnalyzer : DiagnosticAnalyzer { private static readonly string[] s_enumerableMethods = - { + [ "Contains", "Distinct", "Except", @@ -28,7 +28,7 @@ public sealed class UseStringComparerAnalyzer : DiagnosticAnalyzer "ThenByDescending", "ToHashSet", "Union", - }; + ]; private static readonly Dictionary s_arityIndex = new(StringComparer.Ordinal) { @@ -68,25 +68,15 @@ public override void Initialize(AnalysisContext context) }); } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(Compilation compilation) { - private readonly OverloadFinder _overloadFinder; - private readonly OperationUtilities _operationUtilities; - - public AnalyzerContext(Compilation compilation) - { - _overloadFinder = new OverloadFinder(compilation); - _operationUtilities = new OperationUtilities(compilation); - EqualityComparerStringType = GetIEqualityComparerString(compilation); - ComparerStringType = GetIComparerString(compilation); - EnumerableType = compilation.GetBestTypeByMetadataName("System.Linq.Enumerable"); - ISetType = compilation.GetBestTypeByMetadataName("System.Collections.Generic.ISet`1")?.Construct(compilation.GetSpecialType(SpecialType.System_String)); - } + private readonly OverloadFinder _overloadFinder = new(compilation); + private readonly OperationUtilities _operationUtilities = new(compilation); - public INamedTypeSymbol? EqualityComparerStringType { get; } - public INamedTypeSymbol? ComparerStringType { get; } - public INamedTypeSymbol? EnumerableType { get; } - public INamedTypeSymbol? ISetType { get; } + public INamedTypeSymbol? EqualityComparerStringType { get; } = GetIEqualityComparerString(compilation); + public INamedTypeSymbol? ComparerStringType { get; } = GetIComparerString(compilation); + public INamedTypeSymbol? EnumerableType { get; } = compilation.GetBestTypeByMetadataName("System.Linq.Enumerable"); + public INamedTypeSymbol? ISetType { get; } = compilation.GetBestTypeByMetadataName("System.Collections.Generic.ISet`1")?.Construct(compilation.GetSpecialType(SpecialType.System_String)); public void AnalyzeConstructor(OperationAnalysisContext ctx) { diff --git a/src/Meziantou.Analyzer/Rules/UseStringComparisonAnalyzer.cs b/src/Meziantou.Analyzer/Rules/UseStringComparisonAnalyzer.cs index 021978b2f..89528f34b 100644 --- a/src/Meziantou.Analyzer/Rules/UseStringComparisonAnalyzer.cs +++ b/src/Meziantou.Analyzer/Rules/UseStringComparisonAnalyzer.cs @@ -47,22 +47,13 @@ public override void Initialize(AnalysisContext context) }); } - private sealed class AnalyzerContext + private sealed class AnalyzerContext(Compilation compilation) { - private readonly OverloadFinder _overloadFinder; - private readonly OperationUtilities _operationUtilities; - private readonly INamedTypeSymbol _stringComparisonSymbol; - private readonly INamedTypeSymbol? _jobjectSymbol; - private readonly INamedTypeSymbol? _xunitAssertSymbol; - - public AnalyzerContext(Compilation compilation) - { - _overloadFinder = new OverloadFinder(compilation); - _operationUtilities = new OperationUtilities(compilation); - _stringComparisonSymbol = compilation.GetBestTypeByMetadataName("System.StringComparison")!; - _jobjectSymbol = compilation.GetBestTypeByMetadataName("Newtonsoft.Json.Linq.JObject"); - _xunitAssertSymbol = compilation.GetBestTypeByMetadataName("XUnit.Assert"); - } + private readonly OverloadFinder _overloadFinder = new OverloadFinder(compilation); + private readonly OperationUtilities _operationUtilities = new OperationUtilities(compilation); + private readonly INamedTypeSymbol _stringComparisonSymbol = compilation.GetBestTypeByMetadataName("System.StringComparison")!; + private readonly INamedTypeSymbol? _jobjectSymbol = compilation.GetBestTypeByMetadataName("Newtonsoft.Json.Linq.JObject"); + private readonly INamedTypeSymbol? _xunitAssertSymbol = compilation.GetBestTypeByMetadataName("XUnit.Assert"); public bool IsValid => _stringComparisonSymbol != null; diff --git a/src/Meziantou.Analyzer/Suppressors/CA1822DecoratedMethodSuppressor.cs b/src/Meziantou.Analyzer/Suppressors/CA1822DecoratedMethodSuppressor.cs index 8ef586835..bc2fa1253 100644 --- a/src/Meziantou.Analyzer/Suppressors/CA1822DecoratedMethodSuppressor.cs +++ b/src/Meziantou.Analyzer/Suppressors/CA1822DecoratedMethodSuppressor.cs @@ -21,12 +21,12 @@ public sealed class CA1822DecoratedMethodSuppressor : DiagnosticSuppressor ); private static readonly (SuppressionDescriptor Descriptor, string AttributeName)[] AttributeNames = - { + [ (s_ruleBenchmarkDotNet, "BenchmarkDotNet.Attributes.BenchmarkAttribute"), (s_ruleJsonPropertyName, "System.Text.Json.Serialization.JsonPropertyNameAttribute"), (s_ruleJsonPropertyName, "System.Text.Json.Serialization.JsonPropertyOrderAttribute"), (s_ruleJsonPropertyName, "System.Text.Json.Serialization.JsonRequiredAttribute"), - }; + ]; public override ImmutableArray SupportedSuppressions => ImmutableArray.Create(s_ruleBenchmarkDotNet, s_ruleJsonPropertyName); diff --git a/tests/Meziantou.Analyzer.Test/Helpers/ProjectBuilder.Validation.cs b/tests/Meziantou.Analyzer.Test/Helpers/ProjectBuilder.Validation.cs index 339feca7a..928034081 100644 --- a/tests/Meziantou.Analyzer.Test/Helpers/ProjectBuilder.Validation.cs +++ b/tests/Meziantou.Analyzer.Test/Helpers/ProjectBuilder.Validation.cs @@ -191,7 +191,7 @@ private Task CreateProject() break; case TargetFramework.Net8_0: - AddNuGetReference("Microsoft.NETCore.App.Ref", "8.0.0-rc.1.23419.4", "ref/net8.0/"); + AddNuGetReference("Microsoft.NETCore.App.Ref", "8.0.0", "ref/net8.0/"); break; case TargetFramework.AspNetCore5_0: @@ -210,8 +210,8 @@ private Task CreateProject() break; case TargetFramework.AspNetCore8_0: - AddNuGetReference("Microsoft.NETCore.App.Ref", "8.0.0-rc.1.23419.4", "ref/net8.0/"); - AddNuGetReference("Microsoft.AspNetCore.App.Ref", "8.0.0-rc.1.23421.29", "ref/net8.0/"); + AddNuGetReference("Microsoft.NETCore.App.Ref", "8.0.0", "ref/net8.0/"); + AddNuGetReference("Microsoft.AspNetCore.App.Ref", "8.0.0", "ref/net8.0/"); break; case TargetFramework.WindowsDesktop5_0: @@ -572,15 +572,8 @@ private static async Task GetStringFromDocument(Document document) return root.GetText().ToString(); } - private sealed class CustomDiagnosticProvider : FixAllContext.DiagnosticProvider + private sealed class CustomDiagnosticProvider(Diagnostic[] diagnostics) : FixAllContext.DiagnosticProvider { - private readonly Diagnostic[] _diagnostics; - - public CustomDiagnosticProvider(Diagnostic[] diagnostics) - { - _diagnostics = diagnostics; - } - public override Task> GetAllDiagnosticsAsync(Project project, CancellationToken cancellationToken) { return GetProjectDiagnosticsAsync(project, cancellationToken); @@ -589,7 +582,7 @@ public override Task> GetAllDiagnosticsAsync(Project pro public override async Task> GetDocumentDiagnosticsAsync(Document document, CancellationToken cancellationToken) { var documentRoot = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); - return _diagnostics.Where(diagnostic => documentRoot == diagnostic.Location.SourceTree.GetRoot()); + return diagnostics.Where(diagnostic => documentRoot == diagnostic.Location.SourceTree.GetRoot()); } public override Task> GetProjectDiagnosticsAsync(Project project, CancellationToken cancellationToken) diff --git a/tests/Meziantou.Analyzer.Test/Helpers/ProjectBuilder.cs b/tests/Meziantou.Analyzer.Test/Helpers/ProjectBuilder.cs index 58f079980..ff2948990 100644 --- a/tests/Meziantou.Analyzer.Test/Helpers/ProjectBuilder.cs +++ b/tests/Meziantou.Analyzer.Test/Helpers/ProjectBuilder.cs @@ -129,7 +129,7 @@ public ProjectBuilder WithMicrosoftCodeAnalysisNetAnalyzers(params string[] rule WithAnalyzerFromNuGet( "Microsoft.CodeAnalysis.NetAnalyzers", "7.0.1", - paths: new[] { "analyzers/dotnet/cs/Microsoft.CodeAnalysis" }, + paths: ["analyzers/dotnet/cs/Microsoft.CodeAnalysis"], ruleIds); public ProjectBuilder AddMSTestApi() => AddNuGetReference("MSTest.TestFramework", "2.1.1", "lib/netstandard1.0/"); @@ -227,14 +227,14 @@ public ProjectBuilder WithAnalyzerConfiguration(Dictionary confi public ProjectBuilder AddAnalyzerConfiguration(string key, string value) { - AnalyzerConfiguration ??= new Dictionary(); + AnalyzerConfiguration ??= []; AnalyzerConfiguration[key] = value; return this; } public ProjectBuilder AddAdditionalFile(string path, string content) { - AdditionalFiles ??= new Dictionary(); + AdditionalFiles ??= []; AdditionalFiles[path] = content; return this; } diff --git a/tests/Meziantou.Analyzer.Test/Helpers/SharedHttpClient.cs b/tests/Meziantou.Analyzer.Test/Helpers/SharedHttpClient.cs index b4ba88e1c..ce12e6444 100644 --- a/tests/Meziantou.Analyzer.Test/Helpers/SharedHttpClient.cs +++ b/tests/Meziantou.Analyzer.Test/Helpers/SharedHttpClient.cs @@ -35,13 +35,8 @@ private static HttpClient CreateHttpClient() return new HttpClient(new HttpRetryMessageHandler(socketHandler), disposeHandler: true); } - private sealed class HttpRetryMessageHandler : DelegatingHandler + private sealed class HttpRetryMessageHandler(HttpMessageHandler handler) : DelegatingHandler(handler) { - public HttpRetryMessageHandler(HttpMessageHandler handler) - : base(handler) - { - } - protected override async Task SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { const int MaxRetries = 5; diff --git a/tests/Meziantou.Analyzer.Test/Helpers/TestAnalyzerConfigOptionsProvider.cs b/tests/Meziantou.Analyzer.Test/Helpers/TestAnalyzerConfigOptionsProvider.cs index 3df31febd..27d9ea79b 100644 --- a/tests/Meziantou.Analyzer.Test/Helpers/TestAnalyzerConfigOptionsProvider.cs +++ b/tests/Meziantou.Analyzer.Test/Helpers/TestAnalyzerConfigOptionsProvider.cs @@ -4,27 +4,17 @@ namespace Meziantou.Analyzer.Test.Helpers; -internal sealed class TestAnalyzerConfigOptionsProvider : AnalyzerConfigOptionsProvider +internal sealed class TestAnalyzerConfigOptionsProvider(Dictionary values) : AnalyzerConfigOptionsProvider { - private readonly Dictionary _values; - - public TestAnalyzerConfigOptionsProvider(Dictionary values) - { - _values = values ?? new Dictionary(); - } + private readonly Dictionary _values = values ?? []; public override AnalyzerConfigOptions GlobalOptions => new TestAnalyzerConfigOptions(_values); public override AnalyzerConfigOptions GetOptions(SyntaxTree tree) => new TestAnalyzerConfigOptions(_values); public override AnalyzerConfigOptions GetOptions(AdditionalText textFile) => new TestAnalyzerConfigOptions(_values); - private sealed class TestAnalyzerConfigOptions : AnalyzerConfigOptions + private sealed class TestAnalyzerConfigOptions(Dictionary values) : AnalyzerConfigOptions { - private readonly Dictionary _values; - - public TestAnalyzerConfigOptions(Dictionary values) - { - _values = values; - } + private readonly Dictionary _values = values; public override bool TryGetValue(string key, out string value) { diff --git a/tests/Meziantou.Analyzer.Test/Meziantou.Analyzer.Test.csproj b/tests/Meziantou.Analyzer.Test/Meziantou.Analyzer.Test.csproj index 18f6c6ef3..fdd9f77e3 100644 --- a/tests/Meziantou.Analyzer.Test/Meziantou.Analyzer.Test.csproj +++ b/tests/Meziantou.Analyzer.Test/Meziantou.Analyzer.Test.csproj @@ -1,7 +1,7 @@  - net7.0 + net8.0 $(TargetFrameworks);net462 false true @@ -28,10 +28,4 @@ - - - 1.0.11 - - -