diff --git a/.editorconfig b/.editorconfig index f41b2c17e4..c29c1e2ed5 100644 --- a/.editorconfig +++ b/.editorconfig @@ -242,6 +242,21 @@ dotnet_diagnostic.IDE0130.severity = silent # IDE0150: Null check can be clarified dotnet_diagnostic.IDE0150.severity = silent +# IDE2000: Allow multiple blank lines +dotnet_style_allow_multiple_blank_lines_experimental = false + +# IDE2001: Embedded statements must be on their own line +csharp_style_allow_embedded_statements_on_same_line_experimental = false + +# IDE2002: Consecutive braces must not have blank line between them +csharp_style_allow_blank_lines_between_consecutive_braces_experimental = false + +# IDE2003: Blank line required between block and subsequent statement +dotnet_style_allow_statement_immediately_after_block_experimental = false + +# IDE2004: Blank line not allowed after constructor initializer colon +csharp_style_allow_blank_line_after_colon_in_constructor_initializer_experimental = false + ### Configuration for FxCop analyzers executed on this repo ### [*.{cs,vb}] diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/CompareSymbolsCorrectlyAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/CompareSymbolsCorrectlyAnalyzer.cs index 7798b48e0c..6300a3aaaf 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/CompareSymbolsCorrectlyAnalyzer.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/CompareSymbolsCorrectlyAnalyzer.cs @@ -165,6 +165,7 @@ private static void HandleInvocationOperation( { context.ReportDiagnostic(invocationOperation.CreateDiagnostic(GetHashCodeRule)); } + break; case s_symbolEqualsName: @@ -176,6 +177,7 @@ private static void HandleInvocationOperation( context.ReportDiagnostic(invocationOperation.Syntax.GetLocation().CreateDiagnostic(EqualityRule)); } } + break; case s_HashCodeCombineName: @@ -187,6 +189,7 @@ invocationOperation.Instance is null && { context.ReportDiagnostic(invocationOperation.CreateDiagnostic(GetHashCodeRule)); } + break; default: @@ -198,6 +201,7 @@ invocationOperation.Instance is null && { context.ReportDiagnostic(invocationOperation.CreateDiagnostic(CollectionRule)); } + break; } diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/AnalyzerReleaseTrackingFix.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/AnalyzerReleaseTrackingFix.cs index 49c0201609..575f19f2eb 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/AnalyzerReleaseTrackingFix.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/AnalyzerReleaseTrackingFix.cs @@ -72,6 +72,7 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) cancellationToken => UpdateEntryInUnshippedFileAsync(context.Document.Project, ruleId, entryToUpdate, cancellationToken), equivalenceKey: CodeAnalysisDiagnosticsResources.UpdateEntryForDiagnosticIdInAnalyzerReleaseCodeFixTitle); } + break; case DiagnosticIds.EnableAnalyzerReleaseTrackingRuleId: diff --git a/src/Microsoft.CodeAnalysis.Analyzers/VisualBasic/MetaAnalyzers/Fixers/BasicPreferIsKindFix.vb b/src/Microsoft.CodeAnalysis.Analyzers/VisualBasic/MetaAnalyzers/Fixers/BasicPreferIsKindFix.vb index f19a63a360..d59c616ad2 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/VisualBasic/MetaAnalyzers/Fixers/BasicPreferIsKindFix.vb +++ b/src/Microsoft.CodeAnalysis.Analyzers/VisualBasic/MetaAnalyzers/Fixers/BasicPreferIsKindFix.vb @@ -35,6 +35,7 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Analyzers.MetaAnalyzers.CodeFixes If invocation Is Nothing Then Return binaryExpression End If + Dim newInvocation = invocation _ .WithExpression(ConvertKindNameToIsKind(invocation.Expression)) _ .AddArgumentListArguments(SyntaxFactory.SimpleArgument(binaryExpression.Right.WithoutTrailingTrivia())) _ diff --git a/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/SymbolIsBannedAnalyzerBase.cs b/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/SymbolIsBannedAnalyzerBase.cs index b80ed9f34d..6599b93a82 100644 --- a/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/SymbolIsBannedAnalyzerBase.cs +++ b/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/SymbolIsBannedAnalyzerBase.cs @@ -101,6 +101,7 @@ private void OnCompilationStart(CompilationStartAnalysisContext compilationConte VerifySymbol(context.ReportDiagnostic, conversion.OperatorMethod, context.Operation.Syntax); VerifyType(context.ReportDiagnostic, conversion.OperatorMethod.ContainingType, context.Operation.Syntax); } + break; case IUnaryOperation unary: @@ -109,6 +110,7 @@ private void OnCompilationStart(CompilationStartAnalysisContext compilationConte VerifySymbol(context.ReportDiagnostic, unary.OperatorMethod, context.Operation.Syntax); VerifyType(context.ReportDiagnostic, unary.OperatorMethod.ContainingType, context.Operation.Syntax); } + break; case IBinaryOperation binary: @@ -117,6 +119,7 @@ private void OnCompilationStart(CompilationStartAnalysisContext compilationConte VerifySymbol(context.ReportDiagnostic, binary.OperatorMethod, context.Operation.Syntax); VerifyType(context.ReportDiagnostic, binary.OperatorMethod.ContainingType, context.Operation.Syntax); } + break; case IIncrementOrDecrementOperation incrementOrDecrement: @@ -125,6 +128,7 @@ private void OnCompilationStart(CompilationStartAnalysisContext compilationConte VerifySymbol(context.ReportDiagnostic, incrementOrDecrement.OperatorMethod, context.Operation.Syntax); VerifyType(context.ReportDiagnostic, incrementOrDecrement.OperatorMethod.ContainingType, context.Operation.Syntax); } + break; case ITypeOfOperation typeOfOperation: VerifyType(context.ReportDiagnostic, typeOfOperation.TypeOperand, context.Operation.Syntax); @@ -220,6 +224,7 @@ bool VerifyTypeArguments(Action reportDiagnostic, ITypeSymbol? type, return false; } } + break; case IArrayTypeSymbol arrayTypeSymbol: diff --git a/src/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator/AbstractResxGenerator.cs b/src/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator/AbstractResxGenerator.cs index f3eeb1d731..a4f114220c 100644 --- a/src/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator/AbstractResxGenerator.cs +++ b/src/Microsoft.CodeAnalysis.ResxSourceGenerator/Microsoft.CodeAnalysis.ResxSourceGenerator/AbstractResxGenerator.cs @@ -304,6 +304,7 @@ public bool Execute(GeneratorExecutionContext context) RenderFormatMethod(memberIndent, language, strings, resourceString); } } + break; case Lang.VisualBasic: @@ -324,6 +325,7 @@ public bool Execute(GeneratorExecutionContext context) { throw new NotImplementedException(); } + break; default: @@ -378,6 +380,7 @@ public bool Execute(GeneratorExecutionContext context) {memberIndent}}} "; } + break; case Lang.VisualBasic: @@ -390,6 +393,7 @@ public bool Execute(GeneratorExecutionContext context) { throw new NotImplementedException(); } + break; default: @@ -450,6 +454,7 @@ public bool Execute(GeneratorExecutionContext context) {resourceTypeDefinition} }}"; } + break; case Lang.VisualBasic: @@ -461,6 +466,7 @@ public bool Execute(GeneratorExecutionContext context) {resourceTypeDefinition} End Namespace"; } + break; default: @@ -603,6 +609,7 @@ private static string CreateStringLiteral(string original, Lang lang) { stringLiteral.Append('@'); } + stringLiteral.Append('\"'); for (var i = 0; i < original.Length; i++) { @@ -611,8 +618,10 @@ private static string CreateStringLiteral(string original, Lang lang) { stringLiteral.Append('"'); } + stringLiteral.Append(original[i]); } + stringLiteral.Append('\"'); return stringLiteral.ToString(); @@ -644,6 +653,7 @@ private static void RenderFormatMethod(string indent, Lang language, StringBuild { strings.AppendLine($@"{indent} => string.Format(Culture, GetResourceString(""{resourceString.Name}"") ?? """", {resourceString.GetArguments()});"); } + strings.AppendLine(); } diff --git a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/InteropServices/CSharpDisableRuntimeMarshalling.FixAllProvider.cs b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/InteropServices/CSharpDisableRuntimeMarshalling.FixAllProvider.cs index 4bb27f03de..8a5093a4f8 100644 --- a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/InteropServices/CSharpDisableRuntimeMarshalling.FixAllProvider.cs +++ b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/InteropServices/CSharpDisableRuntimeMarshalling.FixAllProvider.cs @@ -28,6 +28,7 @@ protected override async Task FixAllInDocumentAsync(FixAllContext fi // We can't code fix if unsafe code isn't allowed. return await document.GetSyntaxRootAsync(fixAllContext.CancellationToken); } + var editor = await DocumentEditor.CreateAsync(document, fixAllContext.CancellationToken).ConfigureAwait(false); SyntaxNode root = await document.GetSyntaxRootAsync(fixAllContext.CancellationToken).ConfigureAwait(false); @@ -47,12 +48,14 @@ protected override async Task FixAllInDocumentAsync(FixAllContext fi { identifierGenerator = scopeMap[block] = new IdentifierGenerator(editor.SemanticModel, block); } + if (TryRewriteMethodCall(node, editor, identifierGenerator, addRenameAnnotation: false, fixAllContext.CancellationToken)) { AddUnsafeModifierToEnclosingMethod(editor, node); } } } + return editor.GetChangedRoot(); } } diff --git a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/InteropServices/CSharpDisableRuntimeMarshalling.Fixer.IdentifierGenerator.cs b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/InteropServices/CSharpDisableRuntimeMarshalling.Fixer.IdentifierGenerator.cs index 407b3787e5..6bddfc2b6d 100644 --- a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/InteropServices/CSharpDisableRuntimeMarshalling.Fixer.IdentifierGenerator.cs +++ b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/InteropServices/CSharpDisableRuntimeMarshalling.Fixer.IdentifierGenerator.cs @@ -26,6 +26,7 @@ public IdentifierGenerator(SemanticModel model, IBlockOperation block) { identifier = NextIdentifier(); } + if (identifier is not null) { // The last identifier was not in use, so go back one to use it the next call. diff --git a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/InteropServices/CSharpDisableRuntimeMarshalling.Fixer.cs b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/InteropServices/CSharpDisableRuntimeMarshalling.Fixer.cs index cf5225a0aa..27fd23f8e8 100644 --- a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/InteropServices/CSharpDisableRuntimeMarshalling.Fixer.cs +++ b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/InteropServices/CSharpDisableRuntimeMarshalling.Fixer.cs @@ -32,6 +32,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) // We can't code fix if unsafe code isn't allowed. return; } + SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false); SyntaxNode enclosingNode = root.FindNode(context.Span); @@ -64,6 +65,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) return i; } } + return 0; } @@ -102,6 +104,7 @@ private static bool TryRewriteMethodCall(SyntaxNode node, DocumentEditor editor, return true; } } + if (operation.TargetMethod.Name == "StructureToPtr" && operation.Arguments[0].Value.Type.IsUnmanagedType) { editor.ReplaceNode(syntax, @@ -112,6 +115,7 @@ private static bool TryRewriteMethodCall(SyntaxNode node, DocumentEditor editor, operation.Arguments[0].Value.Syntax)); return true; } + if (operation.TargetMethod.Name == "PtrToStructure") { ITypeSymbol type; @@ -178,6 +182,7 @@ private static bool TryRewriteMethodCall(SyntaxNode node, DocumentEditor editor, { return false; } + editor.ReplaceNode(syntax, replacementNode); return true; } diff --git a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/InteropServices/CSharpDynamicInterfaceCastableImplementation.Fixer.cs b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/InteropServices/CSharpDynamicInterfaceCastableImplementation.Fixer.cs index 2ddd4b6858..a82b96d21a 100644 --- a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/InteropServices/CSharpDynamicInterfaceCastableImplementation.Fixer.cs +++ b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/InteropServices/CSharpDynamicInterfaceCastableImplementation.Fixer.cs @@ -70,6 +70,7 @@ protected override async Task ImplementInterfacesOnDynamicCastableImpl { return null; } + var methodDeclaration = generator.MethodDeclaration(method); methodDeclaration = generator.WithModifiers(methodDeclaration, generator.GetModifiers(methodDeclaration).WithIsAbstract(false)); return generator.WithStatements(methodDeclaration, defaultMethodBodyStatements); @@ -90,6 +91,7 @@ SyntaxNode GeneratePropertyImplementation(IPropertySymbol property) { propertyDeclaration = generator.WithGetAccessorStatements(propertyDeclaration, defaultMethodBodyStatements); } + if (property.SetMethod is not null && model.Compilation.IsSymbolAccessibleWithin(property.SetMethod, type)) { diff --git a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Performance/CSharpConstantExpectedAnalyzer.cs b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Performance/CSharpConstantExpectedAnalyzer.cs index ae87caec60..56d1ad9f08 100644 --- a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Performance/CSharpConstantExpectedAnalyzer.cs +++ b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Performance/CSharpConstantExpectedAnalyzer.cs @@ -55,6 +55,7 @@ private sealed class CSharpDiagnosticHelper : DiagnosticHelper { return null; } + var targetArg = attributeSyntax.ArgumentList.Arguments.FirstOrDefault(arg => arg.NameEquals.Name.IsEquivalentTo(targetNameSyntax, true)); return targetArg?.GetLocation(); } diff --git a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Performance/CSharpPreferHashDataOverComputeHash.Fixer.cs b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Performance/CSharpPreferHashDataOverComputeHash.Fixer.cs index 428e14cb5d..f8b4ddf2e5 100644 --- a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Performance/CSharpPreferHashDataOverComputeHash.Fixer.cs +++ b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Performance/CSharpPreferHashDataOverComputeHash.Fixer.cs @@ -53,6 +53,7 @@ protected override SyntaxNode GetHashDataSyntaxNode(PreferHashDataOverComputeHas { arg = arg.WithNameColon(arg.NameColon.WithName(SyntaxFactory.IdentifierName("source"))); } + var args = SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(arg)); return SyntaxFactory.InvocationExpression(hashData, args); } @@ -69,6 +70,7 @@ protected override SyntaxNode GetHashDataSyntaxNode(PreferHashDataOverComputeHas { list[secondArgIndex] = secondArg.WithNameColon(SyntaxFactory.NameColon(SyntaxFactory.IdentifierName("start"))); } + var thirdArg = list[thirdArgIndex]; if (thirdArg.NameColon is not null) { @@ -90,6 +92,7 @@ protected override SyntaxNode GetHashDataSyntaxNode(PreferHashDataOverComputeHas { arg = arg.WithNameColon(SyntaxFactory.NameColon(SyntaxFactory.IdentifierName("source"))); } + var args = SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(arg)); return SyntaxFactory.InvocationExpression(hashData, args); } @@ -135,6 +138,7 @@ protected override SyntaxNode FixHashCreateNode(SyntaxNode root, SyntaxNode crea break; } } + return root; } @@ -165,6 +169,7 @@ private SyntaxNode MoveStatementsOutOfUsingStatementWithFormatting(SyntaxNode ro newTrivia = AddRangeIfInteresting(newTrivia, usingStatement.GetTrailingTrivia()); statement = statement.WithTrailingTrivia(newTrivia); } + return statement; }); @@ -197,7 +202,6 @@ protected override bool IsInterestingTrivia(SyntaxTriviaList triviaList) { ns = qualifiedNamespaceSyntax.ToFullString(); } - } else if (invocationNode.Expression is MemberAccessExpressionSyntax { Expression: InvocationExpressionSyntax { Expression: MemberAccessExpressionSyntax { Expression: MemberAccessExpressionSyntax originalType } } }) { @@ -214,7 +218,6 @@ protected override bool IsInterestingTrivia(SyntaxTriviaList triviaList) ns = qualifiedNamespaceSyntax.ToFullString(); } - return ns; } } diff --git a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Performance/CSharpPreferIsEmptyOverCount.Fixer.cs b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Performance/CSharpPreferIsEmptyOverCount.Fixer.cs index 41cff783e0..a6e20d6901 100644 --- a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Performance/CSharpPreferIsEmptyOverCount.Fixer.cs +++ b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Performance/CSharpPreferIsEmptyOverCount.Fixer.cs @@ -25,18 +25,21 @@ public sealed class CSharpPreferIsEmptyOverCountFixer : PreferIsEmptyOverCountFi { countNode = binaryExpression.Left; } + break; case UseCountProperlyAnalyzer.OperationBinaryRight: if (node is BinaryExpressionSyntax binaryExpression2) { countNode = binaryExpression2.Right; } + break; case UseCountProperlyAnalyzer.OperationEqualsArgument: if (node is InvocationExpressionSyntax invocationExpression) { countNode = invocationExpression.ArgumentList.Arguments[0].Expression; } + break; case UseCountProperlyAnalyzer.OperationEqualsInstance: if (node is InvocationExpressionSyntax invocationExpression2) @@ -47,6 +50,7 @@ public sealed class CSharpPreferIsEmptyOverCountFixer : PreferIsEmptyOverCountFi countNode = memberAccess.Expression; } } + break; } diff --git a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Performance/CSharpUseStringContainsCharOverloadWithSingleCharactersFixer.cs b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Performance/CSharpUseStringContainsCharOverloadWithSingleCharactersFixer.cs index a9109695d6..1b77ee9e54 100644 --- a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Performance/CSharpUseStringContainsCharOverloadWithSingleCharactersFixer.cs +++ b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Performance/CSharpUseStringContainsCharOverloadWithSingleCharactersFixer.cs @@ -23,6 +23,7 @@ protected override bool TryGetArgumentName(SyntaxNode violatingNode, out string argumentName = argumentSyntax.NameColon.Name.Identifier.ValueText; return true; } + return false; } @@ -38,6 +39,7 @@ protected override bool TryGetLiteralValueFromNode(SyntaxNode violatingNode, out { return TryGetCharFromLiteralExpressionSyntax(containedLiteralExpressionSyntax, out charLiteral); } + return false; static bool TryGetCharFromLiteralExpressionSyntax(LiteralExpressionSyntax sourceLiteralExpressionSyntax, out char parsedCharLiteral) @@ -47,6 +49,7 @@ static bool TryGetCharFromLiteralExpressionSyntax(LiteralExpressionSyntax source { return true; } + return false; } } diff --git a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Runtime/CSharpDoNotUseStackallocInLoops.cs b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Runtime/CSharpDoNotUseStackallocInLoops.cs index e5eeac01f4..1a7c3c6af9 100644 --- a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Runtime/CSharpDoNotUseStackallocInLoops.cs +++ b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Runtime/CSharpDoNotUseStackallocInLoops.cs @@ -44,6 +44,7 @@ public sealed override void Initialize(AnalysisContext context) { continue; } + goto case SyntaxKind.WhileStatement; // fall through // Look for loops. We don't bother with ad-hoc loops via gotos as we're diff --git a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Runtime/CSharpForwardCancellationTokenToInvocations.Analyzer.cs b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Runtime/CSharpForwardCancellationTokenToInvocations.Analyzer.cs index 9cfc35814c..a1bee06b5c 100644 --- a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Runtime/CSharpForwardCancellationTokenToInvocations.Analyzer.cs +++ b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Runtime/CSharpForwardCancellationTokenToInvocations.Analyzer.cs @@ -24,8 +24,10 @@ public sealed class CSharpForwardCancellationTokenToInvocationsAnalyzer : Forwar // so that the diagnostic gets properly returned in the method name only. return memberBindingExpression.Name; } + return invocationExpression.Expression; } + return null; } protected override bool ArgumentsImplicitOrNamed(INamedTypeSymbol cancellationTokenType, ImmutableArray arguments) diff --git a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Runtime/CSharpPreferStreamAsyncMemoryOverloads.Fixer.cs b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Runtime/CSharpPreferStreamAsyncMemoryOverloads.Fixer.cs index 2a404d335c..e4a2cac869 100644 --- a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Runtime/CSharpPreferStreamAsyncMemoryOverloads.Fixer.cs +++ b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Runtime/CSharpPreferStreamAsyncMemoryOverloads.Fixer.cs @@ -63,6 +63,7 @@ protected override bool IsSystemNamespaceImported(IReadOnlyList impo return true; } } + return false; } @@ -90,6 +91,7 @@ thirdArgumentMemberAccessExpression.Expression is IdentifierNameSyntax thirdArgu } } } + return false; } diff --git a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Runtime/CSharpSpecifyCultureForToLowerAndToUpper.cs b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Runtime/CSharpSpecifyCultureForToLowerAndToUpper.cs index 73ab4650d9..adf2cdba42 100644 --- a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Runtime/CSharpSpecifyCultureForToLowerAndToUpper.cs +++ b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Runtime/CSharpSpecifyCultureForToLowerAndToUpper.cs @@ -25,6 +25,7 @@ protected override Location GetMethodNameLocation(SyntaxNode invocationNode) { return memberBinding.Name.GetLocation(); } + return invocation.GetLocation(); } } diff --git a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Runtime/CSharpUseSpanBasedStringConcat.Fixer.cs b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Runtime/CSharpUseSpanBasedStringConcat.Fixer.cs index 5752b4600c..b95f6fa13f 100644 --- a/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Runtime/CSharpUseSpanBasedStringConcat.Fixer.cs +++ b/src/NetAnalyzers/CSharp/Microsoft.NetCore.Analyzers/Runtime/CSharpUseSpanBasedStringConcat.Fixer.cs @@ -28,6 +28,7 @@ private protected override bool IsSystemNamespaceImported(Project project, IRead if (import is UsingDirectiveSyntax { Name: IdentifierNameSyntax { Identifier.ValueText: nameof(System) } }) return true; } + return false; } diff --git a/src/NetAnalyzers/CSharp/Microsoft.NetFramework.Analyzers/Helpers/SyntaxNodeHelper.cs b/src/NetAnalyzers/CSharp/Microsoft.NetFramework.Analyzers/Helpers/SyntaxNodeHelper.cs index 726d0f7f6c..2acfc81112 100644 --- a/src/NetAnalyzers/CSharp/Microsoft.NetFramework.Analyzers/Helpers/SyntaxNodeHelper.cs +++ b/src/NetAnalyzers/CSharp/Microsoft.NetFramework.Analyzers/Helpers/SyntaxNodeHelper.cs @@ -160,6 +160,7 @@ private CSharpSyntaxNodeHelper() } } } + return null; } @@ -179,6 +180,7 @@ protected override IEnumerable GetCallArgumentExpressionNodes(Syntax var invocationNode = (ObjectCreationExpressionSyntax)node; argList = invocationNode.ArgumentList; } + if (argList != null) { return argList.Arguments.Select(arg => arg.Expression); @@ -217,6 +219,7 @@ public override bool IsMethodInvocationNode(SyntaxNode? node) { return false; } + SyntaxKind kind = node.Kind(); return kind is SyntaxKind.InvocationExpression or SyntaxKind.ObjectCreationExpression; } diff --git a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/CollectionsShouldImplementGenericInterface.cs b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/CollectionsShouldImplementGenericInterface.cs index 2507a39a43..0358e53113 100644 --- a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/CollectionsShouldImplementGenericInterface.cs +++ b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/CollectionsShouldImplementGenericInterface.cs @@ -147,6 +147,7 @@ private static void AnalyzeSymbol(SymbolAnalysisContext context, ImmutableArray< { ReportDiagnostic(kvp.Key, kvp.Value[0]); } + return; } } diff --git a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/DefineAccessorsForAttributeArguments.Fixer.cs b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/DefineAccessorsForAttributeArguments.Fixer.cs index be06227cbb..d176c1ac89 100644 --- a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/DefineAccessorsForAttributeArguments.Fixer.cs +++ b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/DefineAccessorsForAttributeArguments.Fixer.cs @@ -42,6 +42,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) equivalenceKey: title), diagnostic); } + return; case DefineAccessorsForAttributeArgumentsAnalyzer.MakePublicCase: @@ -54,6 +55,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) equivalenceKey: title), diagnostic); } + return; case DefineAccessorsForAttributeArgumentsAnalyzer.RemoveSetterCase: diff --git a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/EnumShouldNotHaveDuplicatedValues.cs b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/EnumShouldNotHaveDuplicatedValues.cs index b1af731ef4..5cc71a87c7 100644 --- a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/EnumShouldNotHaveDuplicatedValues.cs +++ b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/EnumShouldNotHaveDuplicatedValues.cs @@ -126,12 +126,14 @@ void visitInitializerValue(IOperation operation) { context.ReportDiagnostic(fieldOperation.CreateDiagnostic(RuleDuplicatedBitwiseValuePart, referencedField.Name)); } + break; default: foreach (var childOperation in operation.Children) { visitInitializerValue(childOperation); } + break; } } @@ -145,6 +147,7 @@ void endVisitEnumSymbol(SymbolAnalysisContext context) var duplicatedField = membersByValue[field.ConstantValue]; context.ReportDiagnostic(field.CreateDiagnostic(RuleDuplicatedValue, field.Name, field.ConstantValue, duplicatedField.Name)); } + duplicates.Free(context.CancellationToken); membersByValue.Free(context.CancellationToken); } diff --git a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/ExceptionsShouldBePublic.cs b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/ExceptionsShouldBePublic.cs index 82465d9ef2..95155c4dde 100644 --- a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/ExceptionsShouldBePublic.cs +++ b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/ExceptionsShouldBePublic.cs @@ -63,7 +63,8 @@ private static void AnalyzeCompilationStart(CompilationStartAnalysisContext csCo var symbol = (INamedTypeSymbol)saContext.Symbol; // skip public symbols - if (symbol.IsPublic()) return; + if (symbol.IsPublic()) + return; // only report if base type matches if (symbol.BaseType != null && exceptionTypes.Contains(symbol.BaseType)) diff --git a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/Maintainability/AvoidUninstantiatedInternalClasses.cs b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/Maintainability/AvoidUninstantiatedInternalClasses.cs index 614889bd70..92414bbeaa 100644 --- a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/Maintainability/AvoidUninstantiatedInternalClasses.cs +++ b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/Maintainability/AvoidUninstantiatedInternalClasses.cs @@ -216,6 +216,7 @@ bool CanBeDesignerAttributeContext(INamedTypeSymbol type) { return namedType; } + break; } @@ -246,6 +247,7 @@ bool CanBeDebuggerTypeProxyAttributeContext(INamedTypeSymbol type) { return namedType; } + break; } diff --git a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/Maintainability/DoNotIgnoreMethodResults.cs b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/Maintainability/DoNotIgnoreMethodResults.cs index 66575322a9..b08712f7de 100644 --- a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/Maintainability/DoNotIgnoreMethodResults.cs +++ b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/Maintainability/DoNotIgnoreMethodResults.cs @@ -173,6 +173,7 @@ public override void Initialize(AnalysisContext context) rule = ObjectCreationRule; targetMethodName = ctor.ContainingType.Name; } + break; case OperationKind.Invocation: diff --git a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/Maintainability/UseNameofInPlaceOfString.cs b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/Maintainability/UseNameofInPlaceOfString.cs index b85d070d2f..afd4490429 100644 --- a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/Maintainability/UseNameofInPlaceOfString.cs +++ b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/Maintainability/UseNameofInPlaceOfString.cs @@ -70,12 +70,14 @@ private void AnalyzeArgument(OperationAnalysisContext context) { context.ReportDiagnostic(argument.Value.CreateDiagnostic(RuleWithSuggestion, stringText)); } + return; case PropertyName: if (HasAnyPropertyMatchInScope(context, stringText)) { context.ReportDiagnostic(argument.Value.CreateDiagnostic(RuleWithSuggestion, stringText)); } + return; default: return; diff --git a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/QualityGuidelines/AssigningSymbolAndItsMemberInSameStatement.cs b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/QualityGuidelines/AssigningSymbolAndItsMemberInSameStatement.cs index 2e6b6abcb3..723facc2bd 100644 --- a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/QualityGuidelines/AssigningSymbolAndItsMemberInSameStatement.cs +++ b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/QualityGuidelines/AssigningSymbolAndItsMemberInSameStatement.cs @@ -89,6 +89,7 @@ private static bool AnalyzeAssignmentToMember(ISimpleAssignmentOperation assi return true; } } + return false; } } diff --git a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/QualityGuidelines/AvoidDuplicateElementInitialization.cs b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/QualityGuidelines/AvoidDuplicateElementInitialization.cs index 0c2a3617b9..dca43411de 100644 --- a/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/QualityGuidelines/AvoidDuplicateElementInitialization.cs +++ b/src/NetAnalyzers/Core/Microsoft.CodeQuality.Analyzers/QualityGuidelines/AvoidDuplicateElementInitialization.cs @@ -91,6 +91,7 @@ private static ImmutableArray GetConstantArgumentValues(ImmutableArray>.GetHashCode(ImmutableArray hash = unchecked((hash * (int)0xA5555529) + _objectComparer.GetHashCode(item)); } } + return hash; } } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/DisableRuntimeMarshalling.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/DisableRuntimeMarshalling.cs index f105702d9f..7f9d420d37 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/DisableRuntimeMarshalling.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/DisableRuntimeMarshalling.cs @@ -153,6 +153,7 @@ public override void Initialize(AnalysisContext context) var disabledRuntimeMarshallingAssemblyAnalyzer = new DisabledRuntimeMarshallingAssemblyAnalyzer(context.Compilation, autoLayoutCache); disabledRuntimeMarshallingAssemblyAnalyzer.RegisterActions(context); } + var delegateInteropUsageAnalyzer = new DelegateInteropUsageAnalyzer(context.Compilation, autoLayoutCache, disableRuntimeMarshallingAttribute); delegateInteropUsageAnalyzer.RegisterActions(context, hasDisableRuntimeMarshallingAttribute); } @@ -169,6 +170,7 @@ private static void AnalyzeMethodSignature(AutoLayoutTypeCache autoLayoutCache, { reportDiagnostic(paramLocation.CreateDiagnostic(descriptorOverride ?? FeatureUnsupportedWhenRuntimeMarshallingDisabledByRefParameters)); } + AnalyzeSignatureType(paramLocation, param.Type); } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/DisableRuntimeMarshallingAnalyzer.DisabledRuntimeMarshallingAssemblyAnalyzer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/DisableRuntimeMarshallingAnalyzer.DisabledRuntimeMarshallingAssemblyAnalyzer.cs index 5ae8e9adc5..a013f4c14e 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/DisableRuntimeMarshallingAnalyzer.DisabledRuntimeMarshallingAssemblyAnalyzer.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/DisableRuntimeMarshallingAnalyzer.DisabledRuntimeMarshallingAssemblyAnalyzer.cs @@ -34,6 +34,7 @@ public DisabledRuntimeMarshallingAssemblyAnalyzer(Compilation compilation, AutoL marshalMethods.AddRange(marshalType.GetMembers("PtrToStructure")); _marshalMethods = marshalMethods.ToImmutable(); } + _autoLayoutCache = autoLayoutCache; } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/DynamicInterfaceCastableImplementation.Fixer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/DynamicInterfaceCastableImplementation.Fixer.cs index 32e7b29b47..eb5501bdd7 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/DynamicInterfaceCastableImplementation.Fixer.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/DynamicInterfaceCastableImplementation.Fixer.cs @@ -34,6 +34,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) { return; } + foreach (Diagnostic diagnostic in context.Diagnostics) { if (diagnostic.Id == DynamicInterfaceCastableImplementationAnalyzer.InterfaceMembersMissingImplementationRuleId) diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/DynamicInterfaceCastableImplementation.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/DynamicInterfaceCastableImplementation.cs index ba36699443..7ffc6c3922 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/DynamicInterfaceCastableImplementation.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/DynamicInterfaceCastableImplementation.cs @@ -139,6 +139,7 @@ private static void AnalyzeType(SymbolAnalysisContext context, INamedTypeSymbol { propertyBag = propertyBag.Add(NonStaticMemberIsMethodKey, string.Empty); } + context.ReportDiagnostic(member.CreateDiagnostic(MembersDeclaredOnImplementationTypeMustBeStatic, propertyBag, member.ToDisplayString(), targetType.ToDisplayString())); } } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/PlatformCompatibilityAnalyzer.OperationVisitor.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/PlatformCompatibilityAnalyzer.OperationVisitor.cs index 492d720e4d..dedef5ccb4 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/PlatformCompatibilityAnalyzer.OperationVisitor.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/PlatformCompatibilityAnalyzer.OperationVisitor.cs @@ -136,6 +136,7 @@ public bool TryDecodeGuardAttributes(SmallDictionary mappedAtt { infosBuilder.RemoveAt(index); } + v.SupportedFirst = null; v.UnsupportedFirst = null; } @@ -146,6 +147,7 @@ public bool TryDecodeGuardAttributes(SmallDictionary mappedAtt } } } + return infosBuilder.Any(); } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/PlatformCompatibilityAnalyzer.Value.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/PlatformCompatibilityAnalyzer.Value.cs index 3af28b5fc2..bdefd0c069 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/PlatformCompatibilityAnalyzer.Value.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/PlatformCompatibilityAnalyzer.Value.cs @@ -129,6 +129,7 @@ private static bool TryDecodeRuntimeInformationIsOSPlatform( { decodedOsPlatformNamesBuilder.Add(propertyReference.Property.Name); } + return true; } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/PlatformCompatibilityAnalyzer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/PlatformCompatibilityAnalyzer.cs index 6086108e20..be22ce5653 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/PlatformCompatibilityAnalyzer.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/PlatformCompatibilityAnalyzer.cs @@ -502,6 +502,7 @@ static bool IsKnownValueGuarded( attribute.SupportedSecond = null; attribute.UnsupportedSecond = null; } + attribute.UnsupportedFirst = null; attribute.UnsupportedMessage = null; } @@ -706,6 +707,7 @@ static SmallDictionary SetCallSiteSupportedAttribute(SmallDict { attributes.SupportedSecond = info.Version; } + attributes.UnsupportedFirst = unsupportedVersion; } else @@ -753,6 +755,7 @@ static void RemoveUnsupportsOnDifferentPlatforms(SmallDictionary operatio { ReportUnsupportedDiagnostic(operationToSymbol.Key, context, operationName, attributes, csAttributes); } + break; } @@ -868,6 +872,7 @@ static bool GetSupportedPlatforms(SmallDictionary attributes, platformsBuilder.Add(GetFormattedString(PlatformCompatibilityAllVersions, pName)); continue; } + platformsBuilder.Add(EncloseWithQuotes(pName)); } else @@ -881,6 +886,7 @@ static bool GetSupportedPlatforms(SmallDictionary attributes, { platformsBuilder.Clear(); } + supportedRule = false; if (IsEmptyVersion(pAttribute.UnsupportedFirst)) { @@ -889,6 +895,7 @@ static bool GetSupportedPlatforms(SmallDictionary attributes, platformsBuilder.Add(AppendMessage(pAttribute, GetFormattedString(PlatformCompatibilityAllVersions, pName))); continue; } + platformsBuilder.Add(AppendMessage(pAttribute, EncloseWithQuotes(pName))); } else @@ -906,6 +913,7 @@ static bool GetSupportedPlatforms(SmallDictionary attributes, return supportedRule.GetValueOrDefault(true); } } + static DiagnosticDescriptor SwitchObsoletedRule(Callsite callsite) { return callsite switch @@ -957,6 +965,7 @@ static string AppendMessageAndUrl(Versions attribute, string message) { customMessge = $"{customMessge} {attribute.ObsoletedUrl}"; } + message += string.Format(CultureInfo.InvariantCulture, ParenthesisWithPlaceHolder, customMessge); } else if (attribute.ObsoletedUrl is not null) @@ -1126,6 +1135,7 @@ static ImmutableArray GetCallsitePlatforms(SmallDictionary GetCallsitePlatforms(SmallDictionary GetCallsitePlatforms(SmallDictionary at version = supportedVersion.IsGreaterThanOrEqualTo(version) ? supportedVersion : version; } } + if (version != null && !IsEmptyVersion(version)) { return true; } } + return false; } @@ -1234,6 +1248,7 @@ static bool HasVersionedCallsite(SmallDictionary csAttributes, return true; } } + return false; } } @@ -1290,6 +1305,7 @@ private static ISymbol GetEventAccessor(IEventSymbol iEvent, IOperation operatio else return iEvent.RemoveMethod; } + return iEvent; } @@ -1429,6 +1445,7 @@ private static PlatformAttributes CopyAttributes(PlatformAttributes copyAttribut { copy.Platforms!.Add(platformName, CopyAllAttributes(new Versions(), attributes)); } + copy.IsAssemblyAttribute = copyAttributes.IsAssemblyAttribute; return copy; } @@ -1667,6 +1684,7 @@ private static bool IsNotSuppressedByCallSite(SmallDictionary } } } + return !notSuppressedAttributes.IsEmpty; static void AddOrUpdatedDiagnostic(Versions operationAttributes, @@ -1678,6 +1696,7 @@ static void AddOrUpdatedDiagnostic(Versions operationAttributes, { diagnosticAttribute = new Versions(); } + diagnosticAttribute.SupportedFirst = (Version)operationAttributes.SupportedFirst.Clone(); notSuppressedAttributes[name] = diagnosticAttribute; } @@ -1776,8 +1795,10 @@ static void MergePlatformAttributes(ImmutableArray immediateAttri { parentAttributes = new PlatformAttributes(); } + return; } + if (s_osPlatformAttributes.Contains(attribute.AttributeClass.Name)) { TryAddValidAttribute(ref childAttributes, attribute, relatedPlatforms); @@ -1817,11 +1838,13 @@ static void MergePlatformAttributes(ImmutableArray immediateAttri existing.SupportedFirst = childAttribute.SupportedFirst; } } + if (childAttribute.UnsupportedSecond != null && (existing.UnsupportedSecond == null || childAttribute.UnsupportedSecond < existing.UnsupportedSecond)) { existing.UnsupportedSecond = childAttribute.UnsupportedSecond; } + if (existing.SupportedFirst != null && childAttribute.SupportedFirst != null && childAttribute.SupportedFirst > existing.SupportedFirst) @@ -1881,6 +1904,7 @@ static void MergePlatformAttributes(ImmutableArray immediateAttri { attributes.SupportedSecond = null; } + if (childAttribute.UnsupportedSecond != null && childAttribute.UnsupportedSecond > attributes.UnsupportedFirst) { attributes.UnsupportedFirst = childAttribute.UnsupportedSecond; @@ -1935,6 +1959,7 @@ static void MergePlatformAttributes(ImmutableArray immediateAttri parentAttributes.Callsite = Callsite.Empty; } } + parentAttributes.IsAssemblyAttribute = false; } else @@ -1944,6 +1969,7 @@ static void MergePlatformAttributes(ImmutableArray immediateAttri { pAttributes[platform] = attributes; } + parentAttributes.Platforms = pAttributes; } @@ -1966,6 +1992,7 @@ static void CheckAttributesConsistency(SmallDictionary childAt unsupportedList.Add(platform); } } + if (allowList && unsupportedList.Count > 0) { foreach (var name in unsupportedList) @@ -1993,6 +2020,7 @@ static Versions NormalizeAttribute(Versions attributes) { attributes.UnsupportedSecond = null; } + return attributes; } } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/ProvidePublicParameterlessSafeHandleConstructor.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/ProvidePublicParameterlessSafeHandleConstructor.cs index 5c9c2b77a9..152d4ee2c1 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/ProvidePublicParameterlessSafeHandleConstructor.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/InteropServices/ProvidePublicParameterlessSafeHandleConstructor.cs @@ -59,6 +59,7 @@ private static void AnalyzeSymbol(SymbolAnalysisContext context, INamedTypeSymbo // We only want to put the diagnostic on concrete SafeHandle-derived types. return; } + foreach (var constructor in type.InstanceConstructors) { if (constructor.Parameters.Length == 0) @@ -68,6 +69,7 @@ private static void AnalyzeSymbol(SymbolAnalysisContext context, INamedTypeSymbo // The parameterless constructor is as visible as the containing type, so there is no diagnostic to emit. return; } + context.ReportDiagnostic(constructor.CreateDiagnostic(Rule, type.Name)); break; } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/ConstantExpectedAnalyzer.UnmanagedHelper.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/ConstantExpectedAnalyzer.UnmanagedHelper.cs index 5060578fd6..5e7228d0ca 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/ConstantExpectedAnalyzer.UnmanagedHelper.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/ConstantExpectedAnalyzer.UnmanagedHelper.cs @@ -154,6 +154,7 @@ private bool IsValidMinMax(AttributeData attributeData, T typeMin, T typeMax, ou errorFlags = ErrorKind.MinMaxInverted; return false; } + return true; } } @@ -186,6 +187,7 @@ public override bool ValidateParameterIsWithinRange(ConstantExpectedParameter su validationDiagnostics = null; return true; } + validationDiagnostics = CreateConstantOutOfBoundsRuleDiagnostic(argument, Min.ToString(), Max.ToString()); return false; } @@ -204,9 +206,11 @@ public override bool ValidateValue(IArgumentOperation argument, Optional validationDiagnostics = null; return true; } + validationDiagnostics = CreateConstantOutOfBoundsRuleDiagnostic(argument, Min.ToString(), Max.ToString()); return false; } + validationDiagnostics = CreateConstantInvalidConstantRuleDiagnostic(argument); return false; } @@ -222,6 +226,7 @@ private static bool TryConvertSignedInteger(object constant, out long integer) integer = default; return false; } + integer = Convert.ToInt64(constant); } catch @@ -229,6 +234,7 @@ private static bool TryConvertSignedInteger(object constant, out long integer) integer = default; return false; } + return true; } private static bool TryConvertUnsignedInteger(object constant, out ulong integer) @@ -240,6 +246,7 @@ private static bool TryConvertUnsignedInteger(object constant, out ulong integer integer = default; return false; } + integer = Convert.ToUInt64(constant); } catch @@ -247,6 +254,7 @@ private static bool TryConvertUnsignedInteger(object constant, out ulong integer integer = default; return false; } + return true; } @@ -258,10 +266,12 @@ private static bool TryTransformInt64(object constant, out long value, out bool { return isValidSigned; } + if (!TryConvertUnsignedInteger(constant, out _)) { isInvalid = true; } + return isValidSigned; } private static bool TryTransformUInt64(object constant, out ulong value, out bool isInvalid) @@ -272,10 +282,12 @@ private static bool TryTransformUInt64(object constant, out ulong value, out boo { return isValidUnsigned; } + if (!TryConvertSignedInteger(constant, out _)) { isInvalid = true; } + return isValidUnsigned; } @@ -287,12 +299,14 @@ private static bool TryTransformChar(object constant, out char value, out bool i { return Invalid(out value, out isInvalid); } + value = Convert.ToChar(constant); } catch { return Invalid(out value, out isInvalid); } + isInvalid = false; return true; } @@ -305,6 +319,7 @@ private static bool TryTransformBoolean(object constant, out bool value, out boo isInvalid = false; return true; } + return Invalid(out value, out isInvalid); } @@ -314,6 +329,7 @@ private static bool TryTransformSingle(object constant, out float value, out boo { return Invalid(out value, out isInvalid); } + value = Convert.ToSingle(constant); isInvalid = false; return true; @@ -325,6 +341,7 @@ private static bool TryTransformDouble(object constant, out double value, out bo { return Invalid(out value, out isInvalid); } + value = Convert.ToDouble(constant); isInvalid = false; return true; diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/ConstantExpectedAnalyzer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/ConstantExpectedAnalyzer.cs index 4d9ad2ab30..9e556afe3e 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/ConstantExpectedAnalyzer.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/ConstantExpectedAnalyzer.cs @@ -135,6 +135,7 @@ private void OnCompilationStart(CompilationStartAnalysisContext context) { return; } + context.RegisterOperationAction(context => OnInvocation(context, constantExpectedContext), OperationKind.Invocation); context.RegisterSymbolAction(context => OnMethodSymbol(context, constantExpectedContext), SymbolKind.Method); RegisterAttributeSyntax(context, constantExpectedContext); @@ -157,7 +158,6 @@ private static void OnMethodSymbol(SymbolAnalysisContext context, ConstantExpect CheckParameters(methodSymbol.Parameters, interfaceMethodSymbol.Parameters); } - void CheckParameters(ImmutableArray parameters, ImmutableArray baseParameters) { if (constantExpectedContext.ValidatesAttributeImplementedFromParent(parameters, baseParameters, out var diagnostics)) @@ -182,6 +182,7 @@ private static void OnInvocation(OperationAnalysisContext context, ConstantExpec { continue; } + var v = argument.Value.WalkDownConversion(); if (v is IParameterReferenceOperation parameterReference && constantExpectedContext.TryCreateConstantExpectedParameter(parameterReference.Parameter, out var currConstantParameter)) @@ -190,8 +191,10 @@ private static void OnInvocation(OperationAnalysisContext context, ConstantExpec { context.ReportDiagnostic(parameterCheckDiagnostic); } + continue; } + var constantValue = v.ConstantValue; if (!argConstantParameter.ValidateValue(argument, constantValue, out var valueDiagnostic)) { @@ -238,6 +241,7 @@ public bool ValidatesAttributeImplementedFromParent(ImmutableArray.Empty; return true; } @@ -478,6 +485,7 @@ public bool ValidateConstant(IArgumentOperation argument, Optional const validationDiagnostics = argument.CreateDiagnostic(CA1857.ConstantNotConstantRule); return false; } + validationDiagnostics = null; return true; } @@ -498,6 +506,7 @@ public override bool ValidateParameterIsWithinRange(ConstantExpectedParameter su validationDiagnostics = CreateConstantInvalidConstantRuleDiagnostic(argument); return false; } + validationDiagnostics = null; return true; } @@ -508,11 +517,13 @@ public override bool ValidateValue(IArgumentOperation argument, Optional { return false; } + if (constant.Value is not string and not null) { validationDiagnostics = CreateConstantInvalidConstantRuleDiagnostic(argument); return false; } + validationDiagnostics = null; return true; } @@ -525,6 +536,7 @@ public static bool TryCreate(IParameterSymbol parameterSymbol, AttributeData att parameter = null; return false; } + parameter = new StringConstantExpectedParameter(parameterSymbol); return true; } @@ -565,12 +577,12 @@ public static AttributeConstant Get(AttributeData attributeData) { return null; } + return typedConstant.Kind == TypedConstantKind.Array ? typedConstant.Values : typedConstant.Value; } } } - protected abstract class DiagnosticHelper { public abstract Location? GetMinLocation(SyntaxNode attributeSyntax); diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/DoNotGuardDictionaryRemoveByContainsKey.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/DoNotGuardDictionaryRemoveByContainsKey.cs index cbd7dfadf8..4f790af82a 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/DoNotGuardDictionaryRemoveByContainsKey.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/DoNotGuardDictionaryRemoveByContainsKey.cs @@ -117,6 +117,7 @@ static void AnalyzeOperation(OperationAnalysisContext context, IMethodSymbol con } } } + static bool TryGetDictionaryTypeAndMethods(Compilation compilation, [NotNullWhen(true)] out IMethodSymbol? containsKey, [NotNullWhen(true)] out IMethodSymbol? remove1Param, out IMethodSymbol? remove2Param) { @@ -141,12 +142,14 @@ static bool TryGetDictionaryTypeAndMethods(Compilation compilation, [NotNullWhen case ContainsKey: containsKey = m; break; case Remove: remove1Param = m; break; } + break; case 2: if (m.Name == Remove) { remove2Param = m; } + break; } } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/PreferHashDataOverComputeHash.Fixer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/PreferHashDataOverComputeHash.Fixer.cs index ff0d15f6dd..102cd32643 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/PreferHashDataOverComputeHash.Fixer.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/PreferHashDataOverComputeHash.Fixer.cs @@ -111,6 +111,7 @@ protected override async Task GetChangedSolutionAsync(CancellationToke { continue; } + SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var hashInstanceTargets = CollectTargets(root, grouping, cancellationToken); @@ -142,6 +143,7 @@ protected override async Task GetChangedSolutionAsync(CancellationToke dictionary.Free(cancellationToken); return null; } + var hashInstanceTargets = dictionary.Values.Append(new HashInstanceTarget(chainedComputeHashList)).ToArray(); dictionary.Free(cancellationToken); return hashInstanceTargets; @@ -154,19 +156,23 @@ bool CollectNodes() { return false; } + if (!_helper.TryGetHashCreationNode(root, d, out var createNode, out var hashCreationIndex)) { chainedComputeHashList.Add(computeHashSyntaxHolder); continue; } + if (!dictionary.TryGetValue(createNode, out HashInstanceTarget hashInstanceTarget)) { var disposeNodes = _helper.GetDisposeNodes(root, d, hashCreationIndex); hashInstanceTarget = new HashInstanceTarget(createNode, disposeNodes); dictionary.Add(createNode, hashInstanceTarget); } + hashInstanceTarget.ComputeHashNodes.Add(computeHashSyntaxHolder); } + return true; } } @@ -177,6 +183,7 @@ internal SyntaxNode FixDocumentRoot(SyntaxNode root, HashInstanceTarget[] hashIn { root = _helper.FixHashInstanceTarget(root, target); } + return root; } } @@ -243,11 +250,13 @@ protected abstract class PreferHashDataOverComputeHashFixAllProvider : FixAllPro ImmutableArray diagnostics = await fixAllContext.GetAllDiagnosticsAsync(project).ConfigureAwait(false); diagnosticsToFix.Add(new KeyValuePair>(project, diagnostics)); } + break; } default: return null; } + return new PreferHashDataOverComputeHashFixAllCodeAction(title, fixAllContext.Solution, diagnosticsToFix, Helper); } } @@ -263,12 +272,14 @@ public bool TryComputeHashNode(SyntaxNode root, Diagnostic diagnostic, [NotNullW computeHashHolder = null; return false; } + var computeHashNode = root.FindNode(diagnostic.Location.SourceSpan, getInnermostNodeForTie: true); if (computeHashNode is null) { computeHashHolder = null; return false; } + var hashTypeName = diagnostic.Properties[PreferHashDataOverComputeHashAnalyzer.TargetHashTypeDiagnosticPropertyKey]; computeHashHolder = new ComputeHashSyntaxHolder(computeHashNode, computeType, hashTypeName); @@ -309,6 +320,7 @@ public bool TryGetHashCreationNode(SyntaxNode root, Diagnostic diagnostic, [NotN { return null; } + var disposeNodes = new SyntaxNode[disposeCount]; for (int i = 0; i < disposeNodes.Length; i++) @@ -318,8 +330,10 @@ public bool TryGetHashCreationNode(SyntaxNode root, Diagnostic diagnostic, [NotN { return null; } + disposeNodes[i] = node; } + return disposeNodes; } @@ -332,6 +346,7 @@ public SyntaxNode TrackTargets(SyntaxNode root, HashInstanceTarget[] targets) { list.Add(t.CreateNode); } + if (t.DisposeNodes is not null) { list.AddRange(t.DisposeNodes); @@ -353,6 +368,7 @@ public SyntaxNode TrackTarget(SyntaxNode root, HashInstanceTarget target) { list.Add(target.CreateNode); } + if (target.DisposeNodes is not null) { list.AddRange(target.DisposeNodes); @@ -393,6 +409,7 @@ public SyntaxNode FixHashInstanceTarget(SyntaxNode root, HashInstanceTarget hash var trackedDisposeNode = root.GetCurrentNode(disposeNode); root = RemoveNodeWithFormatting(root, trackedDisposeNode); } + return root; } protected SyntaxNode RemoveNodeWithFormatting(SyntaxNode root, SyntaxNode nodeToRemove) @@ -402,10 +419,12 @@ protected SyntaxNode RemoveNodeWithFormatting(SyntaxNode root, SyntaxNode nodeTo { option |= SyntaxRemoveOptions.KeepLeadingTrivia; } + if (IsInterestingTrivia(nodeToRemove.GetTrailingTrivia())) { option |= SyntaxRemoveOptions.KeepTrailingTrivia; } + var parent = nodeToRemove.Parent; root = root.TrackNodes(parent); var newParent = parent.RemoveNode(nodeToRemove, option) @@ -420,6 +439,7 @@ protected SyntaxTriviaList AddRangeIfInteresting(SyntaxTriviaList triviaList, Sy { triviaList = triviaList.AddRange(triviaToAdd); } + return triviaList; } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/PreferHashDataOverComputeHash.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/PreferHashDataOverComputeHash.cs index f8ba580eab..0abdab46a9 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/PreferHashDataOverComputeHash.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/PreferHashDataOverComputeHash.cs @@ -144,6 +144,7 @@ void CaptureHashObjectCreationOperation(OperationAnalysisContext context) { return; } + if (TryGetVariableInitializerOperation(objectCreationOperation.Parent, out var variableInitializerOperation)) { CaptureVariableDeclaratorOperation(dataCollector, objectCreationOperation.Type, variableInitializerOperation); @@ -177,6 +178,7 @@ void OnOperationBlockEnd(OperationBlockAnalysisContext context) context.ReportDiagnostic(diagnostics); } } + dataResult.Free(cancellationToken); } } @@ -247,7 +249,7 @@ private static bool TryGetVariableInitializerOperation(IOperation symbol, [NotNu default: variableInitializerOperation = null; return false; - }; + } } private static Diagnostic CreateDiagnostics(IInvocationOperation computeHashMethod, @@ -311,6 +313,7 @@ private static ImmutableArray GetValueOrEmpty(PooledDictio { return value; } + return ImmutableArray.Empty; } @@ -403,11 +406,13 @@ public bool IsComputeHashMethod(IInvocationOperation invocationOperation, out Co computeType = ComputeType.ComputeHash; return true; } + if (IsComputeHashSectionMethod(invocationOperation)) { computeType = ComputeType.ComputeHashSection; return true; } + if (IsTryComputeHashMethod(invocationOperation)) { computeType = ComputeType.TryComputeHash; @@ -508,6 +513,7 @@ private static bool IsSpecialManagedHashAlgorithms(ITypeSymbol originalHashType) { return null; } + var rosByteType = rosType.Construct(byteType); var spanByteType = spanType.Construct(byteType); @@ -640,6 +646,7 @@ private sealed class DataCollector { count = 0; } + localRefSymbolCountMap[local] = count + 1; } @@ -650,6 +657,7 @@ private sealed class DataCollector { count = 0; } + computeHashSymbolCountMap[local] = count + 1; } @@ -659,6 +667,7 @@ private sealed class DataCollector { continue; } + var disposeArray = GetValueOrEmpty(disposeMap, local); var refCountWithoutDispose = refCount - disposeArray.Length; diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/UseCountProperly.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/UseCountProperly.cs index 708a961df7..77d6a2a538 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/UseCountProperly.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/UseCountProperly.cs @@ -511,6 +511,7 @@ private static bool IsLeftCountComparison(IBinaryOperation binaryOperation, out default: return false; } + break; case 1: switch (binaryOperation.OperatorKind) @@ -524,6 +525,7 @@ private static bool IsLeftCountComparison(IBinaryOperation binaryOperation, out default: return false; } + break; default: return false; @@ -559,6 +561,7 @@ private static bool IsRightCountComparison(IBinaryOperation binaryOperation, out default: return false; } + break; case 1: switch (binaryOperation.OperatorKind) @@ -574,6 +577,7 @@ private static bool IsRightCountComparison(IBinaryOperation binaryOperation, out default: return false; } + break; default: return false; diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/UseStringContainsCharOverloadWithSingleCharacters.Fixer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/UseStringContainsCharOverloadWithSingleCharacters.Fixer.cs index 9c14a62aae..1af27a1c79 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/UseStringContainsCharOverloadWithSingleCharacters.Fixer.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/UseStringContainsCharOverloadWithSingleCharacters.Fixer.cs @@ -71,6 +71,7 @@ protected override async Task GetChangedDocumentAsync(CancellationToke { newExpression = editor.Generator.Argument(_argumentName, RefKind.None, newExpression); } + editor.ReplaceNode(_nodeToBeFixed, newExpression); return editor.GetChangedDocument(); diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/UseStringContainsCharOverloadWithSingleCharactersAnalyzer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/UseStringContainsCharOverloadWithSingleCharactersAnalyzer.cs index eca54ef9a6..0648ca75ca 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/UseStringContainsCharOverloadWithSingleCharactersAnalyzer.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Performance/UseStringContainsCharOverloadWithSingleCharactersAnalyzer.cs @@ -54,6 +54,7 @@ private void CheckIfRuleIsApplicableAndRegister(CompilationStartAnalysisContext { return m.Parameters[0].Type.SpecialType == SpecialType.System_Char; } + return false; }); @@ -89,6 +90,7 @@ static bool CheckForViolation(IArgumentOperation primaryArgument) { return true; } + return false; } } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/BufferBlockCopyLengthAnalyzer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/BufferBlockCopyLengthAnalyzer.cs index 0f3f4ae881..226639fd6f 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/BufferBlockCopyLengthAnalyzer.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/BufferBlockCopyLengthAnalyzer.cs @@ -99,6 +99,7 @@ bool CheckArgumentArrayType(IArgumentOperation targetArgument, IPropertyReferenc } } } + return false; } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DetectPreviewFeatureAnalyzer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DetectPreviewFeatureAnalyzer.cs index c28816f46d..4c5c596963 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DetectPreviewFeatureAnalyzer.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DetectPreviewFeatureAnalyzer.cs @@ -305,6 +305,7 @@ public override void Initialize(AnalysisContext context) return previewSymbol; } } + if (SymbolIsAnnotatedAsPreview(typeParameter, requiresPreviewFeaturesSymbols, previewFeatureAttributeSymbol)) { return typeParameter; diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DoNotRaiseReservedExceptionTypes.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DoNotRaiseReservedExceptionTypes.cs index a507b1c09f..c1cb4e1676 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DoNotRaiseReservedExceptionTypes.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/DoNotRaiseReservedExceptionTypes.cs @@ -110,10 +110,12 @@ private static ImmutableHashSet CreateSymbolSet(Compilation co { continue; } + if (set == null) { set = new HashSet(); } + set.Add(symbol); } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/ForwardCancellationTokenToInvocations.Analyzer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/ForwardCancellationTokenToInvocations.Analyzer.cs index 3067d29a8c..a8dd734d98 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/ForwardCancellationTokenToInvocations.Analyzer.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/ForwardCancellationTokenToInvocations.Analyzer.cs @@ -300,6 +300,7 @@ private static bool InvocationIgnoresOptionalCancellationToken( arguments, a => a.Parameter.Type.Equals(cancellationTokenType) && a.ArgumentKind == ArgumentKind.DefaultValue); } + return false; } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/InstantiateArgumentExceptionsCorrectly.Fixer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/InstantiateArgumentExceptionsCorrectly.Fixer.cs index 1c13032339..775e1c58c6 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/InstantiateArgumentExceptionsCorrectly.Fixer.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/InstantiateArgumentExceptionsCorrectly.Fixer.cs @@ -64,6 +64,7 @@ private static async Task PopulateCodeFixAsync(CodeFixContext context, Diagnosti createChangedDocument: c => SwapArgumentsOrderAsync(context.Document, creation, paramPosition, creation.Arguments.Length, c), equivalenceKey: MicrosoftNetCoreAnalyzersResources.InstantiateArgumentExceptionsCorrectlyFlipArgumentOrderCodeFixTitle); } + context.RegisterCodeFix(codeAction, diagnostic); } } @@ -97,6 +98,7 @@ private static async Task SwapArgumentsOrderAsync(Document document, I newCreation = editor.Generator.ObjectCreationExpression(creation.Type, parameter, creation.Arguments[1].Syntax, creation.Arguments[0].Syntax); } } + editor.ReplaceNode(creation.Syntax, newCreation); return editor.GetChangedDocument(); } @@ -116,6 +118,7 @@ private static SyntaxNode AddNameOfIfLiteral(IOperation expression, SyntaxGenera { return generator.NameOfExpression(generator.IdentifierName(literal.ConstantValue.Value.ToString())); } + return expression.Syntax; } } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/InstantiateArgumentExceptionsCorrectly.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/InstantiateArgumentExceptionsCorrectly.cs index 76be088859..387835adb1 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/InstantiateArgumentExceptionsCorrectly.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/InstantiateArgumentExceptionsCorrectly.cs @@ -253,6 +253,7 @@ private static bool MatchesParameterCore(ISymbol? symbol, string stringArgumentV } } } + return false; } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/LoggerMessageDefineAnalyzer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/LoggerMessageDefineAnalyzer.cs index 310e78a904..b7cfd0a768 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/LoggerMessageDefineAnalyzer.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/LoggerMessageDefineAnalyzer.cs @@ -191,6 +191,7 @@ private void AnalyzeFormatArgument(OperationAnalysisContext context, IOperation { context.ReportDiagnostic(formatExpression.CreateDiagnostic(CA2254Rule, methodSymbol.ToDisplayString(GetLanguageSpecificFormat(formatExpression)))); } + return; } @@ -279,6 +280,7 @@ private static bool FindLogParameters(IMethodSymbol methodSymbol, [NotNullWhen(t arguments = parameter; } } + return message != null; } } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/ModuleInitializerAttributeShouldNotBeUsedInLibraries.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/ModuleInitializerAttributeShouldNotBeUsedInLibraries.cs index c20db43a1e..d39c5deb7f 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/ModuleInitializerAttributeShouldNotBeUsedInLibraries.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/ModuleInitializerAttributeShouldNotBeUsedInLibraries.cs @@ -51,7 +51,8 @@ public override void Initialize(AnalysisContext context) } // Only validate libraries (which will still produce some false positives, but that is acceptable) - if (context.Compilation.Options.OutputKind != OutputKind.DynamicallyLinkedLibrary) return; + if (context.Compilation.Options.OutputKind != OutputKind.DynamicallyLinkedLibrary) + return; context.RegisterSymbolAction(context => { diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/NormalizeStringsToUppercase.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/NormalizeStringsToUppercase.cs index 48d02dc6cd..8349b07e86 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/NormalizeStringsToUppercase.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/NormalizeStringsToUppercase.cs @@ -74,6 +74,7 @@ protected override void InitializeWorker(CompilationStartAnalysisContext context { return; } + var method = invocation.TargetMethod; if (method.Equals(toLowerInvariant) || (method.Equals(toLowerWithCultureInfo) && diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/PreferStreamAsyncMemoryOverloads.Fixer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/PreferStreamAsyncMemoryOverloads.Fixer.cs index 40ce34e236..9c269eccbe 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/PreferStreamAsyncMemoryOverloads.Fixer.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/PreferStreamAsyncMemoryOverloads.Fixer.cs @@ -173,6 +173,7 @@ private Task FixInvocationAsync(SemanticModel model, Document doc, Syn { nodeArguments = new SyntaxNode[] { replacedInvocationNode }; } + SyntaxNode newInvocationExpression = generator.InvocationExpression(asyncMethodNode, nodeArguments).WithTriviaFrom(streamInstanceNode); bool containsSystemImport = IsSystemNamespaceImported(generator.GetNamespaceImports(root)); diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/PreferStreamAsyncMemoryOverloads.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/PreferStreamAsyncMemoryOverloads.cs index df9861d8ff..007bab58e1 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/PreferStreamAsyncMemoryOverloads.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/PreferStreamAsyncMemoryOverloads.cs @@ -236,6 +236,7 @@ x.Parameters[0].Type is INamedTypeSymbol type && // Prevent use of unassigned variables error return; } + context.ReportDiagnostic(invocation.CreateDiagnostic(rule, ruleMessageMethod, ruleMessagePreferredMethod)); } }, diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/PreferStringContainsOverIndexOfAnalyzer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/PreferStringContainsOverIndexOfAnalyzer.cs index 7424a15d6a..3e27549737 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/PreferStringContainsOverIndexOfAnalyzer.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/PreferStringContainsOverIndexOfAnalyzer.cs @@ -136,6 +136,7 @@ void PopulateLocalReferencesSet(OperationAnalysisContext context) return; } } + localsToBailOut.Add(localReference.Local); } @@ -181,6 +182,7 @@ static bool CheckOperatorKindAndOperand(IBinaryOperation binaryOperation, IOpera return true; } } + return false; } @@ -194,6 +196,7 @@ void OnOperationBlockEnd(OperationBlockAnalysisContext context) context.ReportDiagnostic(variableNameAndLocation.Value.CreateDiagnostic(Rule)); } } + variableNameToOperationsMap.Free(context.CancellationToken); localsToBailOut.Free(context.CancellationToken); } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/SealInternalTypes.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/SealInternalTypes.cs index f70db6761c..f75043d48a 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/SealInternalTypes.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/SealInternalTypes.cs @@ -70,7 +70,6 @@ private static void OnCompilationStart(CompilationStartAnalysisContext context) { baseTypes.Add(baseType.OriginalDefinition); } - }, SymbolKind.NamedType); context.RegisterCompilationEndAction(context => diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/UseAsyncMethodInAsyncContext.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/UseAsyncMethodInAsyncContext.cs index 0b542df6de..2c4e3204a2 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/UseAsyncMethodInAsyncContext.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/UseAsyncMethodInAsyncContext.cs @@ -234,6 +234,7 @@ static bool CheckReturnTypeMatch(string targetType, ISymbol returnType, Concurre { return method; } + containingSymbol = containingSymbol.ContainingSymbol; } @@ -264,7 +265,8 @@ private static bool InspectAndReportBlockingMemberAccess(OperationAnalysisContex foreach (SyncBlockingSymbol symbol in syncBlockingSymbols) { - if (symbol.Kind != kind) continue; + if (symbol.Kind != kind) + continue; if (symbol.Value.Equals(memberSymbol.OriginalDefinition)) { Diagnostic diagnostic = context.Operation.Syntax.CreateDiagnostic( @@ -276,6 +278,7 @@ private static bool InspectAndReportBlockingMemberAccess(OperationAnalysisContex return true; } } + return false; } } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/UseExceptionThrowHelpers.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/UseExceptionThrowHelpers.cs index c789078f2a..a7d001cea3 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/UseExceptionThrowHelpers.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/UseExceptionThrowHelpers.cs @@ -189,6 +189,7 @@ aooreThrowIfGreaterThan is not null || aooreThrowIfGreaterThanOrEqual is not nul properties: null, args: new object[] { nameof(ArgumentNullException), "ThrowIfNull" })); } + return; } @@ -204,6 +205,7 @@ aooreThrowIfGreaterThan is not null || aooreThrowIfGreaterThanOrEqual is not nul properties: null, args: new object[] { nameof(ArgumentException), "ThrowIfNullOrEmpty" })); } + return; } @@ -242,6 +244,7 @@ static bool AvoidComparing(IParameterReferenceOperation p) => p.Type.IsNullableValueType() || p.Type.TypeKind == TypeKind.Enum; } + return; } @@ -274,6 +277,7 @@ nameReference.Instance is IInvocationOperation getTypeCall && properties: null, args: new object[] { nameof(ObjectDisposedException), "ThrowIf" })); } + return; } }, OperationKind.Throw); @@ -441,6 +445,7 @@ private static bool IsNegativeAndOrZeroComparison(IOperation condition, [NotNull parameterReferenceOperation = binaryOperation.LeftOperand as IParameterReferenceOperation; return parameterReferenceOperation is not null; } + break; case BinaryOperatorKind.LessThanOrEqual or BinaryOperatorKind.LessThan: @@ -453,6 +458,7 @@ private static bool IsNegativeAndOrZeroComparison(IOperation condition, [NotNull parameterReferenceOperation = leftOperandParameterReference; return true; } + break; case BinaryOperatorKind.GreaterThanOrEqual or BinaryOperatorKind.GreaterThan: @@ -465,6 +471,7 @@ private static bool IsNegativeAndOrZeroComparison(IOperation condition, [NotNull parameterReferenceOperation = rightOperationParameterReference; return true; } + break; } } @@ -522,6 +529,7 @@ private static bool IsGreaterLessThanComparison(IOperation condition, [NotNullWh parameterReferenceOperation = rightParameter; return true; } + break; } } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/UseSpanBasedStringConcat.Fixer.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/UseSpanBasedStringConcat.Fixer.cs index ca1083ea25..33018429a9 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/UseSpanBasedStringConcat.Fixer.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/UseSpanBasedStringConcat.Fixer.cs @@ -139,6 +139,7 @@ private SyntaxNode ConvertOperandToArgument(in RequiredSymbols symbols, SyntaxGe var renamedArgumentSyntax = generator.Argument(AsSpanStartParameterName, RefKind.None, namedStartIndexArgument.Value.Syntax); invocationSyntax = generator.ReplaceNode(invocationSyntax, namedStartIndexArgument.Syntax, renamedArgumentSyntax); } + var asSpanInvocationSyntax = ReplaceInvocationMethodName(generator, invocationSyntax, AsSpanName); return generator.Argument(asSpanInvocationSyntax); } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/UseThreadStaticCorrectly.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/UseThreadStaticCorrectly.cs index c7cb42ff11..db41113943 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/UseThreadStaticCorrectly.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Runtime/UseThreadStaticCorrectly.cs @@ -94,7 +94,6 @@ public override void Initialize(AnalysisContext context) break; } } - }, OperationKind.FieldInitializer); }); } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/PotentialReferenceCycleInDeserializedObjectGraph.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/PotentialReferenceCycleInDeserializedObjectGraph.cs index 996b26bd07..0c1253f706 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/PotentialReferenceCycleInDeserializedObjectGraph.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Security/PotentialReferenceCycleInDeserializedObjectGraph.cs @@ -178,7 +178,11 @@ static HashSet GetAssociatedTypes(ITypeSymbol type) // graph: The graph void AddLine(ISymbol from, ISymbol to, ConcurrentDictionary degree, ConcurrentDictionary> graph) { - graph.AddOrUpdate(from, new ConcurrentDictionary { [to] = true }, (k, v) => { v[to] = true; return v; }); + graph.AddOrUpdate(from, new ConcurrentDictionary { [to] = true }, (k, v) => + { + v[to] = true; + return v; + }); degree.AddOrUpdate(from, 1, (k, v) => v + 1); } diff --git a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Tasks/UseValueTasksCorrectly.cs b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Tasks/UseValueTasksCorrectly.cs index 29380944b6..e8b76d7c5a 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Tasks/UseValueTasksCorrectly.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetCore.Analyzers/Tasks/UseValueTasksCorrectly.cs @@ -168,6 +168,7 @@ public sealed override void Initialize(AnalysisContext context) return; } } + goto default; case OperationKind.ExpressionStatement: @@ -186,6 +187,7 @@ public sealed override void Initialize(AnalysisContext context) operation = operation.Parent; continue; } + goto default; // At this point, we're "in the weeds", but there are still some rare-but-used valid patterns to check for. @@ -388,6 +390,7 @@ private static bool TryGetLocalSymbolAssigned(IOperation? operation, [NotNullWhe startingBlock = cfg.GetEntry(); return true; } + break; case OperationKind.SimpleAssignment: @@ -407,6 +410,7 @@ private static bool TryGetLocalSymbolAssigned(IOperation? operation, [NotNullWhe return true; } } + break; } diff --git a/src/NetAnalyzers/Core/Microsoft.NetFramework.Analyzers/DoNotUseInsecureDtdProcessing.cs b/src/NetAnalyzers/Core/Microsoft.NetFramework.Analyzers/DoNotUseInsecureDtdProcessing.cs index 2a7b121ebf..d88459668e 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetFramework.Analyzers/DoNotUseInsecureDtdProcessing.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetFramework.Analyzers/DoNotUseInsecureDtdProcessing.cs @@ -237,6 +237,7 @@ public void AnalyzeOperation(OperationAnalysisContext context) { AnalyzeObjectCreationInternal(context, field, fieldInitializer.Value); } + break; case OperationKind.VariableDeclarator: var declarator = (IVariableDeclaratorOperation)context.Operation; diff --git a/src/NetAnalyzers/Core/Microsoft.NetFramework.Analyzers/DoNotUseInsecureDtdProcessingInApiDesign.cs b/src/NetAnalyzers/Core/Microsoft.NetFramework.Analyzers/DoNotUseInsecureDtdProcessingInApiDesign.cs index 50258cb331..c431716e64 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetFramework.Analyzers/DoNotUseInsecureDtdProcessingInApiDesign.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetFramework.Analyzers/DoNotUseInsecureDtdProcessingInApiDesign.cs @@ -99,6 +99,7 @@ public void AnalyzeOperationBlock(OperationBlockStartAnalysisContext context) { AnalyzeBlockForXmlTextReaderDerivedTypeConstructorDecl(context); } + AnalyzeBlockForXmlTextReaderDerivedTypeMethodDecl(context); } @@ -330,6 +331,7 @@ private void AnalyzeBlockForXmlTextReaderDerivedTypeMethodDecl( { locations.Enqueue(assignment.Syntax.GetLocation()); } + return; } diff --git a/src/NetAnalyzers/Core/Microsoft.NetFramework.Analyzers/Helpers/SecurityDiagnosticHelpers.cs b/src/NetAnalyzers/Core/Microsoft.NetFramework.Analyzers/Helpers/SecurityDiagnosticHelpers.cs index 1cccd0cd1d..7659e80e79 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetFramework.Analyzers/Helpers/SecurityDiagnosticHelpers.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetFramework.Analyzers/Helpers/SecurityDiagnosticHelpers.cs @@ -186,6 +186,7 @@ private static int GetSpecifiedParameterIndex(IMethodSymbol? method, Compilation { return index; } + for (int i = 0; i < method.Parameters.Length; i++) { ITypeSymbol parameter = method.Parameters[i].Type; @@ -299,16 +300,19 @@ public static string GetNonEmptyParentName(ISymbol symbol) { return new Version(4, 6); } + INamedTypeSymbol typeSymbol = mscorlibAssembly.GetTypeByMetadataName(WellKnownTypeNames.SystemIOUnmanagedMemoryStream); if (!typeSymbol.GetMembers("FlushAsync").IsEmpty) { return new Version(4, 5, 2); } + typeSymbol = mscorlibAssembly.GetTypeByMetadataName(WellKnownTypeNames.SystemDiagnosticsTracingEventSource); if (typeSymbol != null) { return typeSymbol.GetMembers("CurrentThreadActivityId").IsEmpty ? new Version(4, 5) : new Version(4, 5, 1); } + return new Version(4, 0); } } diff --git a/src/NetAnalyzers/Core/Microsoft.NetFramework.Analyzers/Helpers/SyntaxNodeHelper.cs b/src/NetAnalyzers/Core/Microsoft.NetFramework.Analyzers/Helpers/SyntaxNodeHelper.cs index d90a247f4f..4da324a6da 100644 --- a/src/NetAnalyzers/Core/Microsoft.NetFramework.Analyzers/Helpers/SyntaxNodeHelper.cs +++ b/src/NetAnalyzers/Core/Microsoft.NetFramework.Analyzers/Helpers/SyntaxNodeHelper.cs @@ -132,6 +132,7 @@ public static bool NodeHasConstantValueNull(SyntaxNode? node, SemanticModel? mod { return false; } + Optional value = model.GetConstantValue(node); return value.HasValue && value.Value == null; } @@ -142,6 +143,7 @@ public static bool NodeHasConstantValueBoolFalse(SyntaxNode? node, SemanticModel { return false; } + Optional value = model.GetConstantValue(node); return value.HasValue && value.Value is false; diff --git a/src/NetAnalyzers/UnitTests/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/EnumsShouldHaveZeroValueTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/EnumsShouldHaveZeroValueTests.cs index 3fad324f64..9a1d85b211 100644 --- a/src/NetAnalyzers/UnitTests/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/EnumsShouldHaveZeroValueTests.cs +++ b/src/NetAnalyzers/UnitTests/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/EnumsShouldHaveZeroValueTests.cs @@ -497,6 +497,7 @@ public enum E3 { csTest.ExpectedDiagnostics.Add(GetCSharpRenameResultAt(14, 5, "E2", "Never")); } + if (!editorConfigText.EndsWith("Zero")) { csTest.ExpectedDiagnostics.Add(GetCSharpRenameResultAt(21, 5, "E3", "Zero")); @@ -542,6 +543,7 @@ Public Enum E3 { vbTest.ExpectedDiagnostics.Add(GetCSharpRenameResultAt(12, 5, "E2", "Never")); } + if (!editorConfigText.EndsWith("Zero")) { vbTest.ExpectedDiagnostics.Add(GetCSharpRenameResultAt(18, 5, "E3", "Zero")); diff --git a/src/NetAnalyzers/UnitTests/Microsoft.CodeQuality.Analyzers/QualityGuidelines/AvoidMultipleEnumerationsTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.CodeQuality.Analyzers/QualityGuidelines/AvoidMultipleEnumerationsTests.cs index ce96e147a1..00b0dcbd5e 100644 --- a/src/NetAnalyzers/UnitTests/Microsoft.CodeQuality.Analyzers/QualityGuidelines/AvoidMultipleEnumerationsTests.cs +++ b/src/NetAnalyzers/UnitTests/Microsoft.CodeQuality.Analyzers/QualityGuidelines/AvoidMultipleEnumerationsTests.cs @@ -3897,7 +3897,6 @@ End Module await VerifyVisualBasicAsync(vbCode); } - [Theory] [InlineData("HashSet")] [InlineData("LinkedList")] diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/InteropServices/DisableRuntimeMarshallingTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/InteropServices/DisableRuntimeMarshallingTests.cs index 4c08c17593..47855b548a 100644 --- a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/InteropServices/DisableRuntimeMarshallingTests.cs +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/InteropServices/DisableRuntimeMarshallingTests.cs @@ -160,7 +160,6 @@ class C await VerifyCSAnalyzerAsync(source); } - [Fact] public async Task VB_PInvokeWithClassReturnValue_Emits_Diagnostic() { diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/InteropServices/PlatformCompatibilityAnalyzer.ObsoletedOSPlatformTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/InteropServices/PlatformCompatibilityAnalyzer.ObsoletedOSPlatformTests.cs index c841e2f33a..959b59650f 100644 --- a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/InteropServices/PlatformCompatibilityAnalyzer.ObsoletedOSPlatformTests.cs +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/InteropServices/PlatformCompatibilityAnalyzer.ObsoletedOSPlatformTests.cs @@ -44,7 +44,6 @@ public void ObsoletedOnLinux4AndWindows10() { } await VerifyAnalyzerCSAsync(csSource, VerifyCS.Diagnostic(PlatformCompatibilityAnalyzer.ObsoletedCsReachable).WithLocation(0) .WithArguments("Test.ObsoletedOnLinux4()", "'Linux' 4.1 and later", "'Linux'")); - var vbSource = @" Imports System Imports System.Runtime.Versioning diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/InteropServices/PlatformCompatibilityAnalyzerTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/InteropServices/PlatformCompatibilityAnalyzerTests.cs index e6adadd4fb..b3a0c64352 100644 --- a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/InteropServices/PlatformCompatibilityAnalyzerTests.cs +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/InteropServices/PlatformCompatibilityAnalyzerTests.cs @@ -228,7 +228,6 @@ public class Test await VerifyAnalyzerCSAsync(csSource, "build_property.PlatformNeutralAssembly = true\nbuild_property.TargetFramework=net5.0"); } - [Fact] public async Task OnlyThrowsNotSupportedWithOsDependentStringNotWarnsAsync() { diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Performance/DoNotUseCountWhenAnyCanBeUsedTests.Code.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Performance/DoNotUseCountWhenAnyCanBeUsedTests.Code.cs index b8fe4c08e4..88192887f5 100644 --- a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Performance/DoNotUseCountWhenAnyCanBeUsedTests.Code.cs +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Performance/DoNotUseCountWhenAnyCanBeUsedTests.Code.cs @@ -395,7 +395,8 @@ public static int GetNumberOfLines(string source) { var numberOfLines = 0; var index = -Environment.NewLine.Length; - while ((index = source.IndexOf(Environment.NewLine, index + Environment.NewLine.Length, StringComparison.Ordinal)) >= 0) numberOfLines++; + while ((index = source.IndexOf(Environment.NewLine, index + Environment.NewLine.Length, StringComparison.Ordinal)) >= 0) + numberOfLines++; return numberOfLines; } } diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Performance/DoNotUseCountWhenAnyCanBeUsedTests.Data.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Performance/DoNotUseCountWhenAnyCanBeUsedTests.Data.cs index a3df0aca15..7a47d476d0 100644 --- a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Performance/DoNotUseCountWhenAnyCanBeUsedTests.Data.cs +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Performance/DoNotUseCountWhenAnyCanBeUsedTests.Data.cs @@ -35,6 +35,7 @@ private static TheoryData Build_LeftCount_NoDiagn theoryData.Add((BinaryOperatorKind)fixerData[0], (int)fixerData[1], withPredicate); } } + return theoryData; } @@ -66,6 +67,7 @@ private static TheoryData Build_RightCount_NoDiag theoryData.Add((int)fixerData[0], (BinaryOperatorKind)fixerData[1], withPredicate); } } + return theoryData; } @@ -91,6 +93,7 @@ private static TheoryData Build_LeftCount_F theoryData.Add((BinaryOperatorKind)fixerData[0], (int)fixerData[1], withPredicate, (bool)fixerData[2]); } } + return theoryData; } @@ -103,6 +106,7 @@ private static TheoryData Build_LeftCount_Diagnostic_Th { theoryData.Add((BinaryOperatorKind)fixerData[0], (int)fixerData[1]); } + return theoryData; } @@ -128,6 +132,7 @@ private static TheoryData Build_RightCount_ theoryData.Add((int)fixerData[0], (BinaryOperatorKind)fixerData[1], withPredicate, (bool)fixerData[2]); } } + return theoryData; } @@ -140,6 +145,7 @@ private static TheoryData Build_RightCount_Diagnostic_T { theoryData.Add((int)fixerData[0], (BinaryOperatorKind)fixerData[1]); } + return theoryData; } } diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Performance/PreferHashDataOverComputeHashTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Performance/PreferHashDataOverComputeHashTests.cs index 8ad86c451c..d534e02abf 100644 --- a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Performance/PreferHashDataOverComputeHashTests.cs +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Performance/PreferHashDataOverComputeHashTests.cs @@ -3193,6 +3193,7 @@ private static async Task TestCSAsync(string source, string corrected, params Di var expected = diagnosticResults[i]; test.ExpectedDiagnostics.Add(expected); } + await test.RunAsync(); await GetTestCS(source, source, ReferenceAssemblies.NetCore.NetCoreApp31).RunAsync(); } diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/DoNotUseEnumerableMethodsOnIndexableCollectionsInsteadUseTheCollectionDirectlyTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/DoNotUseEnumerableMethodsOnIndexableCollectionsInsteadUseTheCollectionDirectlyTests.cs index ece435db2e..d8eacae452 100644 --- a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/DoNotUseEnumerableMethodsOnIndexableCollectionsInsteadUseTheCollectionDirectlyTests.cs +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/DoNotUseEnumerableMethodsOnIndexableCollectionsInsteadUseTheCollectionDirectlyTests.cs @@ -387,7 +387,7 @@ public C(IReadOnlyList l) {{|CS0201:l.Count|}}; {csharpFirstOrDefaultAndLastOrDefault} }} -}}"; ; +}}"; var csharpTest = new VerifyCS.Test { @@ -454,7 +454,8 @@ End Sub Private Sub Use(Of U)(p As U) End Sub -End Class"; ; +End Class"; + var vbTest = new VerifyVB.Test { TestState = diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/LoggerMessageDefineTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/LoggerMessageDefineTests.cs index 509fef0b18..f0a3e53caf 100644 --- a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/LoggerMessageDefineTests.cs +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/LoggerMessageDefineTests.cs @@ -147,6 +147,7 @@ public static IEnumerable GenerateTemplateUsages(string template, stri { templateAndArguments = $"{template}, {arguments}"; } + var methods = new[] { "LogTrace", "LogError", "LogWarning", "LogInformation", "LogDebug", "LogCritical" }; var formats = new[] { diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/PreferConstCharOverConstUnitStringTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/PreferConstCharOverConstUnitStringTests.cs index d33665b3ee..ae4c55f8ea 100644 --- a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/PreferConstCharOverConstUnitStringTests.cs +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/PreferConstCharOverConstUnitStringTests.cs @@ -463,6 +463,7 @@ private void TestMethod(int value) { input = "CType(Nothing, String)"; } + string methodParameterInAppend_vb = @" Imports System diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/UseExceptionThrowHelpersTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/UseExceptionThrowHelpersTests.cs index 321565cd5f..35b4a557ac 100644 --- a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/UseExceptionThrowHelpersTests.cs +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Runtime/UseExceptionThrowHelpersTests.cs @@ -331,7 +331,6 @@ void M(T arg) }.RunAsync(); } - [Fact] public async Task ArgumentNullExceptionThrowIfNull_EnsureSystemIsUsed() { diff --git a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Usage/ImplementGenericMathInterfacesCorrectlyTests.cs b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Usage/ImplementGenericMathInterfacesCorrectlyTests.cs index 06cfc0c9f1..db3c6c44d1 100644 --- a/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Usage/ImplementGenericMathInterfacesCorrectlyTests.cs +++ b/src/NetAnalyzers/UnitTests/Microsoft.NetCore.Analyzers/Usage/ImplementGenericMathInterfacesCorrectlyTests.cs @@ -801,4 +801,3 @@ private static VerifyCS.Test PopulateTestCs(string sourceCode, params Diagnostic } } - diff --git a/src/NetAnalyzers/VisualBasic/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/BasicTypesThatOwnDisposableFieldsShouldBeDisposable.vb b/src/NetAnalyzers/VisualBasic/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/BasicTypesThatOwnDisposableFieldsShouldBeDisposable.vb index 7a9cc85719..395b570dc8 100644 --- a/src/NetAnalyzers/VisualBasic/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/BasicTypesThatOwnDisposableFieldsShouldBeDisposable.vb +++ b/src/NetAnalyzers/VisualBasic/Microsoft.CodeQuality.Analyzers/ApiDesignGuidelines/BasicTypesThatOwnDisposableFieldsShouldBeDisposable.vb @@ -39,6 +39,7 @@ Namespace Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines If declarator.Names.Count > 1 Then Continue For End If + Dim firstFieldName = declarator.Names.First() If TypeOf declarator?.Initializer?.Value Is ObjectCreationExpressionSyntax Then Dim field = TryCast(model.GetDeclaredSymbol(firstFieldName, cancellationToken), IFieldSymbol) diff --git a/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Performance/BasicPreferHashDataOverComputeHash.Fixer.vb b/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Performance/BasicPreferHashDataOverComputeHash.Fixer.vb index e0710934c8..98d4173067 100644 --- a/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Performance/BasicPreferHashDataOverComputeHash.Fixer.vb +++ b/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Performance/BasicPreferHashDataOverComputeHash.Fixer.vb @@ -53,6 +53,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Performance Dim variableDeclaratorSyntax = DirectCast(currentCreateNode, VariableDeclaratorSyntax) root = RemoveNodeWithFormatting(root, variableDeclaratorSyntax) End If + Return root End Function @@ -70,6 +71,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Performance newTrivia = AddRangeIfInteresting(newTrivia, usingBlock.EndUsingStatement.GetTrailingTrivia()) statement = statement.WithTrailingTrivia(newTrivia) End If + Return statement End Function) Dim parent = usingBlock.Parent @@ -92,6 +94,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Performance If namespacePrefix IsNot Nothing Then identifier = namespacePrefix + "." + identifier End If + Dim argumentList = DirectCast(computeHashNode, InvocationExpressionSyntax).ArgumentList Select Case computeType Case PreferHashDataOverComputeHashAnalyzer.ComputeType.ComputeHash @@ -104,6 +107,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Performance If arg.IsNamed Then arg = DirectCast(arg, SimpleArgumentSyntax).WithNameColonEquals(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName("source"))) End If + Dim args = SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(Of ArgumentSyntax)(arg)) Return SyntaxFactory.InvocationExpression(hashData, args) Case PreferHashDataOverComputeHashAnalyzer.ComputeType.ComputeHashSection @@ -116,6 +120,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Performance If secondArg.IsNamed Then list(secondArgIndex) = secondArg.WithNameColonEquals(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName("start"))) End If + Dim thirdArg = DirectCast(list(thirdArgIndex), SimpleArgumentSyntax) If thirdArg.IsNamed Then list(thirdArgIndex) = thirdArg.WithNameColonEquals(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName("length"))) @@ -138,6 +143,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Performance If firstArg.IsNamed Then arg = arg.WithNameColonEquals(SyntaxFactory.NameColonEquals(SyntaxFactory.IdentifierName("source"))) End If + Dim args = SyntaxFactory.ArgumentList(SyntaxFactory.SingletonSeparatedList(Of ArgumentSyntax)(arg)) Return SyntaxFactory.InvocationExpression(hashData, args) Case PreferHashDataOverComputeHashAnalyzer.ComputeType.TryComputeHash @@ -149,6 +155,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Performance SyntaxFactory.IdentifierName(PreferHashDataOverComputeHashAnalyzer.TryHashDataMethodName)) Return SyntaxFactory.InvocationExpression(hashData, argumentList) End Select + Debug.Fail("there is only 3 type of ComputeHash") Throw New InvalidOperationException("there is only 3 type of ComputeHash") End Function @@ -188,6 +195,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Performance End If End If End If + Return ns End Function Private Shared Function GetNamespacePrefixes(objectCreation As ObjectCreationExpressionSyntax) As String @@ -198,6 +206,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Performance Return qualifiedNamespace.ToString() End If End If + Return Nothing End Function Private Shared Function GetNamespacePrefixes(invocationExpression As InvocationExpressionSyntax) As String @@ -208,6 +217,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Performance Return originalType.Expression.ToString() End If End If + Return Nothing End Function End Class diff --git a/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Performance/BasicUseStringContainsCharOverloadWithSingleCharactersFixer.vb b/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Performance/BasicUseStringContainsCharOverloadWithSingleCharactersFixer.vb index e96e1c26e2..be0f5fadc2 100644 --- a/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Performance/BasicUseStringContainsCharOverloadWithSingleCharactersFixer.vb +++ b/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Performance/BasicUseStringContainsCharOverloadWithSingleCharactersFixer.vb @@ -16,10 +16,12 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Performance If TypeOf violatingNode IsNot SimpleArgumentSyntax Then Return False End If + Dim argumentSyntax = CType(violatingNode, SimpleArgumentSyntax) If argumentSyntax.NameColonEquals Is Nothing Then Return False End If + argumentName = argumentSyntax.NameColonEquals.Name.Identifier.ValueText Return True End Function @@ -32,8 +34,10 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Performance If TypeOf argumentSyntaxNode.Expression Is LiteralExpressionSyntax Then Return TryGetCharFromLiteralExpressionSyntax(CType(argumentSyntaxNode.Expression, LiteralExpressionSyntax), charLiteral) End If + Return False End If + Return False End Function @@ -41,10 +45,12 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Performance If TypeOf sourceLiteralExpressionSyntax.Token.Value IsNot String Then Return False End If + Dim sourceLiteralValue = CType(sourceLiteralExpressionSyntax.Token.Value, String) If Char.TryParse(sourceLiteralValue, parsedCharLiteral) Then Return True End If + Return False End Function diff --git a/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicDetectPreviewFeatureAnalyzer.vb b/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicDetectPreviewFeatureAnalyzer.vb index afb6dcd100..fbd7d625b8 100644 --- a/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicDetectPreviewFeatureAnalyzer.vb +++ b/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicDetectPreviewFeatureAnalyzer.vb @@ -157,6 +157,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Runtime Return GetSyntaxNodeFromTypeConstraints(methodDeclaration.TypeParameterList, previewInterfaceConstraintSymbol) End If Next + Return Nothing End Function diff --git a/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicPreferDictionaryContainsMethods.Fixer.vb b/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicPreferDictionaryContainsMethods.Fixer.vb index b7c35867ee..33eeeaba08 100644 --- a/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicPreferDictionaryContainsMethods.Fixer.vb +++ b/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicPreferDictionaryContainsMethods.Fixer.vb @@ -42,6 +42,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Runtime Return editor.GetChangedDocument() End Function + Dim codeFixTitle = MicrosoftNetCoreAnalyzersResources.PreferDictionaryContainsKeyCodeFixTitle Dim action = CodeAction.Create(codeFixTitle, ReplaceWithContainsKey, codeFixTitle) context.RegisterCodeFix(action, context.Diagnostics) @@ -56,6 +57,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Runtime Return editor.GetChangedDocument() End Function + Dim codeFixTitle = MicrosoftNetCoreAnalyzersResources.PreferDictionaryContainsValueCodeFixTitle Dim action = CodeAction.Create(codeFixTitle, ReplaceWithContainsValue, codeFixTitle) context.RegisterCodeFix(action, context.Diagnostics) diff --git a/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicPreferStreamAsyncMemoryOverloads.Fixer.vb b/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicPreferStreamAsyncMemoryOverloads.Fixer.vb index 151c10ad84..079a8c076e 100644 --- a/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicPreferStreamAsyncMemoryOverloads.Fixer.vb +++ b/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicPreferStreamAsyncMemoryOverloads.Fixer.vb @@ -35,6 +35,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Runtime End If End If End If + Return Nothing End Function @@ -53,6 +54,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Runtime Next End If Next + Return False End Function @@ -62,6 +64,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Runtime If arg1 Is Nothing Then Return False End If + Dim firstArgumentIdentifierName = TryCast(arg1.GetExpression(), IdentifierNameSyntax) If firstArgumentIdentifierName Is Nothing Then Return False @@ -71,6 +74,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Runtime If arg2 Is Nothing Then Return False End If + Dim literal = TryCast(arg2.GetExpression(), LiteralExpressionSyntax) If literal Is Nothing Then Return False @@ -89,6 +93,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Runtime If arg3 Is Nothing Then Return False End If + Dim thirdArgumentMemberAccessExpression = TryCast(arg3.GetExpression(), MemberAccessExpressionSyntax) If thirdArgumentMemberAccessExpression Is Nothing Then Return False @@ -100,6 +105,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Runtime String.Equals(thirdArgumentMemberAccessExpression.Name.Identifier.Text, WellKnownMemberNames.LengthPropertyName, StringComparison.OrdinalIgnoreCase) Then Return True End If + Return False End Function @@ -115,8 +121,10 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Runtime If argument IsNot Nothing Then actualNode = argument.GetExpression() End If + Return generator.Argument(newName, RefKind.None, actualNode) End If + Return node End Function @@ -126,6 +134,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Runtime If argument IsNot Nothing Then actualNode = argument.GetExpression() End If + Return generator.MemberAccessExpression(actualNode.WithoutTrivia(), memberName) End Function End Class diff --git a/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicSpecifyCultureForToLowerAndToUpper.Fixer.vb b/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicSpecifyCultureForToLowerAndToUpper.Fixer.vb index 36954182a8..5eb8161fce 100644 --- a/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicSpecifyCultureForToLowerAndToUpper.Fixer.vb +++ b/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicSpecifyCultureForToLowerAndToUpper.Fixer.vb @@ -64,6 +64,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Runtime Dim newRoot = root.ReplaceNode(memberAccess, newMemberAccess) Return Task.FromResult(document.WithSyntaxRoot(newRoot)) End If + Return Task.FromResult(document) End Function End Class diff --git a/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicTestForEmptyStringsUsingStringLength.Fixer.vb b/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicTestForEmptyStringsUsingStringLength.Fixer.vb index 0ed3a69b91..fbef37e081 100644 --- a/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicTestForEmptyStringsUsingStringLength.Fixer.vb +++ b/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicTestForEmptyStringsUsingStringLength.Fixer.vb @@ -51,6 +51,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Runtime Return memberAccessExpression.Expression End If End If + Return Nothing End Function End Class diff --git a/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicUseOrdinalStringComparison.Fixer.vb b/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicUseOrdinalStringComparison.Fixer.vb index 6e3cb2cfdb..a50f07822c 100644 --- a/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicUseOrdinalStringComparison.Fixer.vb +++ b/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicUseOrdinalStringComparison.Fixer.vb @@ -32,6 +32,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Runtime Dim newRoot = root.ReplaceNode(memberAccess, newMemberAccess) Return Task.FromResult(document.WithSyntaxRoot(newRoot)) End If + Return Task.FromResult(document) End Function @@ -54,6 +55,7 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Runtime Return document.WithSyntaxRoot(newRoot) End If End If + Return document End Function End Class diff --git a/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicUseSpanBasedStringConcat.Fixer.vb b/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicUseSpanBasedStringConcat.Fixer.vb index ceb7d6bf85..b816ec381e 100644 --- a/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicUseSpanBasedStringConcat.Fixer.vb +++ b/src/NetAnalyzers/VisualBasic/Microsoft.NetCore.Analyzers/Runtime/BasicUseSpanBasedStringConcat.Fixer.vb @@ -34,17 +34,20 @@ Namespace Microsoft.NetCore.VisualBasic.Analyzers.Runtime If importsStatement Is Nothing Then Continue For End If + For Each importsClause As ImportsClauseSyntax In importsStatement.ImportsClauses Dim simpleClause = TryCast(importsClause, SimpleImportsClauseSyntax) Dim identifierName = TryCast(simpleClause?.Name, IdentifierNameSyntax) If identifierName Is Nothing Then Continue For End If + If identifierName.Identifier.ValueText = NameOf(System) Then Return True End If Next Next + Return False End Function diff --git a/src/PerformanceSensitiveAnalyzers/CSharp/Analyzers/CallSiteImplicitAllocationAnalyzer.cs b/src/PerformanceSensitiveAnalyzers/CSharp/Analyzers/CallSiteImplicitAllocationAnalyzer.cs index ad1f70558f..3581586b97 100644 --- a/src/PerformanceSensitiveAnalyzers/CSharp/Analyzers/CallSiteImplicitAllocationAnalyzer.cs +++ b/src/PerformanceSensitiveAnalyzers/CSharp/Analyzers/CallSiteImplicitAllocationAnalyzer.cs @@ -72,6 +72,7 @@ protected override void AnalyzeNode(SyntaxNodeAnalysisContext context, in Perfor { reportDiagnostic(node.CreateDiagnostic(ParamsParameterRule)); } + break; } } diff --git a/src/PerformanceSensitiveAnalyzers/CSharp/Analyzers/EnumeratorAllocationAnalyzer.cs b/src/PerformanceSensitiveAnalyzers/CSharp/Analyzers/EnumeratorAllocationAnalyzer.cs index 2365518978..fdf0357641 100644 --- a/src/PerformanceSensitiveAnalyzers/CSharp/Analyzers/EnumeratorAllocationAnalyzer.cs +++ b/src/PerformanceSensitiveAnalyzers/CSharp/Analyzers/EnumeratorAllocationAnalyzer.cs @@ -58,6 +58,7 @@ protected override void AnalyzeNode(SyntaxNodeAnalysisContext context, in Perfor // 1st we try and fallback to using the ConvertedType enumerator = typeInfo.ConvertedType.GetMembers("GetEnumerator"); } + if ((enumerator == null || enumerator.IsEmpty) && typeInfo.Type.Interfaces != null) { // 2nd fallback, now we try and find the IEnumerable Interface explicitly diff --git a/src/PerformanceSensitiveAnalyzers/CSharp/CodeFixes/AvoidAllocationWithArrayEmptyCodeFix.cs b/src/PerformanceSensitiveAnalyzers/CSharp/CodeFixes/AvoidAllocationWithArrayEmptyCodeFix.cs index 70377db71f..63361ab75f 100644 --- a/src/PerformanceSensitiveAnalyzers/CSharp/CodeFixes/AvoidAllocationWithArrayEmptyCodeFix.cs +++ b/src/PerformanceSensitiveAnalyzers/CSharp/CodeFixes/AvoidAllocationWithArrayEmptyCodeFix.cs @@ -76,6 +76,7 @@ private void TryRegisterCodeFix(CodeFixContext context, SyntaxNode node, Diagnos context.RegisterCodeFix(codeAction, diagnostic); } } + break; case ArrayCreationExpressionSyntax arrayCreation: { @@ -87,6 +88,7 @@ private void TryRegisterCodeFix(CodeFixContext context, SyntaxNode node, Diagnos context.RegisterCodeFix(codeAction, diagnostic); } } + break; } } diff --git a/src/PerformanceTests/Utilities/Common/ReferenceAssemblies.cs b/src/PerformanceTests/Utilities/Common/ReferenceAssemblies.cs index 9cd6e5f969..e8b95fc4be 100644 --- a/src/PerformanceTests/Utilities/Common/ReferenceAssemblies.cs +++ b/src/PerformanceTests/Utilities/Common/ReferenceAssemblies.cs @@ -50,6 +50,7 @@ public Task> ResolveAsync(string? language) references.Add(assembly); } } + return Task.FromResult(references.ToImmutable()); } diff --git a/src/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.Impl.cs b/src/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.Impl.cs index 737e67f5be..faf35839cf 100644 --- a/src/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.Impl.cs +++ b/src/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.Impl.cs @@ -793,6 +793,7 @@ private bool IsNamespaceSkipped(ISymbol symbol, CancellationToken cancellationTo { continue; } + (skippedNamespaces ??= PooledHashSet.GetInstance()).AddRange(currentSkippedNamespaces); } diff --git a/src/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.cs b/src/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.cs index 0b4ebc0ff2..d4167ad55d 100644 --- a/src/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.cs +++ b/src/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.cs @@ -46,7 +46,6 @@ public sealed partial class DeclarePublicApiAnalyzer : DiagnosticAnalyzer private const string BailOnMissingPublicApiFilesEditorConfigOptionName = $"{BaseEditorConfigPath}.require_api_files"; private const string NamespaceToIgnoreInTrackingEditorConfigOptionName = $"{BaseEditorConfigPath}.skip_namespaces"; - internal static readonly SymbolDisplayFormat ShortSymbolNameFormat = new( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.OmittedAsContaining, diff --git a/src/Roslyn.Diagnostics.Analyzers/CSharp/CSharpSpecializedEnumerableCreationAnalyzer.cs b/src/Roslyn.Diagnostics.Analyzers/CSharp/CSharpSpecializedEnumerableCreationAnalyzer.cs index e0098fd473..48f08fbe53 100644 --- a/src/Roslyn.Diagnostics.Analyzers/CSharp/CSharpSpecializedEnumerableCreationAnalyzer.cs +++ b/src/Roslyn.Diagnostics.Analyzers/CSharp/CSharpSpecializedEnumerableCreationAnalyzer.cs @@ -23,8 +23,8 @@ protected override void GetCodeBlockStartedAnalyzer(CompilationStartAnalysisCont private sealed class CodeBlockStartedAnalyzer : AbstractCodeBlockStartedAnalyzer { - public CodeBlockStartedAnalyzer(INamedTypeSymbol genericEnumerableSymbol, IMethodSymbol genericEmptyEnumerableSymbol) : - base(genericEnumerableSymbol, genericEmptyEnumerableSymbol) + public CodeBlockStartedAnalyzer(INamedTypeSymbol genericEnumerableSymbol, IMethodSymbol genericEmptyEnumerableSymbol) + : base(genericEnumerableSymbol, genericEmptyEnumerableSymbol) { } @@ -36,8 +36,8 @@ protected override void GetSyntaxAnalyzer(CodeBlockStartAnalysisContext FixCommentsAsync(Document document, LiteralE { return "@\""; } + if (text.StartsWith("\"", StringComparison.OrdinalIgnoreCase)) { return "\""; } + return null; } } @@ -131,9 +133,11 @@ internal static (int Index, string NewLine) FindNewLineOrEndOfFile(int index, st { return (i, "\r\n"); } + return (i, "\r"); } } + return (length, ""); // EOF } @@ -147,11 +151,13 @@ internal static (int FoundIndex, int CommaCount) FindNumberComment(int cursor, i { commaCount++; } + if (current == '/' && comment[index - 1] == '/' && comment[index - 2] == ' ') { // found start of comment return (index + 1, commaCount); } + if (!IsDigitOrComma(current)) { break; @@ -167,10 +173,12 @@ internal static bool IsDigitOrComma(char c) { return true; } + if (c is ' ' or ',') { return true; } + return false; } @@ -180,6 +188,7 @@ internal static int GetStringLengthIgnoringQuote(string text, bool hasPrefix) { return text.Length - 1; } + return text.Length; } @@ -212,6 +221,7 @@ private static string FixComments(string text, string? prefix) { builder.Append(text, cursor, eolOrEofIndex + newLine.Length - cursor); } + cursor = eolOrEofIndex + newLine.Length; } while (cursor < length); diff --git a/src/Tools/GenerateDocumentationAndConfigFiles/JsonWriter.cs b/src/Tools/GenerateDocumentationAndConfigFiles/JsonWriter.cs index 943cd805de..e17f15ef6e 100644 --- a/src/Tools/GenerateDocumentationAndConfigFiles/JsonWriter.cs +++ b/src/Tools/GenerateDocumentationAndConfigFiles/JsonWriter.cs @@ -211,6 +211,7 @@ private static string EscapeString(string value) { count++; } + break; } } diff --git a/src/Tools/GenerateDocumentationAndConfigFiles/Program.cs b/src/Tools/GenerateDocumentationAndConfigFiles/Program.cs index 6654d8d338..81af8b841a 100644 --- a/src/Tools/GenerateDocumentationAndConfigFiles/Program.cs +++ b/src/Tools/GenerateDocumentationAndConfigFiles/Program.cs @@ -637,6 +637,7 @@ await checkHelpLinkAsync(helpLinkUri).ConfigureAwait(false)) { File.WriteAllText(fileWithPath, builder.ToString()); } + return; async Task checkHelpLinkAsync(string helpLink) diff --git a/src/Tools/Metrics/Program.cs b/src/Tools/Metrics/Program.cs index a36e17f427..af26141eaa 100644 --- a/src/Tools/Metrics/Program.cs +++ b/src/Tools/Metrics/Program.cs @@ -229,6 +229,7 @@ async Task writeOutputAsync() { Console.WriteLine($"Writing output to '{outputFile}'..."); } + metricFile = new XmlTextWriter(outputFile, Encoding.UTF8); } else diff --git a/src/Tools/PerfDiff/ETL/EtlDiffer.cs b/src/Tools/PerfDiff/ETL/EtlDiffer.cs index 05765bfb60..861968f9f3 100644 --- a/src/Tools/PerfDiff/ETL/EtlDiffer.cs +++ b/src/Tools/PerfDiff/ETL/EtlDiffer.cs @@ -97,6 +97,7 @@ static float LoadTrace(CallTree callTree, out Dictionary data) total += node.ExclusiveMetric; } + return total; } diff --git a/src/Tools/PerfDiff/PerfDiff.cs b/src/Tools/PerfDiff/PerfDiff.cs index 3e4740417e..7c3ed1cf64 100644 --- a/src/Tools/PerfDiff/PerfDiff.cs +++ b/src/Tools/PerfDiff/PerfDiff.cs @@ -91,6 +91,7 @@ private static bool TryGetETLPaths(string path, [NotNullWhen(true)] out string? etlPath = null; return false; } + return true; } else if (File.Exists(path) || !path.EndsWith(ETLFileExtension, StringComparison.OrdinalIgnoreCase)) diff --git a/src/Utilities.UnitTests/Extensions/ImmutableArrayExensionsTests.cs b/src/Utilities.UnitTests/Extensions/ImmutableArrayExensionsTests.cs index 32fb32bced..e77a7d1160 100644 --- a/src/Utilities.UnitTests/Extensions/ImmutableArrayExensionsTests.cs +++ b/src/Utilities.UnitTests/Extensions/ImmutableArrayExensionsTests.cs @@ -46,6 +46,7 @@ private static ImmutableArray CreateImmutableArray(int count) builder.AddRange(Enumerable.Range(0, count)); return builder.ToImmutable(); } + return ImmutableArray.Empty; } } diff --git a/src/Utilities.UnitTests/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisTests.cs b/src/Utilities.UnitTests/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisTests.cs index 9295b00edd..b719f7e38c 100644 --- a/src/Utilities.UnitTests/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisTests.cs +++ b/src/Utilities.UnitTests/FlowAnalysis/Analysis/PropertySetAnalysis/PropertySetAnalysisTests.cs @@ -142,6 +142,7 @@ private void VerifyCSharp( TestOutput.WriteLine( $"Line {lineNumber}, Column {columnNumber}, {MethodSymbolOrReturnString(kvp.Key.Method)}: {kvp.Value}"); } + TestOutput.WriteLine("============================"); throw; @@ -1349,6 +1350,7 @@ protected static (IOperation operation, SemanticModel model, SyntaxNode node) Ge { Assert.Same(model, operation.SemanticModel); } + return (operation, model, syntaxNode); } diff --git a/src/Utilities.UnitTests/Options/SymbolNamesWithValueOptionTests.cs b/src/Utilities.UnitTests/Options/SymbolNamesWithValueOptionTests.cs index fa481c08e4..1b3e19e92d 100644 --- a/src/Utilities.UnitTests/Options/SymbolNamesWithValueOptionTests.cs +++ b/src/Utilities.UnitTests/Options/SymbolNamesWithValueOptionTests.cs @@ -37,6 +37,7 @@ SymbolNamesWithValueOption.NameParts func(string symbolName) { callCount++; } + return new SymbolNamesWithValueOption.NameParts(symbolName, Unit.Default); } @@ -381,6 +382,7 @@ static ISymbol FindSymbol(Compilation compilation, string symbolName) { return currentType; } + currentType = currentType.ContainingType; } @@ -391,6 +393,7 @@ static ISymbol FindSymbol(Compilation compilation, string symbolName) { return currentNamespace; } + currentNamespace = currentNamespace.ContainingNamespace; } diff --git a/src/Utilities/Compiler/CodeMetrics/CodeAnalysisMetricData.MethodMetricData.cs b/src/Utilities/Compiler/CodeMetrics/CodeAnalysisMetricData.MethodMetricData.cs index 4f90fa9fd7..b89947a694 100644 --- a/src/Utilities/Compiler/CodeMetrics/CodeAnalysisMetricData.MethodMetricData.cs +++ b/src/Utilities/Compiler/CodeMetrics/CodeAnalysisMetricData.MethodMetricData.cs @@ -40,6 +40,7 @@ internal static async Task ComputeAsync(IMethodSymbol method, { MetricsHelper.AddCoupledNamedTypes(coupledTypesBuilder, wellKnownTypeProvider, method.ReturnType); } + int? depthOfInheritance = null; int maintainabilityIndex = CalculateMaintainabilityIndex(computationalComplexityMetrics, cyclomaticComplexity); MetricsHelper.RemoveContainingTypes(method, coupledTypesBuilder); diff --git a/src/Utilities/Compiler/CodeMetrics/CodeAnalysisMetricData.NamedTypeMetricData.cs b/src/Utilities/Compiler/CodeMetrics/CodeAnalysisMetricData.NamedTypeMetricData.cs index 165c1c5345..1626d41a12 100644 --- a/src/Utilities/Compiler/CodeMetrics/CodeAnalysisMetricData.NamedTypeMetricData.cs +++ b/src/Utilities/Compiler/CodeMetrics/CodeAnalysisMetricData.NamedTypeMetricData.cs @@ -121,6 +121,7 @@ private static int CalculateDepthOfInheritance(INamedTypeSymbol namedType, Func< depth++; parent = parent.BaseType; } + return depth; case TypeKind.Struct: diff --git a/src/Utilities/Compiler/CodeMetrics/ComputationalComplexityMetrics.cs b/src/Utilities/Compiler/CodeMetrics/ComputationalComplexityMetrics.cs index b222d6e891..83a45063e8 100644 --- a/src/Utilities/Compiler/CodeMetrics/ComputationalComplexityMetrics.cs +++ b/src/Utilities/Compiler/CodeMetrics/ComputationalComplexityMetrics.cs @@ -155,6 +155,7 @@ public static ComputationalComplexityMetrics Compute(IOperation operationBlock) countOperator(operation); countOperand(field); } + continue; case OperationKind.PropertyInitializer: foreach (var property in ((IPropertyInitializerOperation)operation).InitializedProperties) @@ -162,6 +163,7 @@ public static ComputationalComplexityMetrics Compute(IOperation operationBlock) countOperator(operation); countOperand(property); } + continue; case OperationKind.ParameterInitializer: countOperator(operation); @@ -177,6 +179,7 @@ public static ComputationalComplexityMetrics Compute(IOperation operationBlock) { countOperand(variableDeclarator.Symbol); } + continue; // Invocations and Object creations. @@ -187,6 +190,7 @@ public static ComputationalComplexityMetrics Compute(IOperation operationBlock) { countOperand(invocation.TargetMethod); } + continue; case OperationKind.ObjectCreation: countOperator(operation); @@ -225,6 +229,7 @@ public static ComputationalComplexityMetrics Compute(IOperation operationBlock) { countOperator(operation); } + continue; // Other common operators. @@ -271,6 +276,7 @@ public static ComputationalComplexityMetrics Compute(IOperation operationBlock) { countOperator(operation); } + continue; } } @@ -392,10 +398,12 @@ public long DistinctOperators //n1 { count += _distinctBinaryOperatorKinds.Count - 1; } + if (_distinctUnaryOperatorKinds.Count > 1) { count += _distinctUnaryOperatorKinds.Count - 1; } + if (_distinctCaseKinds.Count > 1) { count += _distinctCaseKinds.Count - 1; diff --git a/src/Utilities/Compiler/Extensions/IEnumerableExtensions.cs b/src/Utilities/Compiler/Extensions/IEnumerableExtensions.cs index 90897463dd..8d380602ab 100644 --- a/src/Utilities/Compiler/Extensions/IEnumerableExtensions.cs +++ b/src/Utilities/Compiler/Extensions/IEnumerableExtensions.cs @@ -200,7 +200,10 @@ public static bool HasFewerThan(this IEnumerable source, int c } using var enumerator = source.GetEnumerator(); - while (count > 0 && enumerator.MoveNext()) { count--; } + while (count > 0 && enumerator.MoveNext()) + { + count--; + } return count > 0; } diff --git a/src/Utilities/Compiler/Extensions/IOperationExtensions.cs b/src/Utilities/Compiler/Extensions/IOperationExtensions.cs index a41577ab41..00ac079297 100644 --- a/src/Utilities/Compiler/Extensions/IOperationExtensions.cs +++ b/src/Utilities/Compiler/Extensions/IOperationExtensions.cs @@ -262,6 +262,7 @@ public static bool IsOperationNoneRoot(this IOperation operation) { return GetAncestor(ancestor, ancestorKind, predicate); } + return (TOperation)ancestor; } else @@ -295,6 +296,7 @@ public static bool IsOperationNoneRoot(this IOperation operation) { return GetAncestor(ancestor, ancestorKinds, predicate); } + return ancestor; } else @@ -420,6 +422,7 @@ public static bool IsAdditionOrSubstractionOperation(this IBinaryOperation binar case BinaryOperatorKind.Subtract: binaryOperator = '-'; return true; } + return false; } @@ -814,6 +817,7 @@ public static bool HasAnyExplicitDescendant(this IOperation operation, Func GetDefaultValue() var analyzerConfigOptions = options.GetOrComputeCategorizedAnalyzerConfigOptions(compilation); return analyzerConfigOptions.GetOptionValue(optionName, tree, rule: null, - tryParseValue: (string value, out string? result) => { result = value; return true; }, + tryParseValue: (string value, out string? result) => + { + result = value; + return true; + }, defaultValue: null, OptionKind.BuildProperty); } @@ -532,7 +536,11 @@ public static ImmutableArray GetMSBuildItemMetadataValues( var propertyOptionName = MSBuildItemOptionNamesHelpers.GetPropertyNameForItemOptionName(itemOptionName); var analyzerConfigOptions = options.GetOrComputeCategorizedAnalyzerConfigOptions(compilation); var propertyValue = analyzerConfigOptions.GetOptionValue(propertyOptionName, tree, rule: null, - tryParseValue: (string value, out string? result) => { result = value; return true; }, + tryParseValue: (string value, out string? result) => + { + result = value; + return true; + }, defaultValue: null, OptionKind.BuildProperty); return MSBuildItemOptionNamesHelpers.ParseItemOptionValue(propertyValue); } diff --git a/src/Utilities/Compiler/Options/SymbolNamesWithValueOption.cs b/src/Utilities/Compiler/Options/SymbolNamesWithValueOption.cs index e3422bacc2..59bd3921d7 100644 --- a/src/Utilities/Compiler/Options/SymbolNamesWithValueOption.cs +++ b/src/Utilities/Compiler/Options/SymbolNamesWithValueOption.cs @@ -140,6 +140,7 @@ static void ProcessWildcardName(NameParts parts, PooledDictionary.GetInstance()); } + wildcardNamesBuilder[AllKinds].Add(parts.SymbolName[0..^1], parts.AssociatedValue); return; } @@ -161,6 +162,7 @@ static void ProcessWildcardName(NameParts parts, PooledDictionary.GetInstance()); } + wildcardNamesBuilder[symbolKind.Value].Add(parts.SymbolName[2..^1], parts.AssociatedValue); } } diff --git a/src/Utilities/Compiler/SmallDictionary.cs b/src/Utilities/Compiler/SmallDictionary.cs index dd66bcd4f8..578cda7485 100644 --- a/src/Utilities/Compiler/SmallDictionary.cs +++ b/src/Utilities/Compiler/SmallDictionary.cs @@ -167,7 +167,8 @@ private static AvlNode MinValueNode(AvlNode node) private static int Height(AvlNode? node) { - if (node == null) return 0; + if (node == null) + return 0; int a = Height(node.Left); int b = Height(node.Right); @@ -290,7 +291,8 @@ public AvlNode(int hashCode, K key, V value) public static int AssertBalanced(AvlNode? V) #pragma warning restore CA1000 // Do not declare static members on generic types { - if (V == null) return 0; + if (V == null) + return 0; int a = AssertBalanced(V.Left); int b = AssertBalanced(V.Right); diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysis.DisposeDataFlowOperationVisitor.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysis.DisposeDataFlowOperationVisitor.cs index dca93888c8..3eef871f79 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysis.DisposeDataFlowOperationVisitor.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysis.DisposeDataFlowOperationVisitor.cs @@ -274,6 +274,7 @@ public override DisposeAbstractValue VisitInvocation_NonLambdaOrDelegateOrLocalF { goto case DisposeMethodKind.Dispose; } + break; default: diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAbstractValue.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAbstractValue.cs index f724ace59f..d0a90b0bcd 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAbstractValue.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAbstractValue.cs @@ -86,6 +86,7 @@ internal static PointsToAbstractValue Create(ImmutableHashSet { return NullLocation; } + if (location.IsNoLocation) { return NoLocation; diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysis.CorePointsToAnalysisDataDomain.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysis.CorePointsToAnalysisDataDomain.cs index 32fd10b18c..4b983a527d 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysis.CorePointsToAnalysisDataDomain.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/PointsToAnalysis/PointsToAnalysis.CorePointsToAnalysisDataDomain.cs @@ -78,6 +78,7 @@ public CorePointsToAnalysisData MergeCoreAnalysisDataForBackEdge( stopTrackingAnalysisDataForKeyAndChildren(); } } + break; } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntityFactory.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntityFactory.cs index 0d19d84c4f..ee77af7b3d 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntityFactory.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/AnalysisEntityFactory.cs @@ -163,6 +163,7 @@ public bool TryCreate(IOperation operation, [NotNullWhen(returnValue: true)] out { GetSymbolAndIndicesForMemberReference(memberReferenceParent, ref symbol, ref indices); } + break; case IInstanceReferenceOperation instanceReference: @@ -182,6 +183,7 @@ public bool TryCreate(IOperation operation, [NotNullWhen(returnValue: true)] out analysisEntity = AnalysisEntity.Create(instanceReference, instanceLocation); } } + break; case IConversionOperation conversion: @@ -277,6 +279,7 @@ private static void GetSymbolAndIndicesForMemberReference(IMemberReferenceOperat symbol = fieldReference.Field.ContainingType.GetUnderlyingValueTupleTypeOrThis().GetMembers(name).OfType().FirstOrDefault() ?? symbol; } + break; case IEventReferenceOperation eventReference: @@ -297,6 +300,7 @@ private static void GetSymbolAndIndicesForMemberReference(IMemberReferenceOperat CreateAbstractIndices(propertyReference.Arguments.Select(a => a.Value).ToImmutableArray()) : ImmutableArray.Empty; } + break; } } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowAnalysis.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowAnalysis.cs index 6faddd8f48..135297027e 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowAnalysis.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowAnalysis.cs @@ -593,6 +593,7 @@ bool HasUnprocessedPredecessorBlock(BasicBlock block) { return block.EnclosingRegion.EnclosingRegion; } + break; case ControlFlowRegionKind.Filter: @@ -601,6 +602,7 @@ bool HasUnprocessedPredecessorBlock(BasicBlock block) { return block.EnclosingRegion.EnclosingRegion.EnclosingRegion; } + break; } } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowOperationVisitor.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowOperationVisitor.cs index a4e7bc7e14..15d9298520 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowOperationVisitor.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Framework/DataFlow/DataFlowOperationVisitor.cs @@ -456,6 +456,7 @@ public TAnalysisData OnStartBlockAnalysis(BasicBlock block, TAnalysisData input) { MergeAnalysisDataFromUnhandledThrowOperations(caughtExceptionType: null); } + break; } @@ -1595,6 +1596,7 @@ private void PerformPredicateAnalysisCore(IOperation operation, TAnalysisData ta predicateValueKind = SetValueForEqualsOrNotEqualsComparisonOperator(isPatternOperation.Value, negatedConstantPattern.Value, equals: FlowBranchConditionKind == ControlFlowConditionKind.WhenFalse, isReferenceEquality: false, targetAnalysisData: targetAnalysisData); } + break; } else @@ -1608,6 +1610,7 @@ private void PerformPredicateAnalysisCore(IOperation operation, TAnalysisData ta { predicateValueKind = SetValueForIsNullComparisonOperator(isPatternOperation.Value, equals: false, targetAnalysisData: targetAnalysisData); } + break; case "BinaryPattern": @@ -3530,6 +3533,7 @@ public override TAbstractAnalysisValue VisitDelegateCreation(IDelegateCreationOp { _escapedLocalFunctions.Add(methodReference.Method); } + break; } } @@ -3644,6 +3648,7 @@ public override TAbstractAnalysisValue VisitIsNull(IIsNullOperation operation, o { PerformPredicateAnalysis(operation); } + return value; } diff --git a/src/Utilities/Refactoring/AbstractRefactoringHelpers`3.cs b/src/Utilities/Refactoring/AbstractRefactoringHelpers`3.cs index 3ba0ea9af8..a84f097264 100644 --- a/src/Utilities/Refactoring/AbstractRefactoringHelpers`3.cs +++ b/src/Utilities/Refactoring/AbstractRefactoringHelpers`3.cs @@ -508,6 +508,7 @@ protected virtual async Task AddNodesDeepInAsync( return; } } + ancestor = ancestor.Parent; } }