diff --git a/Directory.Build.props b/Directory.Build.props
index c1635c1e19..df5301e19e 100644
--- a/Directory.Build.props
+++ b/Directory.Build.props
@@ -11,6 +11,9 @@
8
16
+
+
+ enable
diff --git a/src/MetaCompilation.Analyzers/Core/CodeFixProvider.cs b/src/MetaCompilation.Analyzers/Core/CodeFixProvider.cs
index 6a676486ec..0d79102262 100644
--- a/src/MetaCompilation.Analyzers/Core/CodeFixProvider.cs
+++ b/src/MetaCompilation.Analyzers/Core/CodeFixProvider.cs
@@ -1,5 +1,7 @@
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+#nullable disable
+
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
diff --git a/src/MetaCompilation.Analyzers/Core/DiagnosticAnalyzer.cs b/src/MetaCompilation.Analyzers/Core/DiagnosticAnalyzer.cs
index 7c7977b168..924567a909 100644
--- a/src/MetaCompilation.Analyzers/Core/DiagnosticAnalyzer.cs
+++ b/src/MetaCompilation.Analyzers/Core/DiagnosticAnalyzer.cs
@@ -1,5 +1,7 @@
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+#nullable disable
+
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
diff --git a/src/Microsoft.CodeAnalysis.Analyzers/CSharp/CSharpImmutableObjectMethodAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/CSharp/CSharpImmutableObjectMethodAnalyzer.cs
index 1e020a0e51..405ca36ca0 100644
--- a/src/Microsoft.CodeAnalysis.Analyzers/CSharp/CSharpImmutableObjectMethodAnalyzer.cs
+++ b/src/Microsoft.CodeAnalysis.Analyzers/CSharp/CSharpImmutableObjectMethodAnalyzer.cs
@@ -50,19 +50,17 @@ public override void Initialize(AnalysisContext context)
context.RegisterCompilationStartAction(compilationContext =>
{
- INamedTypeSymbol solutionSymbol = compilationContext.Compilation.GetOrCreateTypeByMetadataName(SolutionFullName);
- INamedTypeSymbol projectSymbol = compilationContext.Compilation.GetOrCreateTypeByMetadataName(ProjectFullName);
- INamedTypeSymbol documentSymbol = compilationContext.Compilation.GetOrCreateTypeByMetadataName(DocumentFullName);
- INamedTypeSymbol syntaxNodeSymbol = compilationContext.Compilation.GetOrCreateTypeByMetadataName(SyntaxNodeFullName);
- INamedTypeSymbol compilationSymbol = compilationContext.Compilation.GetOrCreateTypeByMetadataName(CompilationFullName);
-
- ImmutableArray immutableSymbols = ImmutableArray.Create(solutionSymbol, projectSymbol, documentSymbol, syntaxNodeSymbol, compilationSymbol);
- //Only register our node action if we can find the symbols for our immutable types
- if (immutableSymbols.Any(n => n == null))
+ if (!compilationContext.Compilation.TryGetOrCreateTypeByMetadataName(SolutionFullName, out var solutionSymbol) ||
+ !compilationContext.Compilation.TryGetOrCreateTypeByMetadataName(ProjectFullName, out var projectSymbol) ||
+ !compilationContext.Compilation.TryGetOrCreateTypeByMetadataName(DocumentFullName, out var documentSymbol) ||
+ !compilationContext.Compilation.TryGetOrCreateTypeByMetadataName(SyntaxNodeFullName, out var syntaxNodeSymbol) ||
+ !compilationContext.Compilation.TryGetOrCreateTypeByMetadataName(CompilationFullName, out var compilationSymbol))
{
+ // Only register our node action if we can find the symbols for our immutable types
return;
}
+ var immutableSymbols = ImmutableArray.Create(solutionSymbol, projectSymbol, documentSymbol, syntaxNodeSymbol, compilationSymbol);
compilationContext.RegisterSyntaxNodeAction(sc => AnalyzeInvocationForIgnoredReturnValue(sc, immutableSymbols), SyntaxKind.InvocationExpression);
});
}
diff --git a/src/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpRegisterActionAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpRegisterActionAnalyzer.cs
index 61f823d81b..7b346fc945 100644
--- a/src/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpRegisterActionAnalyzer.cs
+++ b/src/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpRegisterActionAnalyzer.cs
@@ -23,19 +23,19 @@ public class CSharpRegisterActionAnalyzer : RegisterActionAnalyzer SyntaxKind.Argument;
protected override SyntaxKind ParameterSyntaxKind => SyntaxKind.Parameter;
- protected override IEnumerable GetArgumentExpressions(InvocationExpressionSyntax invocation)
+ protected override IEnumerable? GetArgumentExpressions(InvocationExpressionSyntax invocation)
{
if (invocation.ArgumentList != null)
{
@@ -71,7 +71,7 @@ protected override SyntaxNode GetInvocationExpression(InvocationExpressionSyntax
return invocation.Expression;
}
- protected override SyntaxNode GetInvocationReceiver(InvocationExpressionSyntax invocation)
+ protected override SyntaxNode? GetInvocationReceiver(InvocationExpressionSyntax invocation)
{
return (invocation.Expression as MemberAccessExpressionSyntax)?.Expression;
}
diff --git a/src/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpReportDiagnosticAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpReportDiagnosticAnalyzer.cs
index 44e4a40d83..2388580df4 100644
--- a/src/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpReportDiagnosticAnalyzer.cs
+++ b/src/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpReportDiagnosticAnalyzer.cs
@@ -24,7 +24,7 @@ public CSharpReportDiagnosticCompilationAnalyzer(ImmutableHashSet GetArgumentExpressions(InvocationExpressionSyntax invocation)
+ protected override IEnumerable? GetArgumentExpressions(InvocationExpressionSyntax invocation)
{
if (invocation.ArgumentList != null)
{
diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/FixAnalyzers/FixerWithFixAllAnalyzer.Fixer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/FixAnalyzers/FixerWithFixAllAnalyzer.Fixer.cs
index 65674a5165..0446b049c3 100644
--- a/src/Microsoft.CodeAnalysis.Analyzers/Core/FixAnalyzers/FixerWithFixAllAnalyzer.Fixer.cs
+++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/FixAnalyzers/FixerWithFixAllAnalyzer.Fixer.cs
@@ -55,8 +55,13 @@ private static async Task AddMethodAsync(Document document, SyntaxNode
var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var typeIsSealed = ((INamedTypeSymbol)model.GetDeclaredSymbol(classDecl)).IsSealed;
- INamedTypeSymbol codeFixProviderSymbol = model.Compilation.GetOrCreateTypeByMetadataName(FixerWithFixAllAnalyzer.CodeFixProviderMetadataName);
- IMethodSymbol getFixAllProviderMethod = codeFixProviderSymbol.GetMembers(FixerWithFixAllAnalyzer.GetFixAllProviderMethodName).OfType().First();
+ INamedTypeSymbol? codeFixProviderSymbol = model.Compilation.GetOrCreateTypeByMetadataName(FixerWithFixAllAnalyzer.CodeFixProviderMetadataName);
+ IMethodSymbol? getFixAllProviderMethod = codeFixProviderSymbol?.GetMembers(FixerWithFixAllAnalyzer.GetFixAllProviderMethodName).OfType().FirstOrDefault();
+ if (getFixAllProviderMethod == null)
+ {
+ return document;
+ }
+
var returnStatement = generator.ReturnStatement(generator.MemberAccessExpression(
generator.IdentifierName("WellKnownFixAllProviders"), "BatchFixer"));
var statements = new SyntaxNode[] { returnStatement };
diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/FixAnalyzers/FixerWithFixAllAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/FixAnalyzers/FixerWithFixAllAnalyzer.cs
index 7f2bdea96b..bd7d7d2826 100644
--- a/src/Microsoft.CodeAnalysis.Analyzers/Core/FixAnalyzers/FixerWithFixAllAnalyzer.cs
+++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/FixAnalyzers/FixerWithFixAllAnalyzer.cs
@@ -86,37 +86,33 @@ private void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext con
{
context.CancellationToken.ThrowIfCancellationRequested();
- INamedTypeSymbol codeFixProviderSymbol = context.Compilation.GetOrCreateTypeByMetadataName(CodeFixProviderMetadataName);
+ INamedTypeSymbol? codeFixProviderSymbol = context.Compilation.GetOrCreateTypeByMetadataName(CodeFixProviderMetadataName);
if (codeFixProviderSymbol == null)
{
return;
}
- IMethodSymbol getFixAllProviderMethod = codeFixProviderSymbol.GetMembers(GetFixAllProviderMethodName).OfType().FirstOrDefault();
+ IMethodSymbol? getFixAllProviderMethod = codeFixProviderSymbol.GetMembers(GetFixAllProviderMethodName).OfType().FirstOrDefault();
if (getFixAllProviderMethod == null)
{
return;
}
- INamedTypeSymbol codeActionSymbol = context.Compilation.GetOrCreateTypeByMetadataName(CodeActionMetadataName);
+ INamedTypeSymbol? codeActionSymbol = context.Compilation.GetOrCreateTypeByMetadataName(CodeActionMetadataName);
if (codeActionSymbol == null)
{
return;
}
- IEnumerable createSymbols = codeActionSymbol.GetMembers(CreateMethodName).OfType();
- if (createSymbols == null)
- {
- return;
- }
-
- IPropertySymbol equivalenceKeyProperty = codeActionSymbol.GetMembers(EquivalenceKeyPropertyName).OfType().FirstOrDefault();
+ IPropertySymbol? equivalenceKeyProperty = codeActionSymbol.GetMembers(EquivalenceKeyPropertyName).OfType().FirstOrDefault();
if (equivalenceKeyProperty == null)
{
return;
}
- CompilationAnalyzer compilationAnalyzer = new CompilationAnalyzer(codeFixProviderSymbol, codeActionSymbol, context.Compilation.Assembly, createMethods: ImmutableHashSet.CreateRange(createSymbols));
+ var createMethods = codeActionSymbol.GetMembers(CreateMethodName).OfType().ToImmutableHashSet();
+
+ CompilationAnalyzer compilationAnalyzer = new CompilationAnalyzer(codeFixProviderSymbol, codeActionSymbol, context.Compilation.Assembly, createMethods);
context.RegisterSymbolAction(compilationAnalyzer.AnalyzeNamedTypeSymbol, SymbolKind.NamedType);
context.RegisterOperationBlockStartAction(compilationAnalyzer.OperationBlockStart);
diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ConfigureGeneratedCodeAnalysisAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ConfigureGeneratedCodeAnalysisAnalyzer.cs
index 50ac08ba23..73f0daa5f4 100644
--- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ConfigureGeneratedCodeAnalysisAnalyzer.cs
+++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ConfigureGeneratedCodeAnalysisAnalyzer.cs
@@ -39,7 +39,7 @@ public override void Initialize(AnalysisContext context)
}
[SuppressMessage("AnalyzerPerformance", "RS1012:Start action has no registered actions.", Justification = "Method returns an analyzer that is registered by the caller.")]
- protected override DiagnosticAnalyzerSymbolAnalyzer GetDiagnosticAnalyzerSymbolAnalyzer(CompilationStartAnalysisContext compilationContext, INamedTypeSymbol diagnosticAnalyzer, INamedTypeSymbol diagnosticAnalyzerAttribute)
+ protected override DiagnosticAnalyzerSymbolAnalyzer? GetDiagnosticAnalyzerSymbolAnalyzer(CompilationStartAnalysisContext compilationContext, INamedTypeSymbol diagnosticAnalyzer, INamedTypeSymbol diagnosticAnalyzerAttribute)
{
var compilation = compilationContext.Compilation;
@@ -62,7 +62,7 @@ protected override DiagnosticAnalyzerSymbolAnalyzer GetDiagnosticAnalyzerSymbolA
return;
}
- IParameterSymbol analysisContextParameter = null;
+ IParameterSymbol? analysisContextParameter = null;
foreach (var parameter in method.Parameters)
{
if (!Equals(parameter.Type, analysisContext))
diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAPIUsageAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAPIUsageAnalyzer.cs
index d3866f9b0c..44bb6f3e8c 100644
--- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAPIUsageAnalyzer.cs
+++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAPIUsageAnalyzer.cs
@@ -63,7 +63,7 @@ public override void Initialize(AnalysisContext context)
return;
}
- INamedTypeSymbol diagnosticAnalyzer = compilationStartContext.Compilation.GetOrCreateTypeByMetadataName(DiagnosticAnalyzerCorrectnessAnalyzer.DiagnosticAnalyzerTypeFullName);
+ INamedTypeSymbol? diagnosticAnalyzer = compilationStartContext.Compilation.GetOrCreateTypeByMetadataName(DiagnosticAnalyzerCorrectnessAnalyzer.DiagnosticAnalyzerTypeFullName);
if (diagnosticAnalyzer == null)
{
// Does not contain any diagnostic analyzers.
diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAttributeAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAttributeAnalyzer.cs
index 8c68ea2d08..a1dca8ba55 100644
--- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAttributeAnalyzer.cs
+++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAttributeAnalyzer.cs
@@ -1,7 +1,6 @@
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
-using System.Diagnostics;
using Microsoft.CodeAnalysis.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Analyzer.Utilities;
@@ -63,9 +62,9 @@ private sealed class AttributeAnalyzer : DiagnosticAnalyzerSymbolAnalyzer
private const string CSharpCompilationFullName = @"Microsoft.CodeAnalysis.CSharp.CSharpCompilation";
private const string BasicCompilationFullName = @"Microsoft.CodeAnalysis.VisualBasic.VisualBasicCompilation";
- private readonly INamedTypeSymbol _attributeUsageAttribute;
+ private readonly INamedTypeSymbol? _attributeUsageAttribute;
- public AttributeAnalyzer(INamedTypeSymbol diagnosticAnalyzer, INamedTypeSymbol diagnosticAnalyzerAttribute, INamedTypeSymbol attributeUsageAttribute)
+ public AttributeAnalyzer(INamedTypeSymbol diagnosticAnalyzer, INamedTypeSymbol diagnosticAnalyzerAttribute, INamedTypeSymbol? attributeUsageAttribute)
: base(diagnosticAnalyzer, diagnosticAnalyzerAttribute)
{
_attributeUsageAttribute = attributeUsageAttribute;
@@ -83,7 +82,7 @@ protected override void AnalyzeDiagnosticAnalyzer(SymbolAnalysisContext symbolCo
// 2) AddLanguageSupportToAnalyzerRule: For analyzer supporting only one of C# or VB languages, detect if it can support the other language.
var hasAttribute = false;
- SyntaxNode attributeSyntax = null;
+ SyntaxNode? attributeSyntax = null;
bool supportsCSharp = false;
bool supportsVB = false;
@@ -127,13 +126,13 @@ protected override void AnalyzeDiagnosticAnalyzer(SymbolAnalysisContext symbolCo
}
else if (supportsCSharp ^ supportsVB)
{
- Debug.Assert(attributeSyntax != null);
+ RoslynDebug.Assert(attributeSyntax != null);
// If the analyzer assembly doesn't reference either C# or VB CodeAnalysis assemblies,
// then the analyzer is pretty likely a language-agnostic analyzer.
Compilation compilation = symbolContext.Compilation;
string compilationTypeNameToCheck = supportsCSharp ? CSharpCompilationFullName : BasicCompilationFullName;
- INamedTypeSymbol compilationType = compilation.GetOrCreateTypeByMetadataName(compilationTypeNameToCheck);
+ INamedTypeSymbol? compilationType = compilation.GetOrCreateTypeByMetadataName(compilationTypeNameToCheck);
if (compilationType == null)
{
string missingLanguage = supportsCSharp ? LanguageNames.VisualBasic : LanguageNames.CSharp;
diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerCorrectnessAnalyzer.DiagnosticAnalyzerSymbolAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerCorrectnessAnalyzer.DiagnosticAnalyzerSymbolAnalyzer.cs
index ae80da31a8..69b2f0a64a 100644
--- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerCorrectnessAnalyzer.DiagnosticAnalyzerSymbolAnalyzer.cs
+++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerCorrectnessAnalyzer.DiagnosticAnalyzerSymbolAnalyzer.cs
@@ -35,7 +35,7 @@ internal void AnalyzeSymbol(SymbolAnalysisContext symbolContext)
protected abstract void AnalyzeDiagnosticAnalyzer(SymbolAnalysisContext symbolContext);
- protected bool HasDiagnosticAnalyzerAttribute(INamedTypeSymbol namedType, INamedTypeSymbol attributeUsageAttribute)
+ protected bool HasDiagnosticAnalyzerAttribute(INamedTypeSymbol namedType, INamedTypeSymbol? attributeUsageAttribute)
{
foreach (AttributeData attribute in namedType.GetApplicableAttributes(attributeUsageAttribute))
{
diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerCorrectnessAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerCorrectnessAnalyzer.cs
index 7a7fd2f534..2308826e0d 100644
--- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerCorrectnessAnalyzer.cs
+++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerCorrectnessAnalyzer.cs
@@ -54,8 +54,8 @@ public override void Initialize(AnalysisContext context)
context.RegisterCompilationStartAction(compilationContext =>
{
- INamedTypeSymbol diagnosticAnalyzer = compilationContext.Compilation.GetOrCreateTypeByMetadataName(DiagnosticAnalyzerTypeFullName);
- INamedTypeSymbol diagnosticAnalyzerAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(DiagnosticAnalyzerAttributeFullName);
+ INamedTypeSymbol? diagnosticAnalyzer = compilationContext.Compilation.GetOrCreateTypeByMetadataName(DiagnosticAnalyzerTypeFullName);
+ INamedTypeSymbol? diagnosticAnalyzerAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(DiagnosticAnalyzerAttributeFullName);
if (diagnosticAnalyzer == null || diagnosticAnalyzerAttribute == null)
{
@@ -63,7 +63,7 @@ public override void Initialize(AnalysisContext context)
return;
}
- DiagnosticAnalyzerSymbolAnalyzer analyzer = GetDiagnosticAnalyzerSymbolAnalyzer(compilationContext, diagnosticAnalyzer, diagnosticAnalyzerAttribute);
+ DiagnosticAnalyzerSymbolAnalyzer? analyzer = GetDiagnosticAnalyzerSymbolAnalyzer(compilationContext, diagnosticAnalyzer, diagnosticAnalyzerAttribute);
if (analyzer != null)
{
compilationContext.RegisterSymbolAction(c => analyzer.AnalyzeSymbol(c), SymbolKind.NamedType);
@@ -71,6 +71,6 @@ public override void Initialize(AnalysisContext context)
});
}
- protected abstract DiagnosticAnalyzerSymbolAnalyzer GetDiagnosticAnalyzerSymbolAnalyzer(CompilationStartAnalysisContext compilationContext, INamedTypeSymbol diagnosticAnalyzer, INamedTypeSymbol diagnosticAnalyzerAttribute);
+ protected abstract DiagnosticAnalyzerSymbolAnalyzer? GetDiagnosticAnalyzerSymbolAnalyzer(CompilationStartAnalysisContext compilationContext, INamedTypeSymbol diagnosticAnalyzer, INamedTypeSymbol diagnosticAnalyzerAttribute);
}
}
diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerFieldsAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerFieldsAnalyzer.cs
index 9f9b5f9aa3..6d76078beb 100644
--- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerFieldsAnalyzer.cs
+++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerFieldsAnalyzer.cs
@@ -44,23 +44,23 @@ public override void Initialize(AnalysisContext context)
}
[SuppressMessage("AnalyzerPerformance", "RS1012:Start action has no registered actions.", Justification = "Method returns an analyzer that is registered by the caller.")]
- protected override DiagnosticAnalyzerSymbolAnalyzer GetDiagnosticAnalyzerSymbolAnalyzer(CompilationStartAnalysisContext compilationContext, INamedTypeSymbol diagnosticAnalyzer, INamedTypeSymbol diagnosticAnalyzerAttribute)
+ protected override DiagnosticAnalyzerSymbolAnalyzer? GetDiagnosticAnalyzerSymbolAnalyzer(CompilationStartAnalysisContext compilationContext, INamedTypeSymbol diagnosticAnalyzer, INamedTypeSymbol diagnosticAnalyzerAttribute)
{
Compilation compilation = compilationContext.Compilation;
- INamedTypeSymbol compilationType = compilation.GetOrCreateTypeByMetadataName(s_compilationTypeFullName);
+ INamedTypeSymbol? compilationType = compilation.GetOrCreateTypeByMetadataName(s_compilationTypeFullName);
if (compilationType == null)
{
return null;
}
- INamedTypeSymbol symbolType = compilation.GetOrCreateTypeByMetadataName(s_symbolTypeFullName);
+ INamedTypeSymbol? symbolType = compilation.GetOrCreateTypeByMetadataName(s_symbolTypeFullName);
if (symbolType == null)
{
return null;
}
- INamedTypeSymbol operationType = compilation.GetOrCreateTypeByMetadataName(s_operationTypeFullName);
+ INamedTypeSymbol? operationType = compilation.GetOrCreateTypeByMetadataName(s_operationTypeFullName);
if (operationType == null)
{
return null;
@@ -76,9 +76,9 @@ private sealed class FieldsAnalyzer : SyntaxNodeWithinAnalyzerTypeCompilationAna
private readonly INamedTypeSymbol _compilationType;
private readonly INamedTypeSymbol _symbolType;
private readonly INamedTypeSymbol _operationType;
- private readonly INamedTypeSymbol _attributeUsageAttribute;
+ private readonly INamedTypeSymbol? _attributeUsageAttribute;
- public FieldsAnalyzer(INamedTypeSymbol compilationType, INamedTypeSymbol symbolType, INamedTypeSymbol operationType, INamedTypeSymbol attributeUsageAttribute, INamedTypeSymbol diagnosticAnalyzer, INamedTypeSymbol diagnosticAnalyzerAttribute)
+ public FieldsAnalyzer(INamedTypeSymbol compilationType, INamedTypeSymbol symbolType, INamedTypeSymbol operationType, INamedTypeSymbol? attributeUsageAttribute, INamedTypeSymbol diagnosticAnalyzer, INamedTypeSymbol diagnosticAnalyzerAttribute)
: base(diagnosticAnalyzer, diagnosticAnalyzerAttribute)
{
_compilationType = compilationType;
diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzer.cs
index 9c056ddb11..51cfc67987 100644
--- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzer.cs
+++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzer.cs
@@ -4,7 +4,7 @@
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
-using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
@@ -24,7 +24,7 @@ public sealed class DiagnosticDescriptorCreationAnalyzer : DiagnosticAnalyzer
private const string DiagnosticIdParameterName = "id";
private const string DiagnosticCategoryAndIdRangeFile = "DiagnosticCategoryAndIdRanges.txt";
- private static readonly (string prefix, int start, int end) s_defaultAllowedIdsInfo = (null, -1, -1);
+ private static readonly (string? prefix, int start, int end) s_defaultAllowedIdsInfo = (null, -1, -1);
private static readonly LocalizableString s_localizableUseLocalizableStringsTitle = new LocalizableResourceString(nameof(CodeAnalysisDiagnosticsResources.UseLocalizableStringsInDescriptorTitle), CodeAnalysisDiagnosticsResources.ResourceManager, typeof(CodeAnalysisDiagnosticsResources));
private static readonly LocalizableString s_localizableUseLocalizableStringsMessage = new LocalizableResourceString(nameof(CodeAnalysisDiagnosticsResources.UseLocalizableStringsInDescriptorMessage), CodeAnalysisDiagnosticsResources.ResourceManager, typeof(CodeAnalysisDiagnosticsResources));
@@ -140,7 +140,7 @@ public override void Initialize(AnalysisContext context)
context.RegisterCompilationStartAction(compilationContext =>
{
- INamedTypeSymbol diagnosticDescriptorType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(DiagnosticAnalyzerCorrectnessAnalyzer.DiagnosticDescriptorFullName);
+ INamedTypeSymbol? diagnosticDescriptorType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(DiagnosticAnalyzerCorrectnessAnalyzer.DiagnosticDescriptorFullName);
if (diagnosticDescriptorType == null)
{
return;
@@ -150,9 +150,9 @@ public override void Initialize(AnalysisContext context)
var checkCategoryAndAllowedIds = TryGetCategoryAndAllowedIdsMap(
compilationContext.Options.AdditionalFiles,
compilationContext.CancellationToken,
- out AdditionalText additionalTextOpt,
- out ImmutableDictionary> categoryAndAllowedIdsMap,
- out List invalidFileDiagnostics);
+ out AdditionalText? additionalTextOpt,
+ out ImmutableDictionary>? categoryAndAllowedIdsMap,
+ out List? invalidFileDiagnostics);
var idToAnalyzerMap = new ConcurrentDictionary>>();
compilationContext.RegisterOperationAction(operationAnalysisContext =>
@@ -173,10 +173,10 @@ public override void Initialize(AnalysisContext context)
AnalyzeTitle(operationAnalysisContext, objectCreation);
AnalyzeHelpLinkUri(operationAnalysisContext, objectCreation);
- string categoryOpt = null;
+ string? categoryOpt = null;
if (!checkCategoryAndAllowedIds ||
!TryAnalyzeCategory(operationAnalysisContext, objectCreation,
- additionalTextOpt, categoryAndAllowedIdsMap, out categoryOpt, out var allowedIdsInfoList))
+ additionalTextOpt!, categoryAndAllowedIdsMap!, out categoryOpt, out var allowedIdsInfoList))
{
allowedIdsInfoList = default;
}
@@ -259,9 +259,9 @@ private static void AnalyzeHelpLinkUri(OperationAnalysisContext operationAnalysi
OperationAnalysisContext operationAnalysisContext,
IObjectCreationOperation objectCreation,
AdditionalText additionalText,
- ImmutableDictionary> categoryAndAllowedIdsInfoMap,
- out string category,
- out ImmutableArray<(string prefix, int start, int end)> allowedIdsInfoList)
+ ImmutableDictionary> categoryAndAllowedIdsInfoMap,
+ [NotNullWhen(returnValue: true)] out string? category,
+ out ImmutableArray<(string? prefix, int start, int end)> allowedIdsInfoList)
{
category = null;
allowedIdsInfoList = default;
@@ -305,13 +305,13 @@ out ImmutableArray<(string prefix, int start, int end)> allowedIdsInfoList)
private static void AnalyzeRuleId(
OperationAnalysisContext operationAnalysisContext,
IObjectCreationOperation objectCreation,
- AdditionalText additionalTextOpt,
- string categoryOpt,
- ImmutableArray<(string prefix, int start, int end)> allowedIdsInfoListOpt,
+ AdditionalText? additionalTextOpt,
+ string? categoryOpt,
+ ImmutableArray<(string? prefix, int start, int end)> allowedIdsInfoListOpt,
ConcurrentDictionary>> idToAnalyzerMap)
{
var analyzer = ((IFieldSymbol)operationAnalysisContext.ContainingSymbol).ContainingType.OriginalDefinition;
- string ruleId = null;
+ string? ruleId = null;
foreach (var argument in objectCreation.Arguments)
{
if (argument.Parameter.Name.Equals(DiagnosticIdParameterName, StringComparison.OrdinalIgnoreCase))
@@ -362,18 +362,18 @@ ConcurrentBag UpdateLocationsFactory(string analyzerName, ConcurrentBa
// If we have an additional file specifying required range and/or format for the ID, validate the ID.
if (!allowedIdsInfoListOpt.IsDefault)
{
- Debug.Assert(!allowedIdsInfoListOpt.IsEmpty);
- Debug.Assert(categoryOpt != null);
- Debug.Assert(additionalTextOpt != null);
+ RoslynDebug.Assert(!allowedIdsInfoListOpt.IsEmpty);
+ RoslynDebug.Assert(categoryOpt != null);
+ RoslynDebug.Assert(additionalTextOpt != null);
var foundMatch = false;
- static bool ShouldValidateRange((string prefix, int start, int end) range)
+ static bool ShouldValidateRange((string? prefix, int start, int end) range)
=> range.start >= 0 && range.end >= 0;
// Check if ID matches any one of the required ranges.
foreach (var allowedIds in allowedIdsInfoListOpt)
{
- Debug.Assert(allowedIds.prefix != null);
+ RoslynDebug.Assert(allowedIds.prefix != null);
if (ruleId.StartsWith(allowedIds.prefix, StringComparison.Ordinal))
{
@@ -434,9 +434,9 @@ static bool ShouldValidateRange((string prefix, int start, int end) range)
private static bool TryGetCategoryAndAllowedIdsMap(
ImmutableArray additionalFiles,
CancellationToken cancellationToken,
- out AdditionalText additionalText,
- out ImmutableDictionary> categoryAndAllowedIdsMap,
- out List invalidFileDiagnostics)
+ [NotNullWhen(returnValue: true)] out AdditionalText? additionalText,
+ [NotNullWhen(returnValue: true)] out ImmutableDictionary>? categoryAndAllowedIdsMap,
+ out List? invalidFileDiagnostics)
{
invalidFileDiagnostics = null;
categoryAndAllowedIdsMap = null;
@@ -448,7 +448,7 @@ static bool ShouldValidateRange((string prefix, int start, int end) range)
TryParseCategoryAndAllowedIdsInfoFile(additionalText, cancellationToken, out categoryAndAllowedIdsMap, out invalidFileDiagnostics);
}
- private static AdditionalText TryGetCategoryAndAllowedIdsInfoFile(ImmutableArray additionalFiles, CancellationToken cancellationToken)
+ private static AdditionalText? TryGetCategoryAndAllowedIdsInfoFile(ImmutableArray additionalFiles, CancellationToken cancellationToken)
{
StringComparer comparer = StringComparer.Ordinal;
foreach (AdditionalText textFile in additionalFiles)
@@ -468,8 +468,8 @@ private static AdditionalText TryGetCategoryAndAllowedIdsInfoFile(ImmutableArray
private static bool TryParseCategoryAndAllowedIdsInfoFile(
AdditionalText additionalText,
CancellationToken cancellationToken,
- out ImmutableDictionary> categoryAndAllowedIdsInfoMap,
- out List invalidFileDiagnostics)
+ [NotNullWhen(returnValue: true)] out ImmutableDictionary>? categoryAndAllowedIdsInfoMap,
+ out List? invalidFileDiagnostics)
{
// Parse the additional file with allowed diagnostic categories and corresponding ID range.
// FORMAT:
@@ -478,7 +478,7 @@ private static AdditionalText TryGetCategoryAndAllowedIdsInfoFile(ImmutableArray
categoryAndAllowedIdsInfoMap = null;
invalidFileDiagnostics = null;
- var builder = ImmutableDictionary.CreateBuilder>();
+ var builder = ImmutableDictionary.CreateBuilder>();
var lines = additionalText.GetText(cancellationToken).Lines;
foreach (var line in lines)
{
@@ -516,10 +516,10 @@ private static AdditionalText TryGetCategoryAndAllowedIdsInfoFile(ImmutableArray
// 'Category': Comma separate list of 'StartId-EndId' or 'Id' or 'Prefix'
var ranges = parts[1].Split(',');
- var infoList = ImmutableArray.CreateBuilder<(string prefix, int start, int end)>(ranges.Length);
+ var infoList = ImmutableArray.CreateBuilder<(string? prefix, int start, int end)>(ranges.Length);
for (int i = 0; i < ranges.Length; i++)
{
- (string prefix, int start, int end) allowedIdsInfo = s_defaultAllowedIdsInfo;
+ (string? prefix, int start, int end) allowedIdsInfo = s_defaultAllowedIdsInfo;
string range = ranges[i].Trim();
if (!range.Contains('-'))
{
diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/EnableConcurrentExecutionAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/EnableConcurrentExecutionAnalyzer.cs
index f0fbf74e17..8870bf4b9e 100644
--- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/EnableConcurrentExecutionAnalyzer.cs
+++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/EnableConcurrentExecutionAnalyzer.cs
@@ -39,7 +39,7 @@ public override void Initialize(AnalysisContext context)
}
[SuppressMessage("AnalyzerPerformance", "RS1012:Start action has no registered actions.", Justification = "Method returns an analyzer that is registered by the caller.")]
- protected override DiagnosticAnalyzerSymbolAnalyzer GetDiagnosticAnalyzerSymbolAnalyzer(CompilationStartAnalysisContext compilationContext, INamedTypeSymbol diagnosticAnalyzer, INamedTypeSymbol diagnosticAnalyzerAttribute)
+ protected override DiagnosticAnalyzerSymbolAnalyzer? GetDiagnosticAnalyzerSymbolAnalyzer(CompilationStartAnalysisContext compilationContext, INamedTypeSymbol diagnosticAnalyzer, INamedTypeSymbol diagnosticAnalyzerAttribute)
{
var compilation = compilationContext.Compilation;
@@ -62,7 +62,7 @@ protected override DiagnosticAnalyzerSymbolAnalyzer GetDiagnosticAnalyzerSymbolA
return;
}
- IParameterSymbol analysisContextParameter = null;
+ IParameterSymbol? analysisContextParameter = null;
foreach (var parameter in method.Parameters)
{
if (!Equals(parameter.Type, analysisContext))
diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/RegisterActionAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/RegisterActionAnalyzer.cs
index 1c63d764d6..46962224d5 100644
--- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/RegisterActionAnalyzer.cs
+++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/RegisterActionAnalyzer.cs
@@ -4,6 +4,7 @@
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using Analyzer.Utilities;
@@ -117,35 +118,35 @@ public abstract class RegisterActionAnalyzer
/// Map from declared analysis context type parameters to invocations of Register methods on them.
///
- private Dictionary> _nestedActionsMap;
+ private Dictionary>? _nestedActionsMap;
///
/// Set of declared start analysis context parameters that need to be analyzed for and .
///
- private HashSet _declaredStartAnalysisContextParams;
+ private HashSet? _declaredStartAnalysisContextParams;
///
/// Set of declared start analysis context parameters that need to be skipped for and .
/// This is to avoid false positives where context types are passed as arguments to a different invocation, and hence the registration responsibility is not on the current method.
///
- private HashSet _startAnalysisContextParamsToSkip;
+ private HashSet? _startAnalysisContextParamsToSkip;
protected RegisterActionCodeBlockAnalyzer(
INamedTypeSymbol analysisContext,
@@ -231,10 +232,10 @@ private struct NodeAndSymbol
_startAnalysisContextParamsToSkip = null;
}
- protected abstract IEnumerable GetArgumentExpressions(TInvocationExpressionSyntax invocation);
+ protected abstract IEnumerable? GetArgumentExpressions(TInvocationExpressionSyntax invocation);
protected abstract SyntaxNode GetArgumentExpression(TArgumentSyntax argument);
protected abstract SyntaxNode GetInvocationExpression(TInvocationExpressionSyntax invocation);
- protected abstract SyntaxNode GetInvocationReceiver(TInvocationExpressionSyntax invocation);
+ protected abstract SyntaxNode? GetInvocationReceiver(TInvocationExpressionSyntax invocation);
protected abstract bool IsSyntaxKind(ITypeSymbol type);
protected abstract TLanguageKindEnum InvocationExpressionKind { get; }
protected abstract TLanguageKindEnum ArgumentSyntaxKind { get; }
@@ -266,7 +267,7 @@ internal void CodeBlockStartAction(CodeBlockStartAnalysisContext arguments = GetArgumentExpressions(invocation);
+ IEnumerable? arguments = GetArgumentExpressions(invocation);
if (arguments != null)
{
int argumentCount = arguments.Count();
@@ -385,7 +386,7 @@ private void AnalyzeInvocation(SyntaxNodeAnalysisContext context)
if (method.TypeParameters.Length > 0 &&
(isRegisterSyntaxNodeAction || isRegisterCodeBlockStartAction))
{
- ITypeSymbol typeArgument = null;
+ ITypeSymbol? typeArgument = null;
if (method.TypeParameters.Length == 1)
{
if (method.TypeParameters[0].Name == TLanguageKindEnumName)
@@ -469,7 +470,7 @@ private void NoteRegisterActionInvocation(IMethodSymbol method, TInvocationExpre
return;
}
- SyntaxNode receiver = GetInvocationReceiver(invocation);
+ SyntaxNode? receiver = GetInvocationReceiver(invocation);
if (receiver == null)
{
return;
diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ReportDiagnosticAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ReportDiagnosticAnalyzer.cs
index f70bf8d2c4..fc06cfe9b7 100644
--- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ReportDiagnosticAnalyzer.cs
+++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ReportDiagnosticAnalyzer.cs
@@ -35,65 +35,65 @@ public abstract class ReportDiagnosticAnalyzer SupportedDiagnostics => ImmutableArray.Create(InvalidReportDiagnosticRule);
[SuppressMessage("AnalyzerPerformance", "RS1012:Start action has no registered actions.", Justification = "Method returns an analyzer that is registered by the caller.")]
- protected override DiagnosticAnalyzerSymbolAnalyzer GetDiagnosticAnalyzerSymbolAnalyzer(CompilationStartAnalysisContext compilationContext, INamedTypeSymbol diagnosticAnalyzer, INamedTypeSymbol diagnosticAnalyzerAttribute)
+ protected override DiagnosticAnalyzerSymbolAnalyzer? GetDiagnosticAnalyzerSymbolAnalyzer(CompilationStartAnalysisContext compilationContext, INamedTypeSymbol diagnosticAnalyzer, INamedTypeSymbol diagnosticAnalyzerAttribute)
{
Compilation compilation = compilationContext.Compilation;
- INamedTypeSymbol compilationEndAnalysisContext = compilation.GetOrCreateTypeByMetadataName(CompilationEndAnalysisContextFullName);
+ INamedTypeSymbol? compilationEndAnalysisContext = compilation.GetOrCreateTypeByMetadataName(CompilationEndAnalysisContextFullName);
if (compilationEndAnalysisContext == null)
{
return null;
}
- INamedTypeSymbol codeBlockAnalysisContext = compilation.GetOrCreateTypeByMetadataName(CodeBlockAnalysisContextFullName);
+ INamedTypeSymbol? codeBlockAnalysisContext = compilation.GetOrCreateTypeByMetadataName(CodeBlockAnalysisContextFullName);
if (codeBlockAnalysisContext == null)
{
return null;
}
- INamedTypeSymbol operationBlockAnalysisContext = compilation.GetOrCreateTypeByMetadataName(OperationBlockAnalysisContextFullName);
+ INamedTypeSymbol? operationBlockAnalysisContext = compilation.GetOrCreateTypeByMetadataName(OperationBlockAnalysisContextFullName);
if (operationBlockAnalysisContext == null)
{
return null;
}
- INamedTypeSymbol operationAnalysisContext = compilation.GetOrCreateTypeByMetadataName(OperationAnalysisContextFullName);
+ INamedTypeSymbol? operationAnalysisContext = compilation.GetOrCreateTypeByMetadataName(OperationAnalysisContextFullName);
if (operationAnalysisContext == null)
{
return null;
}
- INamedTypeSymbol semanticModelAnalysisContext = compilation.GetOrCreateTypeByMetadataName(SemanticModelAnalysisContextFullName);
+ INamedTypeSymbol? semanticModelAnalysisContext = compilation.GetOrCreateTypeByMetadataName(SemanticModelAnalysisContextFullName);
if (semanticModelAnalysisContext == null)
{
return null;
}
- INamedTypeSymbol symbolAnalysisContext = compilation.GetOrCreateTypeByMetadataName(SymbolAnalysisContextFullName);
+ INamedTypeSymbol? symbolAnalysisContext = compilation.GetOrCreateTypeByMetadataName(SymbolAnalysisContextFullName);
if (symbolAnalysisContext == null)
{
return null;
}
- INamedTypeSymbol syntaxNodeAnalysisContext = compilation.GetOrCreateTypeByMetadataName(SyntaxNodeAnalysisContextFullName);
+ INamedTypeSymbol? syntaxNodeAnalysisContext = compilation.GetOrCreateTypeByMetadataName(SyntaxNodeAnalysisContextFullName);
if (syntaxNodeAnalysisContext == null)
{
return null;
}
- INamedTypeSymbol syntaxTreeAnalysisContext = compilation.GetOrCreateTypeByMetadataName(SyntaxTreeAnalysisContextFullName);
+ INamedTypeSymbol? syntaxTreeAnalysisContext = compilation.GetOrCreateTypeByMetadataName(SyntaxTreeAnalysisContextFullName);
if (syntaxTreeAnalysisContext == null)
{
return null;
}
- INamedTypeSymbol diagnosticType = compilation.GetOrCreateTypeByMetadataName(DiagnosticFullName);
+ INamedTypeSymbol? diagnosticType = compilation.GetOrCreateTypeByMetadataName(DiagnosticFullName);
if (diagnosticType == null)
{
return null;
}
- INamedTypeSymbol diagnosticDescriptorType = compilation.GetOrCreateTypeByMetadataName(DiagnosticDescriptorFullName);
+ INamedTypeSymbol? diagnosticDescriptorType = compilation.GetOrCreateTypeByMetadataName(DiagnosticDescriptorFullName);
if (diagnosticDescriptorType == null)
{
return null;
@@ -124,7 +124,7 @@ public ReportDiagnosticCompilationAnalyzer(ImmutableHashSet co
_supportedDescriptorFieldsMap = ImmutableDictionary>.Empty;
}
- protected abstract IEnumerable GetArgumentExpressions(TInvocationExpressionSyntax invocation);
+ protected abstract IEnumerable? GetArgumentExpressions(TInvocationExpressionSyntax invocation);
protected virtual SyntaxNode GetPropertyGetterBlockSyntax(SyntaxNode declaringSyntaxRefNode)
{
return declaringSyntaxRefNode;
@@ -203,8 +203,8 @@ protected override void AnalyzeNode(SymbolAnalysisContext symbolContext, TInvoca
return;
}
- IEnumerable arguments = GetArgumentExpressions(invocation);
- if (arguments.HasExactly(1))
+ IEnumerable? arguments = GetArgumentExpressions(invocation);
+ if (arguments?.HasExactly(1) == true)
{
SyntaxNode argument = arguments.First();
ITypeSymbol type = semanticModel.GetTypeInfo(argument, symbolContext.CancellationToken).ConvertedType;
@@ -213,7 +213,7 @@ protected override void AnalyzeNode(SymbolAnalysisContext symbolContext, TInvoca
ISymbol argSymbol = semanticModel.GetSymbolInfo(argument, symbolContext.CancellationToken).Symbol;
if (argSymbol != null)
{
- SyntaxNode diagnosticInitializerOpt = null;
+ SyntaxNode? diagnosticInitializerOpt = null;
if (argSymbol is ILocalSymbol local)
{
diff --git a/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/RestrictedInternalsVisibleToAnalyzer.cs b/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/RestrictedInternalsVisibleToAnalyzer.cs
index 1b030a97e4..3a4d574957 100644
--- a/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/RestrictedInternalsVisibleToAnalyzer.cs
+++ b/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/RestrictedInternalsVisibleToAnalyzer.cs
@@ -176,7 +176,7 @@ private void OnCompilationStart(CompilationStartAnalysisContext compilationConte
}
private static void VerifySymbol(
- ISymbol symbol,
+ ISymbol? symbol,
SyntaxNode node,
Action reportDiagnostic,
ImmutableDictionary> restrictedInternalsVisibleToMap,
@@ -235,8 +235,8 @@ private void OnCompilationStart(CompilationStartAnalysisContext compilationConte
}
private static void MarkIsBanned(
- INamespaceSymbol startNamespace,
- INamespaceSymbol uptoNamespace,
+ INamespaceSymbol? startNamespace,
+ INamespaceSymbol? uptoNamespace,
ConcurrentDictionary namespaceToIsBannedMap,
bool banned)
{
diff --git a/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/SymbolIsBannedAnalyzer.cs b/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/SymbolIsBannedAnalyzer.cs
index ae4dc0aa16..f16c948b51 100644
--- a/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/SymbolIsBannedAnalyzer.cs
+++ b/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/SymbolIsBannedAnalyzer.cs
@@ -176,7 +176,7 @@ private void OnCompilationStart(CompilationStartAnalysisContext compilationConte
return;
- Dictionary ReadBannedApis()
+ Dictionary? ReadBannedApis()
{
var query =
from additionalFile in compilationContext.Options.AdditionalFiles
@@ -253,14 +253,17 @@ void VerifyAttributes(Action reportDiagnostic, ImmutableArray reportDiagnostic, ITypeSymbol type, SyntaxNode syntaxNode)
+ bool VerifyType(Action reportDiagnostic, ITypeSymbol? type, SyntaxNode syntaxNode)
{
+ RoslynDebug.Assert(entryBySymbol != null);
+
do
{
if (!VerifyTypeArguments(reportDiagnostic, type, syntaxNode, out type))
{
return false;
}
+
if (type == null)
{
// Type will be null for arrays and pointers.
@@ -285,7 +288,7 @@ bool VerifyType(Action reportDiagnostic, ITypeSymbol type, SyntaxNod
return true;
}
- bool VerifyTypeArguments(Action reportDiagnostic, ITypeSymbol type, SyntaxNode syntaxNode, out ITypeSymbol originalDefinition)
+ bool VerifyTypeArguments(Action reportDiagnostic, ITypeSymbol? type, SyntaxNode syntaxNode, out ITypeSymbol? originalDefinition)
{
switch (type)
{
@@ -311,7 +314,7 @@ bool VerifyTypeArguments(Action reportDiagnostic, ITypeSymbol type,
return VerifyType(reportDiagnostic, pointerTypeSymbol.PointedAtType, syntaxNode);
default:
- originalDefinition = type.OriginalDefinition;
+ originalDefinition = type?.OriginalDefinition;
break;
}
@@ -321,6 +324,8 @@ bool VerifyTypeArguments(Action reportDiagnostic, ITypeSymbol type,
void VerifySymbol(Action reportDiagnostic, ISymbol symbol, SyntaxNode syntaxNode)
{
+ RoslynDebug.Assert(entryBySymbol != null);
+
symbol = symbol.OriginalDefinition;
if (entryBySymbol.TryGetValue(symbol, out var entry))
diff --git a/src/Microsoft.CodeAnalysis.FlowAnalysis.Utilities/PublicAPI.Unshipped.txt b/src/Microsoft.CodeAnalysis.FlowAnalysis.Utilities/PublicAPI.Unshipped.txt
index 1d909a8bbd..0df430f45c 100644
--- a/src/Microsoft.CodeAnalysis.FlowAnalysis.Utilities/PublicAPI.Unshipped.txt
+++ b/src/Microsoft.CodeAnalysis.FlowAnalysis.Utilities/PublicAPI.Unshipped.txt
@@ -67,7 +67,7 @@ Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocation.TryGetNodeToReport
Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocationDataFlowOperationVisitor
Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocationDataFlowOperationVisitor.AbstractLocationDataFlowOperationVisitor(TAnalysisContext analysisContext) -> void
Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocationDataFlowOperationVisitor.ApplyMissingCurrentAnalysisDataForUnhandledExceptionData(Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DictionaryAnalysisData coreDataAtException, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DictionaryAnalysisData coreCurrentAnalysisData) -> void
-Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocationDataFlowOperationVisitor.ResetAnalysisData(Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DictionaryAnalysisData currentAnalysisDataOpt) -> void
+Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocationDataFlowOperationVisitor.ResetAnalysisData(Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DictionaryAnalysisData currentAnalysisData) -> void
Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocationDataFlowOperationVisitor.SetAbstractValue(Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAbstractValue instanceLocation, TAbstractAnalysisValue value) -> void
Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractLocationDataFlowOperationVisitor.SetAbstractValue(System.Collections.Generic.IEnumerable locations, TAbstractAnalysisValue value) -> void
Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AbstractValueDomain
@@ -113,7 +113,7 @@ Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntityDataFlowOperationVisi
Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntityDataFlowOperationVisitor.GetChildAnalysisEntities(Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.PointsToAnalysis.PointsToAbstractValue instanceLocationOpt) -> System.Collections.Immutable.ImmutableHashSet
Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntityDataFlowOperationVisitor.GetClonedAnalysisDataHelper(System.Collections.Generic.IDictionary analysisData) -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DictionaryAnalysisData
Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntityDataFlowOperationVisitor.GetTrimmedCurrentAnalysisDataHelper(System.Collections.Generic.IEnumerable withEntities, System.Collections.Generic.IDictionary existingValues, System.Action setAbstractValue) -> TAnalysisData
-Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntityDataFlowOperationVisitor.ResetAnalysisData(Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DictionaryAnalysisData currentAnalysisDataOpt) -> void
+Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntityDataFlowOperationVisitor.ResetAnalysisData(Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.DictionaryAnalysisData currentAnalysisData) -> void
Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntityFactory
Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntityFactory.CreateWithNewInstanceRoot(Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity analysisEntity, Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity newRootInstance) -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity
Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntityFactory.ThisOrMeInstance.get -> Microsoft.CodeAnalysis.FlowAnalysis.DataFlow.AnalysisEntity
diff --git a/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpDefineAccessorsForAttributeArguments.cs b/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpDefineAccessorsForAttributeArguments.cs
index d651a613f1..d56dcdb6d5 100644
--- a/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpDefineAccessorsForAttributeArguments.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpDefineAccessorsForAttributeArguments.cs
@@ -4,6 +4,7 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines
{
@@ -16,7 +17,10 @@ namespace Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class CSharpDefineAccessorsForAttributeArgumentsAnalyzer : DefineAccessorsForAttributeArgumentsAnalyzer
{
- protected override bool IsAssignableTo(ITypeSymbol fromSymbol, ITypeSymbol toSymbol, Compilation compilation)
+ protected override bool IsAssignableTo(
+ [NotNullWhen(returnValue: true)] ITypeSymbol? fromSymbol,
+ [NotNullWhen(returnValue: true)] ITypeSymbol? toSymbol,
+ Compilation compilation)
{
return fromSymbol != null &&
toSymbol != null &&
diff --git a/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpDoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.cs b/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpDoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.cs
index 79fad03f01..9cfec345e0 100644
--- a/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpDoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpDoNotRaiseExceptionsInUnexpectedLocationsAnalyzer.cs
@@ -4,6 +4,7 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines
{
@@ -13,7 +14,10 @@ namespace Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class CSharpDoNotRaiseExceptionsInUnexpectedLocationsAnalyzer : DoNotRaiseExceptionsInUnexpectedLocationsAnalyzer
{
- protected override bool IsAssignableTo(ITypeSymbol fromSymbol, ITypeSymbol toSymbol, Compilation compilation)
+ protected override bool IsAssignableTo(
+ [NotNullWhen(returnValue: true)] ITypeSymbol? fromSymbol,
+ [NotNullWhen(returnValue: true)] ITypeSymbol? toSymbol,
+ Compilation compilation)
{
return fromSymbol != null &&
toSymbol != null &&
diff --git a/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpEnumStorageShouldBeInt32.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpEnumStorageShouldBeInt32.Fixer.cs
index 91b8030561..68d838540a 100644
--- a/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpEnumStorageShouldBeInt32.Fixer.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpEnumStorageShouldBeInt32.Fixer.cs
@@ -14,11 +14,10 @@ namespace Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines
[ExportCodeFixProvider(LanguageNames.CSharp), Shared]
public sealed class CSharpEnumStorageShouldBeInt32Fixer : EnumStorageShouldBeInt32Fixer
{
- protected override SyntaxNode GetTargetNode(SyntaxNode node)
+ protected override SyntaxNode? GetTargetNode(SyntaxNode node)
{
var enumDecl = (EnumDeclarationSyntax)node;
- var baseTypeNode = (enumDecl.BaseList.Types.FirstOrDefault() as SimpleBaseTypeSyntax)?.Type;
- return baseTypeNode;
+ return (enumDecl.BaseList.Types.FirstOrDefault() as SimpleBaseTypeSyntax)?.Type;
}
}
}
diff --git a/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpPassSystemUriObjectsInsteadOfStrings.cs b/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpPassSystemUriObjectsInsteadOfStrings.cs
index 10c2e19216..a50da8bc2f 100644
--- a/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpPassSystemUriObjectsInsteadOfStrings.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpPassSystemUriObjectsInsteadOfStrings.cs
@@ -13,7 +13,7 @@ namespace Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public sealed class CSharpPassSystemUriObjectsInsteadOfStringsAnalyzer : PassSystemUriObjectsInsteadOfStringsAnalyzer
{
- protected override SyntaxNode GetInvocationExpression(SyntaxNode node)
+ protected override SyntaxNode? GetInvocationExpression(SyntaxNode node)
{
var invocationNode = node as InvocationExpressionSyntax;
return invocationNode?.Expression;
diff --git a/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpStaticHolderTypes.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpStaticHolderTypes.Fixer.cs
index 8d0cf5cd34..0ce195ad22 100644
--- a/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpStaticHolderTypes.Fixer.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpStaticHolderTypes.Fixer.cs
@@ -34,7 +34,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
cancellationToken.ThrowIfCancellationRequested();
SyntaxNode root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
- ClassDeclarationSyntax classDeclaration = root.FindToken(span.Start).Parent?.FirstAncestorOrSelf();
+ ClassDeclarationSyntax? classDeclaration = root.FindToken(span.Start).Parent?.FirstAncestorOrSelf();
if (classDeclaration != null)
{
string title = MicrosoftCodeQualityAnalyzersResources.MakeClassStatic;
diff --git a/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpUseGenericEventHandlerInstances.cs b/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpUseGenericEventHandlerInstances.cs
index 7eea392ccd..f560ee4d7d 100644
--- a/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpUseGenericEventHandlerInstances.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/CSharp/ApiDesignGuidelines/CSharpUseGenericEventHandlerInstances.cs
@@ -4,13 +4,17 @@
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
namespace Microsoft.CodeQuality.CSharp.Analyzers.ApiDesignGuidelines
{
[DiagnosticAnalyzer(LanguageNames.CSharp)]
public class CSharpUseGenericEventHandlerInstancesAnalyzer : UseGenericEventHandlerInstancesAnalyzer
{
- protected override bool IsAssignableTo(Compilation compilation, ITypeSymbol fromSymbol, ITypeSymbol toSymbol)
+ protected override bool IsAssignableTo(
+ [NotNullWhen(returnValue: true)] ITypeSymbol? fromSymbol,
+ [NotNullWhen(returnValue: true)] ITypeSymbol? toSymbol,
+ Compilation compilation)
{
return
fromSymbol != null &&
diff --git a/src/Microsoft.CodeQuality.Analyzers/CSharp/QualityGuidelines/CSharpMarkMembersAsStatic.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/CSharp/QualityGuidelines/CSharpMarkMembersAsStatic.Fixer.cs
index a03a91e3a4..d9bd2c13bc 100644
--- a/src/Microsoft.CodeQuality.Analyzers/CSharp/QualityGuidelines/CSharpMarkMembersAsStatic.Fixer.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/CSharp/QualityGuidelines/CSharpMarkMembersAsStatic.Fixer.cs
@@ -15,10 +15,10 @@ namespace Microsoft.CodeQuality.CSharp.Analyzers.QualityGuidelines
[ExportCodeFixProvider(LanguageNames.CSharp), Shared]
public sealed class CSharpMarkMembersAsStaticFixer : MarkMembersAsStaticFixer
{
- protected override IEnumerable GetTypeArguments(SyntaxNode node)
+ protected override IEnumerable? GetTypeArguments(SyntaxNode node)
=> (node as GenericNameSyntax)?.TypeArgumentList.Arguments;
- protected override SyntaxNode GetExpressionOfInvocation(SyntaxNode invocation)
+ protected override SyntaxNode? GetExpressionOfInvocation(SyntaxNode invocation)
=> (invocation as InvocationExpressionSyntax)?.Expression;
}
}
\ No newline at end of file
diff --git a/src/Microsoft.CodeQuality.Analyzers/CSharp/QualityGuidelines/CSharpUseLiteralsWhereAppropriate.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/CSharp/QualityGuidelines/CSharpUseLiteralsWhereAppropriate.Fixer.cs
index f60a03cb99..a6089bac85 100644
--- a/src/Microsoft.CodeQuality.Analyzers/CSharp/QualityGuidelines/CSharpUseLiteralsWhereAppropriate.Fixer.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/CSharp/QualityGuidelines/CSharpUseLiteralsWhereAppropriate.Fixer.cs
@@ -15,14 +15,14 @@ namespace Microsoft.CodeQuality.CSharp.Analyzers.QualityGuidelines
[ExportCodeFixProvider(LanguageNames.CSharp), Shared]
public sealed class CSharpUseLiteralsWhereAppropriateFixer : UseLiteralsWhereAppropriateFixer
{
- protected override SyntaxNode GetFieldDeclaration(SyntaxNode syntaxNode)
+ protected override SyntaxNode? GetFieldDeclaration(SyntaxNode syntaxNode)
{
while (syntaxNode != null && !(syntaxNode is FieldDeclarationSyntax))
{
syntaxNode = syntaxNode.Parent;
}
- var field = (FieldDeclarationSyntax)syntaxNode;
+ var field = (FieldDeclarationSyntax?)syntaxNode;
// Multiple declarators are not supported, as one of them may not be constant.
return field?.Declaration.Variables.Count > 1 ? null : field;
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/AbstractTypesShouldNotHaveConstructors.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/AbstractTypesShouldNotHaveConstructors.Fixer.cs
index e43189fd39..572846ab54 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/AbstractTypesShouldNotHaveConstructors.Fixer.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/AbstractTypesShouldNotHaveConstructors.Fixer.cs
@@ -1,12 +1,14 @@
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
+using System.Collections.Generic;
using System.Collections.Immutable;
using System.Composition;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Analyzer.Utilities;
+using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.Editing;
@@ -33,7 +35,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
context.Diagnostics);
}
- private static SyntaxNode GetDeclaration(ISymbol symbol)
+ private static SyntaxNode? GetDeclaration(ISymbol symbol)
{
return (symbol.DeclaringSyntaxReferences.Length > 0) ? symbol.DeclaringSyntaxReferences[0].GetSyntax() : null;
}
@@ -42,7 +44,7 @@ private static async Task ChangeAccessibilityCodeFix(Document document
{
SemanticModel model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var classSymbol = (INamedTypeSymbol)model.GetDeclaredSymbol(nodeToFix, cancellationToken);
- System.Collections.Generic.List instanceConstructors = classSymbol.InstanceConstructors.Where(t => t.DeclaredAccessibility == Accessibility.Public).Select(t => GetDeclaration(t)).Where(d => d != null).ToList();
+ List instanceConstructors = classSymbol.InstanceConstructors.Where(t => t.DeclaredAccessibility == Accessibility.Public).Select(t => GetDeclaration(t)).WhereNotNull().ToList();
SyntaxGenerator generator = SyntaxGenerator.GetGenerator(document);
SyntaxNode newRoot = root.ReplaceNodes(instanceConstructors, (original, rewritten) => generator.WithAccessibility(original, Accessibility.Protected));
return document.WithSyntaxRoot(newRoot);
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/AbstractTypesShouldNotHaveConstructors.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/AbstractTypesShouldNotHaveConstructors.cs
index 850ac136e8..3cf44cb566 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/AbstractTypesShouldNotHaveConstructors.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/AbstractTypesShouldNotHaveConstructors.cs
@@ -42,7 +42,7 @@ public override void Initialize(AnalysisContext context)
private static void AnalyzeSymbol(SymbolAnalysisContext context)
{
- var symbol = context.Symbol as INamedTypeSymbol;
+ var symbol = (INamedTypeSymbol)context.Symbol;
if (symbol.IsAbstract &&
symbol.MatchesConfiguredVisibility(context.Options, Rule, context.CancellationToken))
{
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/CancellationTokenParametersMustComeLast.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/CancellationTokenParametersMustComeLast.cs
index 3e8ef8cc4f..46f2990b55 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/CancellationTokenParametersMustComeLast.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/CancellationTokenParametersMustComeLast.cs
@@ -37,7 +37,7 @@ public override void Initialize(AnalysisContext context)
context.RegisterCompilationStartAction(compilationContext =>
{
- INamedTypeSymbol cancellationTokenType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingCancellationToken);
+ INamedTypeSymbol? cancellationTokenType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingCancellationToken);
if (cancellationTokenType != null)
{
compilationContext.RegisterSymbolAction(symbolContext =>
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/CollectionPropertiesShouldBeReadOnly.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/CollectionPropertiesShouldBeReadOnly.cs
index e878e0df8b..cd6d688d8c 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/CollectionPropertiesShouldBeReadOnly.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/CollectionPropertiesShouldBeReadOnly.cs
@@ -57,10 +57,10 @@ public override void Initialize(AnalysisContext analysisContext)
analysisContext.RegisterCompilationStartAction(
(context) =>
{
- INamedTypeSymbol iCollectionType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsICollection);
- INamedTypeSymbol genericICollectionType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericICollection1);
- INamedTypeSymbol arrayType = context.Compilation.GetSpecialType(SpecialType.System_Array);
- INamedTypeSymbol dataMemberAttribute = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationDataMemberAttribute);
+ INamedTypeSymbol? iCollectionType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsICollection);
+ INamedTypeSymbol? genericICollectionType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericICollection1);
+ INamedTypeSymbol? arrayType = context.Compilation.GetSpecialType(SpecialType.System_Array);
+ INamedTypeSymbol? dataMemberAttribute = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationDataMemberAttribute);
ImmutableHashSet immutableInterfaces = GetIImmutableInterfaces(context.Compilation);
if (iCollectionType == null ||
@@ -79,7 +79,7 @@ public override void Initialize(AnalysisContext analysisContext)
INamedTypeSymbol iCollectionType,
INamedTypeSymbol genericICollectionType,
INamedTypeSymbol arrayType,
- INamedTypeSymbol dataMemberAttribute,
+ INamedTypeSymbol? dataMemberAttribute,
ImmutableHashSet immutableInterfaces)
{
var property = (IPropertySymbol)context.Symbol;
@@ -147,7 +147,7 @@ private static ImmutableHashSet GetIImmutableInterfaces(Compil
return builder.ToImmutable();
// Local functions.
- void AddIfNotNull(INamedTypeSymbol type)
+ void AddIfNotNull(INamedTypeSymbol? type)
{
if (type != null)
{
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/CollectionsShouldImplementGenericInterface.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/CollectionsShouldImplementGenericInterface.cs
index fbb7fa68fb..284c73fb8d 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/CollectionsShouldImplementGenericInterface.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/CollectionsShouldImplementGenericInterface.cs
@@ -1,7 +1,6 @@
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
-using System.Diagnostics;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
@@ -58,12 +57,12 @@ public override void Initialize(AnalysisContext analysisContext)
analysisContext.RegisterCompilationStartAction(
(context) =>
{
- INamedTypeSymbol iCollectionType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsICollection);
- INamedTypeSymbol genericICollectionType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericICollection1);
- INamedTypeSymbol iEnumerableType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsIEnumerable);
- INamedTypeSymbol genericIEnumerableType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericIEnumerable1);
- INamedTypeSymbol iListType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsIList);
- INamedTypeSymbol genericIListType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericIList1);
+ INamedTypeSymbol? iCollectionType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsICollection);
+ INamedTypeSymbol? genericICollectionType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericICollection1);
+ INamedTypeSymbol? iEnumerableType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsIEnumerable);
+ INamedTypeSymbol? genericIEnumerableType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericIEnumerable1);
+ INamedTypeSymbol? iListType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsIList);
+ INamedTypeSymbol? genericIListType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericIList1);
if (iCollectionType == null && genericICollectionType == null &&
iEnumerableType == null && genericIEnumerableType == null &&
@@ -82,12 +81,12 @@ public override void Initialize(AnalysisContext analysisContext)
private static void AnalyzeSymbol(
SymbolAnalysisContext context,
- INamedTypeSymbol iCollectionType,
- INamedTypeSymbol gCollectionType,
- INamedTypeSymbol iEnumerableType,
- INamedTypeSymbol gEnumerableType,
- INamedTypeSymbol iListType,
- INamedTypeSymbol gListType)
+ INamedTypeSymbol? iCollectionType,
+ INamedTypeSymbol? gCollectionType,
+ INamedTypeSymbol? iEnumerableType,
+ INamedTypeSymbol? gEnumerableType,
+ INamedTypeSymbol? iListType,
+ INamedTypeSymbol? gListType)
{
var namedTypeSymbol = (INamedTypeSymbol)context.Symbol;
@@ -127,8 +126,8 @@ public override void Initialize(AnalysisContext analysisContext)
}
}
- INamedTypeSymbol missingInterface;
- INamedTypeSymbol implementedInterface;
+ INamedTypeSymbol? missingInterface;
+ INamedTypeSymbol? implementedInterface;
if (allInterfacesStatus.GenericIListPresent)
{
// Implemented IList, meaning has all 3 generic interfaces. Nothing can be wrong.
@@ -168,7 +167,7 @@ public override void Initialize(AnalysisContext analysisContext)
return;
}
- Debug.Assert(missingInterface != null && implementedInterface != null);
+ RoslynDebug.Assert(missingInterface != null && implementedInterface != null);
context.ReportDiagnostic(Diagnostic.Create(Rule,
namedTypeSymbol.Locations.First(),
namedTypeSymbol.Name,
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DefineAccessorsForAttributeArguments.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DefineAccessorsForAttributeArguments.cs
index 630ad117fa..fe4581bd29 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DefineAccessorsForAttributeArguments.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DefineAccessorsForAttributeArguments.cs
@@ -3,6 +3,7 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
+using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
@@ -65,7 +66,7 @@ public override void Initialize(AnalysisContext analysisContext)
analysisContext.RegisterCompilationStartAction(compilationContext =>
{
- INamedTypeSymbol attributeType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemAttribute);
+ INamedTypeSymbol? attributeType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemAttribute);
if (attributeType == null)
{
return;
@@ -92,7 +93,10 @@ private void AnalyzeSymbol(INamedTypeSymbol symbol, INamedTypeSymbol attributeTy
}
}
- protected abstract bool IsAssignableTo(ITypeSymbol fromSymbol, ITypeSymbol toSymbol, Compilation compilation);
+ protected abstract bool IsAssignableTo(
+ [NotNullWhen(returnValue: true)] ITypeSymbol? fromSymbol,
+ [NotNullWhen(returnValue: true)] ITypeSymbol? toSymbol,
+ Compilation compilation);
private static IEnumerable GetAllPublicConstructorParameters(INamedTypeSymbol attributeType)
{
@@ -142,7 +146,7 @@ private void AnalyzeParameters(Compilation compilation, IEnumerable { { "case", AddAccessorCase } }.ToImmutableDictionary(), parameter.Name, attributeType.Name);
+ return parameter.Locations.CreateDiagnostic(DefaultRule, new Dictionary { { "case", AddAccessorCase } }.ToImmutableDictionary(), parameter.Name, attributeType.Name);
}
private static Diagnostic GetIncreaseVisibilityDiagnostic(IParameterSymbol parameter, IPropertySymbol property)
{
// If '{0}' is the property accessor for positional argument '{1}', make it public.
- return property.GetMethod.Locations.CreateDiagnostic(IncreaseVisibilityRule, new Dictionary { { "case", MakePublicCase } }.ToImmutableDictionary(), property.Name, parameter.Name);
+ return property.GetMethod.Locations.CreateDiagnostic(IncreaseVisibilityRule, new Dictionary { { "case", MakePublicCase } }.ToImmutableDictionary(), property.Name, parameter.Name);
}
private static Diagnostic GetRemoveSetterDiagnostic(IParameterSymbol parameter, IPropertySymbol property)
{
// Remove the property setter from '{0}' or reduce its accessibility because it corresponds to positional argument '{1}'.
- return property.SetMethod.Locations.CreateDiagnostic(RemoveSetterRule, new Dictionary { { "case", RemoveSetterCase } }.ToImmutableDictionary(), property.Name, parameter.Name);
+ return property.SetMethod.Locations.CreateDiagnostic(RemoveSetterRule, new Dictionary { { "case", RemoveSetterCase } }.ToImmutableDictionary(), property.Name, parameter.Name);
}
}
}
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DoNotDirectlyAwaitATask.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DoNotDirectlyAwaitATask.cs
index d92f84d864..468b4e3326 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DoNotDirectlyAwaitATask.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DoNotDirectlyAwaitATask.cs
@@ -48,8 +48,7 @@ public override void Initialize(AnalysisContext analysisContext)
return;
}
- ImmutableArray taskTypes = GetTaskTypes(context.Compilation);
- if (taskTypes.Any(t => t == null))
+ if (!TryGetTaskTypes(context.Compilation, out ImmutableArray taskTypes))
{
return;
}
@@ -78,22 +77,29 @@ public override void Initialize(AnalysisContext analysisContext)
private static void AnalyzeOperation(OperationAnalysisContext context, ImmutableArray taskTypes)
{
- IAwaitOperation awaitExpression = context.Operation as IAwaitOperation;
+ var awaitExpression = (IAwaitOperation)context.Operation;
// Get the type of the expression being awaited and check it's a task type.
- ITypeSymbol typeOfAwaitedExpression = awaitExpression?.Operation?.Type;
+ ITypeSymbol? typeOfAwaitedExpression = awaitExpression.Operation.Type;
if (typeOfAwaitedExpression != null && taskTypes.Contains(typeOfAwaitedExpression.OriginalDefinition))
{
context.ReportDiagnostic(awaitExpression.Operation.Syntax.CreateDiagnostic(Rule));
}
}
- private static ImmutableArray GetTaskTypes(Compilation compilation)
+ private static bool TryGetTaskTypes(Compilation compilation, out ImmutableArray taskTypes)
{
- INamedTypeSymbol taskType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTask);
- INamedTypeSymbol taskOfTType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksGenericTask);
+ INamedTypeSymbol? taskType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTask);
+ INamedTypeSymbol? taskOfTType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksGenericTask);
- return ImmutableArray.Create(taskType, taskOfTType);
+ if (taskType == null || taskOfTType == null)
+ {
+ taskTypes = ImmutableArray.Empty;
+ return false;
+ }
+
+ taskTypes = ImmutableArray.Create(taskType, taskOfTType);
+ return true;
}
}
}
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DoNotRaiseExceptionsInUnexpectedLocations.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DoNotRaiseExceptionsInUnexpectedLocations.cs
index d14ae34451..7c25d6721f 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DoNotRaiseExceptionsInUnexpectedLocations.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DoNotRaiseExceptionsInUnexpectedLocations.cs
@@ -3,6 +3,7 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
+using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
@@ -67,7 +68,7 @@ public override void Initialize(AnalysisContext analysisContext)
analysisContext.RegisterCompilationStartAction(compilationStartContext =>
{
Compilation compilation = compilationStartContext.Compilation;
- INamedTypeSymbol exceptionType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemException);
+ INamedTypeSymbol? exceptionType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemException);
if (exceptionType == null)
{
return;
@@ -110,7 +111,10 @@ public override void Initialize(AnalysisContext analysisContext)
});
}
- protected abstract bool IsAssignableTo(ITypeSymbol fromSymbol, ITypeSymbol toSymbol, Compilation compilation);
+ protected abstract bool IsAssignableTo(
+ [NotNullWhen(returnValue: true)] ITypeSymbol? fromSymbol,
+ [NotNullWhen(returnValue: true)] ITypeSymbol? toSymbol,
+ Compilation compilation);
///
/// This object describes a class of methods where exception throwing statements should be analyzed.
@@ -138,12 +142,12 @@ private class MethodCategory
///
public ImmutableHashSet AllowedExceptions { get; }
- public MethodCategory(Func matchFunction, bool analyzeOnlyPublicMethods, DiagnosticDescriptor rule, params ITypeSymbol[] allowedExceptionTypes)
+ public MethodCategory(Func matchFunction, bool analyzeOnlyPublicMethods, DiagnosticDescriptor rule, params ITypeSymbol?[] allowedExceptionTypes)
{
_matchFunction = matchFunction;
_analyzeOnlyPublicMethods = analyzeOnlyPublicMethods;
this.Rule = rule;
- AllowedExceptions = allowedExceptionTypes.ToImmutableHashSet();
+ AllowedExceptions = allowedExceptionTypes.WhereNotNull().ToImmutableHashSet();
}
///
@@ -251,7 +255,7 @@ private static bool IsEqualsInterfaceImplementation(IMethodSymbol method, Compil
{
// Substitute the type of the first parameter of Equals in the generic interface and then check if that
// interface method is implemented by the given method.
- INamedTypeSymbol iEqualityComparer = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericIEqualityComparer1);
+ INamedTypeSymbol? iEqualityComparer = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericIEqualityComparer1);
if (method.IsImplementationOfInterfaceMethod(method.Parameters.First().Type, iEqualityComparer, WellKnownMemberNames.ObjectEquals))
{
return true;
@@ -259,7 +263,7 @@ private static bool IsEqualsInterfaceImplementation(IMethodSymbol method, Compil
// Substitute the type of the first parameter of Equals in the generic interface and then check if that
// interface method is implemented by the given method.
- INamedTypeSymbol iEquatable = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIEquatable1);
+ INamedTypeSymbol? iEquatable = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIEquatable1);
if (method.IsImplementationOfInterfaceMethod(method.Parameters.First().Type, iEquatable, WellKnownMemberNames.ObjectEquals))
{
return true;
@@ -286,14 +290,14 @@ private static bool IsGetHashCodeInterfaceImplementation(IMethodSymbol method, C
{
// Substitute the type of the first parameter of Equals in the generic interface and then check if that
// interface method is implemented by the given method.
- INamedTypeSymbol iEqualityComparer = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericIEqualityComparer1);
+ INamedTypeSymbol? iEqualityComparer = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericIEqualityComparer1);
if (method.IsImplementationOfInterfaceMethod(method.Parameters.First().Type, iEqualityComparer, WellKnownMemberNames.ObjectGetHashCode))
{
return true;
}
- INamedTypeSymbol iHashCodeProvider = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsIHashCodeProvider);
+ INamedTypeSymbol? iHashCodeProvider = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsIHashCodeProvider);
if (method.IsImplementationOfInterfaceMethod(null, iHashCodeProvider, WellKnownMemberNames.ObjectGetHashCode))
{
return true;
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumStorageShouldBeInt32.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumStorageShouldBeInt32.Fixer.cs
index c967b6ef91..fedb36dc81 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumStorageShouldBeInt32.Fixer.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumStorageShouldBeInt32.Fixer.cs
@@ -16,7 +16,7 @@ namespace Microsoft.CodeQuality.Analyzers.ApiDesignGuidelines
///
public abstract class EnumStorageShouldBeInt32Fixer : CodeFixProvider
{
- protected abstract SyntaxNode GetTargetNode(SyntaxNode node);
+ protected abstract SyntaxNode? GetTargetNode(SyntaxNode node);
public sealed override ImmutableArray FixableDiagnosticIds => ImmutableArray.Create(EnumStorageShouldBeInt32Analyzer.RuleId);
@@ -54,6 +54,10 @@ private async Task ChangeEnumTypeToInt32Async(Document document, Diagn
// Find the target syntax node to replace. Was not able to find a language neutral way of doing this. So using the language specific methods
var targetNode = GetTargetNode(enumDeclarationNode);
+ if (targetNode == null)
+ {
+ return document;
+ }
// Remove target node
editor.RemoveNode(targetNode, SyntaxRemoveOptions.KeepLeadingTrivia | SyntaxRemoveOptions.KeepTrailingTrivia | SyntaxRemoveOptions.KeepExteriorTrivia | SyntaxRemoveOptions.KeepEndOfLine);
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumStorageShouldBeInt32.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumStorageShouldBeInt32.cs
index eb80776473..771e4924f0 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumStorageShouldBeInt32.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumStorageShouldBeInt32.cs
@@ -45,7 +45,7 @@ public override void Initialize(AnalysisContext analysisContext)
analysisContext.RegisterCompilationStartAction(compilationContext =>
{
- INamedTypeSymbol flagsAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemFlagsAttribute);
+ INamedTypeSymbol? flagsAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemFlagsAttribute);
if (flagsAttribute == null)
{
return;
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumWithFlagsAttribute.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumWithFlagsAttribute.Fixer.cs
index 4a6710060b..d841fac6e1 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumWithFlagsAttribute.Fixer.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumWithFlagsAttribute.Fixer.cs
@@ -3,7 +3,6 @@
using System;
using System.Collections.Immutable;
using System.Composition;
-using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -30,7 +29,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
SemanticModel model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
- INamedTypeSymbol flagsAttributeType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemFlagsAttribute);
+ INamedTypeSymbol? flagsAttributeType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemFlagsAttribute);
if (flagsAttributeType == null)
{
return;
@@ -70,8 +69,10 @@ private static SyntaxNode AddFlagsAttribute(SyntaxGenerator generator, SyntaxNod
private static SyntaxNode RemoveFlagsAttribute(SyntaxGenerator generator, SemanticModel model, SyntaxNode enumTypeSyntax, INamedTypeSymbol flagsAttributeType, CancellationToken cancellationToken)
{
- var enumType = model.GetDeclaredSymbol(enumTypeSyntax, cancellationToken) as INamedTypeSymbol;
- Debug.Assert(enumType != null);
+ if (!(model.GetDeclaredSymbol(enumTypeSyntax, cancellationToken) is INamedTypeSymbol enumType))
+ {
+ return enumTypeSyntax;
+ }
AttributeData flagsAttribute = enumType.GetAttributes().First(a => Equals(a.AttributeClass, flagsAttributeType));
SyntaxNode attributeNode = flagsAttribute.ApplicationSyntaxReference.GetSyntax(cancellationToken);
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumWithFlagsAttribute.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumWithFlagsAttribute.cs
index dc8e7ed6a1..a7c6b14120 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumWithFlagsAttribute.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumWithFlagsAttribute.cs
@@ -165,8 +165,6 @@ private static bool ShouldBeFlags(IList enumValues)
private static ulong GetMissingBitsInBinaryForm(IList values)
{
- Debug.Assert(values != null);
-
// all the powers of two that are individually represented
ulong powersOfTwo = 0;
bool foundNonPowerOfTwo = false;
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumsShouldHavePluralNames.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumsShouldHavePluralNames.cs
index a3590b361a..84b9ef90ec 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumsShouldHavePluralNames.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumsShouldHavePluralNames.cs
@@ -97,7 +97,7 @@ public override void Initialize(AnalysisContext analysisContext)
analysisContext.RegisterCompilationStartAction(compilationContext =>
{
- INamedTypeSymbol flagsAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemFlagsAttribute);
+ INamedTypeSymbol? flagsAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemFlagsAttribute);
if (flagsAttribute == null)
{
return;
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumsShouldHaveZeroValue.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumsShouldHaveZeroValue.Fixer.cs
index abd32ab12c..c41527922a 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumsShouldHaveZeroValue.Fixer.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumsShouldHaveZeroValue.Fixer.cs
@@ -3,7 +3,6 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
-using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -26,7 +25,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
SemanticModel model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
- INamedTypeSymbol flagsAttributeType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemFlagsAttribute);
+ INamedTypeSymbol? flagsAttributeType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemFlagsAttribute);
if (flagsAttributeType == null)
{
return;
@@ -37,8 +36,12 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
SyntaxNode node = root.FindNode(context.Span);
- ISymbol declaredSymbol = model.GetDeclaredSymbol(node, context.CancellationToken);
- Debug.Assert(declaredSymbol != null);
+ ISymbol? declaredSymbol = model.GetDeclaredSymbol(node, context.CancellationToken);
+ if (declaredSymbol == null)
+ {
+ continue;
+ }
+
string title;
foreach (string customTag in diagnostic.Descriptor.CustomTags)
@@ -72,7 +75,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
}
}
- public override FixAllProvider GetFixAllProvider()
+ public override FixAllProvider? GetFixAllProvider()
{
// No trivial way to FixAll diagnostics for this code fix.
return null;
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumsShouldHaveZeroValue.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumsShouldHaveZeroValue.cs
index 00c81ca350..6f6a5211be 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumsShouldHaveZeroValue.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumsShouldHaveZeroValue.cs
@@ -86,7 +86,7 @@ public override void Initialize(AnalysisContext context)
context.RegisterCompilationStartAction(compilationContext =>
{
- INamedTypeSymbol flagsAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemFlagsAttribute);
+ INamedTypeSymbol? flagsAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemFlagsAttribute);
if (flagsAttribute == null)
{
return;
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EquatableAnalyzer.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EquatableAnalyzer.Fixer.cs
index 30341ff9e4..141eb89d63 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EquatableAnalyzer.Fixer.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EquatableAnalyzer.Fixer.cs
@@ -47,7 +47,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
return;
}
- INamedTypeSymbol equatableType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIEquatable1);
+ INamedTypeSymbol? equatableType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIEquatable1);
if (equatableType == null)
{
return;
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EquatableAnalyzer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EquatableAnalyzer.cs
index 535ad99404..5f9214f206 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EquatableAnalyzer.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EquatableAnalyzer.cs
@@ -55,8 +55,8 @@ public override void Initialize(AnalysisContext context)
private static void OnCompilationStart(CompilationStartAnalysisContext context)
{
- INamedTypeSymbol objectType = context.Compilation.GetSpecialType(SpecialType.System_Object);
- INamedTypeSymbol equatableType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIEquatable1);
+ INamedTypeSymbol? objectType = context.Compilation.GetSpecialType(SpecialType.System_Object);
+ INamedTypeSymbol? equatableType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIEquatable1);
if (objectType != null && equatableType != null)
{
context.RegisterSymbolAction(c => AnalyzeSymbol(c, equatableType), SymbolKind.NamedType);
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ExceptionsShouldBePublic.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ExceptionsShouldBePublic.cs
index 8d96d31fb6..2f97c74e2e 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ExceptionsShouldBePublic.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ExceptionsShouldBePublic.cs
@@ -55,7 +55,7 @@ private static void AnalyzeCompilationStart(CompilationStartAnalysisContext csCo
// Get named type symbols for targetted exception types
ImmutableHashSet exceptionTypes = s_exceptionTypeNames
.Select(name => csContext.Compilation.GetOrCreateTypeByMetadataName(name))
- .Where(t => t != null)
+ .WhereNotNull()
.ToImmutableHashSet();
if (!exceptionTypes.IsEmpty)
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/Helpers/EnumHelpers.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/Helpers/EnumHelpers.cs
index 0bfc233775..3e7e996818 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/Helpers/EnumHelpers.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/Helpers/EnumHelpers.cs
@@ -60,7 +60,6 @@ internal static bool TryConvertToUInt64(object value, SpecialType specialType, o
internal static bool TryGetEnumMemberValues(INamedTypeSymbol enumType, out IList values)
{
- Debug.Assert(enumType != null);
Debug.Assert(enumType.TypeKind == TypeKind.Enum);
values = new List();
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/IdentifiersShouldDifferByMoreThanCase.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/IdentifiersShouldDifferByMoreThanCase.cs
index 13c429825b..f20584f053 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/IdentifiersShouldDifferByMoreThanCase.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/IdentifiersShouldDifferByMoreThanCase.cs
@@ -58,7 +58,7 @@ private static void AnalyzeCompilation(CompilationAnalysisContext context)
private static void AnalyzeSymbol(SymbolAnalysisContext context)
{
- var namedTypeSymbol = context.Symbol as INamedTypeSymbol;
+ var namedTypeSymbol = (INamedTypeSymbol)context.Symbol;
// Do not descent into non-publicly visible types by default
// Note: This is the behavior of FxCop, it might be more correct to descend into internal but not private
@@ -245,7 +245,7 @@ private static void CheckTypeNames(IEnumerable types, Compilat
typesWithName.Add(type);
}
- foreach (var (name, typesWithName) in typesByName)
+ foreach (var (_, typesWithName) in typesByName)
{
if (typesWithName.Count > 1)
{
@@ -277,7 +277,7 @@ private static void CheckNamespaceNames(IEnumerable namespaces
namespacesWithName.Add(namespaceSym);
}
- foreach (var (name, namespacesWithName) in namespacesByName)
+ foreach (var (_, namespacesWithName) in namespacesByName)
{
if (namespacesWithName.Count > 1)
{
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/IdentifiersShouldHaveCorrectPrefix.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/IdentifiersShouldHaveCorrectPrefix.cs
index d1caaf3baa..43aad7c26d 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/IdentifiersShouldHaveCorrectPrefix.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/IdentifiersShouldHaveCorrectPrefix.cs
@@ -116,7 +116,7 @@ private static bool HasCorrectPrefix(ISymbol symbol, char prefix)
{
WordParser parser = new WordParser(symbol.Name, WordParserOptions.SplitCompoundWords, prefix);
- string firstWord = parser.NextWord();
+ string? firstWord = parser.NextWord();
if (firstWord == null || firstWord.Length > 1)
{
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/IdentifiersShouldNotContainUnderscores.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/IdentifiersShouldNotContainUnderscores.cs
index 700191e434..4bc0f66e79 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/IdentifiersShouldNotContainUnderscores.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/IdentifiersShouldNotContainUnderscores.cs
@@ -136,7 +136,7 @@ public override void Initialize(AnalysisContext analysisContext)
case SymbolKind.NamedType:
{
- var namedType = symbol as INamedTypeSymbol;
+ var namedType = (INamedTypeSymbol)symbol;
AnalyzeTypeParameters(symbolAnalysisContext, namedType.TypeParameters);
if (namedType.TypeKind == TypeKind.Delegate &&
@@ -156,7 +156,7 @@ public override void Initialize(AnalysisContext analysisContext)
case SymbolKind.Field:
{
- var fieldSymbol = symbol as IFieldSymbol;
+ var fieldSymbol = (IFieldSymbol)symbol;
if (ContainsUnderScore(symbol.Name) && (fieldSymbol.IsConst || (fieldSymbol.IsStatic && fieldSymbol.IsReadOnly)))
{
symbolAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(MemberRule, symbol.ToDisplayString(SymbolDisplayFormat.CSharpErrorMessageFormat)));
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ImplementIDisposableCorrectly.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ImplementIDisposableCorrectly.cs
index df7a9f6699..a4bbd46774 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ImplementIDisposableCorrectly.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ImplementIDisposableCorrectly.cs
@@ -129,7 +129,7 @@ public override void Initialize(AnalysisContext analysisContext)
analysisContext.RegisterCompilationStartAction(
context =>
{
- INamedTypeSymbol disposableType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIDisposable);
+ INamedTypeSymbol? disposableType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIDisposable);
if (disposableType == null)
{
return;
@@ -140,7 +140,7 @@ public override void Initialize(AnalysisContext analysisContext)
return;
}
- INamedTypeSymbol garbageCollectorType = context.Compilation.GetOrCreateTypeByMetadataName(GarbageCollectorTypeName);
+ INamedTypeSymbol? garbageCollectorType = context.Compilation.GetOrCreateTypeByMetadataName(GarbageCollectorTypeName);
if (garbageCollectorType == null)
{
return;
@@ -197,7 +197,7 @@ private void AnalyzeNamedTypeSymbol(SymbolAnalysisContext context)
CheckIDisposableReimplementationRule(type, context, implementsDisposableInBaseType);
}
- IMethodSymbol disposeMethod = FindDisposeMethod(type);
+ IMethodSymbol? disposeMethod = FindDisposeMethod(type);
if (disposeMethod != null)
{
CheckDisposeSignatureRule(disposeMethod, type, context);
@@ -249,7 +249,7 @@ private void AnalyzeOperationBlock(OperationBlockAnalysisContext context)
{
if (ImplementsDisposableDirectly(type))
{
- IMethodSymbol disposeMethod = FindDisposeMethod(type);
+ IMethodSymbol? disposeMethod = FindDisposeMethod(type);
if (disposeMethod != null)
{
if (method.Equals(disposeMethod))
@@ -421,7 +421,7 @@ private bool ImplementsDisposableInBaseType(ITypeSymbol type)
/// Returns method that implements IDisposable.Dispose operation.
/// Only direct implementation is taken into account, implementation in base type is ignored.
///
- private IMethodSymbol FindDisposeMethod(INamedTypeSymbol type)
+ private IMethodSymbol? FindDisposeMethod(INamedTypeSymbol type)
{
if (type.FindImplementationForInterfaceMember(_disposeInterfaceMethod) is IMethodSymbol disposeMethod && Equals(disposeMethod.ContainingType, type))
{
@@ -442,9 +442,9 @@ private static IMethodSymbol FindDisposeBoolMethod(INamedTypeSymbol type)
///
/// Returns method defined in the nearest ancestor: void Dispose(bool)
///
- private IMethodSymbol FindInheritedDisposeBoolMethod(INamedTypeSymbol type)
+ private IMethodSymbol? FindInheritedDisposeBoolMethod(INamedTypeSymbol type)
{
- IMethodSymbol method = null;
+ IMethodSymbol? method = null;
while (type != null && method == null && ImplementsDisposableInBaseType(type))
{
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ImplementStandardExceptionConstructors.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ImplementStandardExceptionConstructors.Fixer.cs
index 976144aaaf..6a9c61ec66 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ImplementStandardExceptionConstructors.Fixer.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ImplementStandardExceptionConstructors.Fixer.cs
@@ -60,7 +60,10 @@ private static async Task AddConstructorsAsync(Document document, IEnu
CodeAnalysis.Text.TextSpan diagnosticSpan = diagnostics.First().Location.SourceSpan; // All the diagnostics are reported at the same location -- the name of the declared class -- so it doesn't matter which one we pick
SyntaxNode node = root.FindNode(diagnosticSpan);
SyntaxNode targetNode = editor.Generator.GetDeclaration(node, DeclarationKind.Class);
- var typeSymbol = model.GetDeclaredSymbol(targetNode) as INamedTypeSymbol;
+ if (!(model.GetDeclaredSymbol(targetNode) is INamedTypeSymbol typeSymbol))
+ {
+ return document;
+ }
foreach (Diagnostic diagnostic in diagnostics)
{
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ImplementStandardExceptionConstructors.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ImplementStandardExceptionConstructors.cs
index fc5ac15fd8..e59eded262 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ImplementStandardExceptionConstructors.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ImplementStandardExceptionConstructors.cs
@@ -130,7 +130,7 @@ private void AnalyzeCompilationSymbol(CompilationStartAnalysisContext context)
private static void ReportDiagnostic(SymbolAnalysisContext context, INamedTypeSymbol namedTypeSymbol, MissingCtorSignature missingCtorSignature, string constructorSignature)
{
//store MissingCtorSignature enum type into dictionary, to set diagnostic property. This is needed because Diagnostic is immutable
- ImmutableDictionary.Builder builder = ImmutableDictionary.CreateBuilder();
+ ImmutableDictionary.Builder builder = ImmutableDictionary.CreateBuilder();
builder.Add("Signature", missingCtorSignature.ToString());
//create dignostic and store signature into diagnostic property for fixer
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/InterfaceMethodsShouldBeCallableByChildTypes.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/InterfaceMethodsShouldBeCallableByChildTypes.Fixer.cs
index e3ce67c49f..8c11d56c49 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/InterfaceMethodsShouldBeCallableByChildTypes.Fixer.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/InterfaceMethodsShouldBeCallableByChildTypes.Fixer.cs
@@ -50,7 +50,7 @@ public async override Task RegisterCodeFixesAsync(CodeFixContext context)
return;
}
- IMethodSymbol candidateToIncreaseVisibility = GetExistingNonVisibleAlternate(methodSymbol);
+ IMethodSymbol? candidateToIncreaseVisibility = GetExistingNonVisibleAlternate(methodSymbol);
if (candidateToIncreaseVisibility != null)
{
ISymbol symbolToChange;
@@ -99,7 +99,7 @@ public async override Task RegisterCodeFixesAsync(CodeFixContext context)
context.Diagnostics);
}
- private static IMethodSymbol GetExistingNonVisibleAlternate(IMethodSymbol methodSymbol)
+ private static IMethodSymbol? GetExistingNonVisibleAlternate(IMethodSymbol methodSymbol)
{
foreach (IMethodSymbol interfaceMethod in methodSymbol.ExplicitInterfaceImplementations)
{
@@ -120,8 +120,8 @@ private static async Task MakeProtected(Document document, ISymbol sym
{
SymbolEditor editor = SymbolEditor.Create(document);
- ISymbol getter = null;
- ISymbol setter = null;
+ ISymbol? getter = null;
+ ISymbol? setter = null;
if (symbolToChange.Kind == SymbolKind.Property)
{
var propertySymbol = (IPropertySymbol)symbolToChange;
@@ -157,7 +157,7 @@ private static async Task ChangeToPublicInterfaceImplementation(Docume
{
SymbolEditor editor = SymbolEditor.Create(document);
- IEnumerable explicitImplementations = GetExplicitImplementations(symbolToChange);
+ IEnumerable? explicitImplementations = GetExplicitImplementations(symbolToChange);
if (explicitImplementations == null)
{
return document;
@@ -178,7 +178,7 @@ private static async Task ChangeToPublicInterfaceImplementation(Docume
return editor.GetChangedDocuments().First();
}
- private static IEnumerable GetExplicitImplementations(ISymbol symbol)
+ private static IEnumerable? GetExplicitImplementations(ISymbol? symbol)
{
if (symbol == null)
{
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/MarkAssembliesWithComVisible.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/MarkAssembliesWithComVisible.cs
index 1ab262fd8e..0837fb10ea 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/MarkAssembliesWithComVisible.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/MarkAssembliesWithComVisible.cs
@@ -53,13 +53,13 @@ private static void AnalyzeCompilation(CompilationAnalysisContext context)
{
if (AssemblyHasPublicTypes(context.Compilation.Assembly))
{
- INamedTypeSymbol comVisibleAttributeSymbol = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesComVisibleAttribute);
+ INamedTypeSymbol? comVisibleAttributeSymbol = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesComVisibleAttribute);
if (comVisibleAttributeSymbol == null)
{
return;
}
- AttributeData attributeInstance = context.Compilation.Assembly.GetAttributes().FirstOrDefault(a => a.AttributeClass.Equals(comVisibleAttributeSymbol));
+ AttributeData? attributeInstance = context.Compilation.Assembly.GetAttributes().FirstOrDefault(a => a.AttributeClass.Equals(comVisibleAttributeSymbol));
if (attributeInstance != null)
{
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/MarkAttributesWithAttributeUsage.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/MarkAttributesWithAttributeUsage.cs
index 9e00f90688..7c235cb9f0 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/MarkAttributesWithAttributeUsage.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/MarkAttributesWithAttributeUsage.cs
@@ -38,8 +38,8 @@ public override void Initialize(AnalysisContext analysisContext)
analysisContext.RegisterCompilationStartAction(compilationContext =>
{
- INamedTypeSymbol attributeType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemAttribute);
- INamedTypeSymbol attributeUsageAttributeType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemAttributeUsageAttribute);
+ INamedTypeSymbol? attributeType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemAttribute);
+ INamedTypeSymbol? attributeUsageAttributeType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemAttributeUsageAttribute);
if (attributeType == null || attributeUsageAttributeType == null)
{
return;
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/NestedTypesShouldNotBeVisible.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/NestedTypesShouldNotBeVisible.cs
index c989cb0efd..0c2f97b345 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/NestedTypesShouldNotBeVisible.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/NestedTypesShouldNotBeVisible.cs
@@ -57,10 +57,10 @@ public override void Initialize(AnalysisContext analysisContext)
{
Compilation compilation = compilationStartContext.Compilation;
- INamedTypeSymbol enumeratorType = compilation.GetSpecialType(SpecialType.System_Collections_IEnumerator);
- INamedTypeSymbol dataSetType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataDataSet);
- INamedTypeSymbol dataTableType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataDataTable);
- INamedTypeSymbol dataRowType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataDataRow);
+ INamedTypeSymbol? enumeratorType = compilation.GetSpecialType(SpecialType.System_Collections_IEnumerator);
+ INamedTypeSymbol? dataSetType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataDataSet);
+ INamedTypeSymbol? dataTableType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataDataTable);
+ INamedTypeSymbol? dataRowType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataDataRow);
compilationStartContext.RegisterSymbolAction(
symbolAnalysisContext =>
@@ -128,9 +128,9 @@ public override void Initialize(AnalysisContext analysisContext)
private static bool IsDataSetSpecialCase(
INamedTypeSymbol containingType,
INamedTypeSymbol nestedType,
- INamedTypeSymbol dataSetType,
- INamedTypeSymbol dataTableType,
- INamedTypeSymbol dataRowType)
+ INamedTypeSymbol? dataSetType,
+ INamedTypeSymbol? dataTableType,
+ INamedTypeSymbol? dataRowType)
{
if (!containingType.GetBaseTypes().Contains(dataSetType))
{
@@ -138,7 +138,8 @@ public override void Initialize(AnalysisContext analysisContext)
}
var nestedTypeBases = nestedType.GetBaseTypes().ToList();
- return nestedTypeBases.Contains(dataTableType) || nestedTypeBases.Contains(dataRowType);
+ return dataTableType != null && nestedTypeBases.Contains(dataTableType) ||
+ dataRowType != null && nestedTypeBases.Contains(dataRowType);
}
}
}
\ No newline at end of file
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OperatorOverloadsHaveNamedAlternates.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OperatorOverloadsHaveNamedAlternates.Fixer.cs
index 709f3244bb..93f0fe3add 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OperatorOverloadsHaveNamedAlternates.Fixer.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OperatorOverloadsHaveNamedAlternates.Fixer.cs
@@ -30,18 +30,23 @@ public override FixAllProvider GetFixAllProvider()
public override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
- SemanticModel semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
- SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
- SyntaxGenerator generator = context.Document.Project?.LanguageServices?.GetService();
- if (semanticModel != null && generator != null)
+ var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
+ SyntaxNode node = root.FindNode(context.Span);
+ if (node == null)
{
- string title = MicrosoftCodeQualityAnalyzersResources.OperatorOverloadsHaveNamedAlternatesTitle;
- context.RegisterCodeFix(new MyCodeAction(title, ct => Fix(context, root, generator, semanticModel, ct), equivalenceKey: title), context.Diagnostics.First());
+ return;
}
+
+ string title = MicrosoftCodeQualityAnalyzersResources.OperatorOverloadsHaveNamedAlternatesTitle;
+ context.RegisterCodeFix(new MyCodeAction(title, ct => Fix(context, ct), equivalenceKey: title), context.Diagnostics.First());
}
- private static async Task Fix(CodeFixContext context, SyntaxNode root, SyntaxGenerator generator, SemanticModel semanticModel, CancellationToken cancellationToken)
+ private static async Task Fix(CodeFixContext context, CancellationToken cancellationToken)
{
+ var semanticModel = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
+ var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
+ var generator = SyntaxGenerator.GetGenerator(context.Document);
+
SyntaxNode node = root.FindNode(context.Span);
Diagnostic diagnostic = context.Diagnostics.First();
switch (diagnostic.Properties[OperatorOverloadsHaveNamedAlternatesAnalyzer.DiagnosticKindText])
@@ -72,7 +77,11 @@ private static async Task Fix(CodeFixContext context, SyntaxNode root,
else
{
// add a method
- ExpectedMethodSignature expectedSignature = GetExpectedMethodSignature(operatorOverloadSymbol, semanticModel.Compilation);
+ ExpectedMethodSignature? expectedSignature = GetExpectedMethodSignature(operatorOverloadSymbol, semanticModel.Compilation);
+ if (expectedSignature == null)
+ {
+ return context.Document;
+ }
if (expectedSignature.Name == "CompareTo" && operatorOverloadSymbol.ContainingType.TypeKind == TypeKind.Class)
{
@@ -114,12 +123,17 @@ private static async Task Fix(CodeFixContext context, SyntaxNode root,
}
}
- private static ExpectedMethodSignature GetExpectedMethodSignature(IMethodSymbol operatorOverloadSymbol, Compilation compilation)
+ private static ExpectedMethodSignature? GetExpectedMethodSignature(IMethodSymbol operatorOverloadSymbol, Compilation compilation)
{
var containingType = (ITypeSymbol)operatorOverloadSymbol.ContainingType;
ITypeSymbol returnType = operatorOverloadSymbol.ReturnType;
- ITypeSymbol parameterType = operatorOverloadSymbol.Parameters.FirstOrDefault()?.Type;
- string expectedName = OperatorOverloadsHaveNamedAlternatesAnalyzer.GetExpectedAlternateMethodGroup(operatorOverloadSymbol.Name, returnType, parameterType).AlternateMethod1;
+ ITypeSymbol? parameterType = operatorOverloadSymbol.Parameters.FirstOrDefault()?.Type;
+ string? expectedName = OperatorOverloadsHaveNamedAlternatesAnalyzer.GetExpectedAlternateMethodGroup(operatorOverloadSymbol.Name, returnType, parameterType)?.AlternateMethod1;
+ if (expectedName == null)
+ {
+ return null;
+ }
+
switch (operatorOverloadSymbol.Name)
{
case "op_GreaterThan":
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OperatorOverloadsHaveNamedAlternates.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OperatorOverloadsHaveNamedAlternates.cs
index ab4f6b8bb6..85bb852646 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OperatorOverloadsHaveNamedAlternates.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OperatorOverloadsHaveNamedAlternates.cs
@@ -112,7 +112,7 @@ private static void AnalyzeSymbol(SymbolAnalysisContext symbolContext)
}
else
{
- ExpectedAlternateMethodGroup expectedGroup = GetExpectedAlternateMethodGroup(operatorName, methodSymbol.ReturnType, methodSymbol.Parameters.FirstOrDefault()?.Type);
+ ExpectedAlternateMethodGroup? expectedGroup = GetExpectedAlternateMethodGroup(operatorName, methodSymbol.ReturnType, methodSymbol.Parameters.FirstOrDefault()?.Type);
if (expectedGroup == null)
{
// no alternate methods required
@@ -191,7 +191,7 @@ internal static bool IsPropertyExpected(string operatorName)
}
}
- internal static ExpectedAlternateMethodGroup GetExpectedAlternateMethodGroup(string operatorName, ITypeSymbol returnType, ITypeSymbol parameterType)
+ internal static ExpectedAlternateMethodGroup? GetExpectedAlternateMethodGroup(string operatorName, ITypeSymbol returnType, ITypeSymbol? parameterType)
{
// list of operator alternate names: https://docs.microsoft.com/visualstudio/code-quality/ca2225-operator-overloads-have-named-alternates
@@ -267,9 +267,9 @@ internal static ExpectedAlternateMethodGroup GetExpectedAlternateMethodGroup(str
internal class ExpectedAlternateMethodGroup
{
public string AlternateMethod1 { get; }
- public string AlternateMethod2 { get; }
+ public string? AlternateMethod2 { get; }
- public ExpectedAlternateMethodGroup(string alternateMethod1, string alternateMethod2 = null)
+ public ExpectedAlternateMethodGroup(string alternateMethod1, string? alternateMethod2 = null)
{
AlternateMethod1 = alternateMethod1;
AlternateMethod2 = alternateMethod2;
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideMethodsOnComparableTypes.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideMethodsOnComparableTypes.cs
index 2a1c80aca0..df638853a6 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideMethodsOnComparableTypes.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideMethodsOnComparableTypes.cs
@@ -66,8 +66,8 @@ public override void Initialize(AnalysisContext analysisContext)
analysisContext.RegisterCompilationStartAction(compilationContext =>
{
- INamedTypeSymbol comparableType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIComparable);
- INamedTypeSymbol genericComparableType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIComparable1);
+ INamedTypeSymbol? comparableType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIComparable);
+ INamedTypeSymbol? genericComparableType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIComparable1);
// Even if one of them is available, we should continue analysis.
if (comparableType == null && genericComparableType == null)
@@ -83,7 +83,7 @@ public override void Initialize(AnalysisContext analysisContext)
});
}
- private static void AnalyzeSymbol(SymbolAnalysisContext context, INamedTypeSymbol comparableType, INamedTypeSymbol genericComparableType)
+ private static void AnalyzeSymbol(SymbolAnalysisContext context, INamedTypeSymbol? comparableType, INamedTypeSymbol? genericComparableType)
{
// Note all the descriptors/rules for this analyzer have the same ID and category and hence
// will always have identical configured visibility.
@@ -115,7 +115,7 @@ private static void AnalyzeSymbol(SymbolAnalysisContext context, INamedTypeSymbo
}
}
- private static bool IsComparableWithBaseNotComparable(INamedTypeSymbol namedTypeSymbol, INamedTypeSymbol comparableType, INamedTypeSymbol genericComparableType)
+ private static bool IsComparableWithBaseNotComparable(INamedTypeSymbol namedTypeSymbol, INamedTypeSymbol? comparableType, INamedTypeSymbol? genericComparableType)
{
if (!IsComparableCore(namedTypeSymbol, comparableType, genericComparableType))
{
@@ -133,20 +133,18 @@ private static bool IsComparableWithBaseNotComparable(INamedTypeSymbol namedType
return true;
}
- private static bool IsComparableCore(INamedTypeSymbol namedTypeSymbol, INamedTypeSymbol comparableType, INamedTypeSymbol genericComparableType)
+ private static bool IsComparableCore(INamedTypeSymbol namedTypeSymbol, INamedTypeSymbol? comparableType, INamedTypeSymbol? genericComparableType)
=> namedTypeSymbol.AllInterfaces.Any(t => t.Equals(comparableType) ||
(t.ConstructedFrom?.Equals(genericComparableType) ?? false));
private static string GetNeededComparisonOperators(INamedTypeSymbol symbol)
{
- bool first = true;
- StringBuilder sb = null;
+ StringBuilder? sb = null;
void Append(string @operator)
{
- if (first)
+ if (sb == null)
{
sb = new StringBuilder();
- first = false;
}
else
{
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ParameterNamesShouldMatchBaseDeclaration.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ParameterNamesShouldMatchBaseDeclaration.cs
index 21fe69c1e6..3bc8da78ad 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ParameterNamesShouldMatchBaseDeclaration.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ParameterNamesShouldMatchBaseDeclaration.cs
@@ -71,7 +71,7 @@ private static void AnalyzeMethodSymbol(SymbolAnalysisContext analysisContext)
return;
}
- IMethodSymbol bestMatch = null;
+ IMethodSymbol? bestMatch = null;
int bestMatchScore = -1;
foreach (var originalDefinition in originalDefinitions)
@@ -108,6 +108,11 @@ private static void AnalyzeMethodSymbol(SymbolAnalysisContext analysisContext)
}
}
+ if (bestMatch == null)
+ {
+ return;
+ }
+
for (int i = 0; i < methodSymbol.Parameters.Length; i++)
{
IParameterSymbol currentParameter = methodSymbol.Parameters[i];
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/PassSystemUriObjectsInsteadOfStrings.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/PassSystemUriObjectsInsteadOfStrings.cs
index a3e482bfa4..0695d15d1f 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/PassSystemUriObjectsInsteadOfStrings.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/PassSystemUriObjectsInsteadOfStrings.cs
@@ -46,8 +46,8 @@ public override void Initialize(AnalysisContext analysisContext)
analysisContext.RegisterCompilationStartAction(c =>
{
- INamedTypeSymbol @string = c.Compilation.GetSpecialType(SpecialType.System_String);
- INamedTypeSymbol uri = c.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemUri);
+ INamedTypeSymbol? @string = c.Compilation.GetSpecialType(SpecialType.System_String);
+ INamedTypeSymbol? uri = c.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemUri);
if (@string == null || uri == null)
{
// we don't have required types
@@ -59,7 +59,7 @@ public override void Initialize(AnalysisContext analysisContext)
});
}
- protected abstract SyntaxNode GetInvocationExpression(SyntaxNode invocationNode);
+ protected abstract SyntaxNode? GetInvocationExpression(SyntaxNode invocationNode);
private sealed class PerCompilationAnalyzer
{
@@ -67,13 +67,13 @@ private sealed class PerCompilationAnalyzer
private readonly Compilation _compilation;
private readonly INamedTypeSymbol _string;
private readonly INamedTypeSymbol _uri;
- private readonly Func _expressionGetter;
+ private readonly Func _expressionGetter;
public PerCompilationAnalyzer(
Compilation compilation,
INamedTypeSymbol @string,
INamedTypeSymbol uri,
- Func expressionGetter)
+ Func expressionGetter)
{
_compilation = compilation;
_string = @string;
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/PropertyNamesShouldNotMatchGetMethods.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/PropertyNamesShouldNotMatchGetMethods.cs
index 006bfd0f28..97e43edc2c 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/PropertyNamesShouldNotMatchGetMethods.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/PropertyNamesShouldNotMatchGetMethods.cs
@@ -76,7 +76,7 @@ private static void AnalyzeSymbol(SymbolAnalysisContext context)
// Iterate through all declared types, including base
foreach (INamedTypeSymbol type in symbol.ContainingType.GetBaseTypesAndThis())
{
- Diagnostic diagnostic = null;
+ Diagnostic? diagnostic = null;
var exposedMembers = type.GetMembers(identifier).Where(member => configuredVisibilities.Contains(member.GetResultantVisibility()));
foreach (var member in exposedMembers)
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ProvideObsoleteAttributeMessage.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ProvideObsoleteAttributeMessage.cs
index 41beae89c7..7e4b8c7acc 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ProvideObsoleteAttributeMessage.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ProvideObsoleteAttributeMessage.cs
@@ -41,7 +41,7 @@ public override void Initialize(AnalysisContext analysisContext)
analysisContext.RegisterCompilationStartAction(compilationContext =>
{
- INamedTypeSymbol obsoleteAttributeType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemObsoleteAttribute);
+ INamedTypeSymbol? obsoleteAttributeType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemObsoleteAttribute);
if (obsoleteAttributeType == null)
{
return;
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/TypeNamesShouldNotMatchNamespaces.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/TypeNamesShouldNotMatchNamespaces.cs
index 708286be0b..6ea1b9e822 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/TypeNamesShouldNotMatchNamespaces.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/TypeNamesShouldNotMatchNamespaces.cs
@@ -47,7 +47,17 @@ public sealed class TypeNamesShouldNotMatchNamespacesAnalyzer : DiagnosticAnalyz
public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(DefaultRule, SystemRule);
private static readonly object s_lock = new object();
- private static ImmutableDictionary s_wellKnownSystemNamespaceTable;
+ private static ImmutableDictionary? s_wellKnownSystemNamespaceTable;
+
+ private static ImmutableDictionary WellKnownSystemNamespaceTable
+ {
+ get
+ {
+ InitializeWellKnownSystemNamespaceTable();
+ RoslynDebug.Assert(s_wellKnownSystemNamespaceTable != null);
+ return s_wellKnownSystemNamespaceTable;
+ }
+ }
public override void Initialize(AnalysisContext analysisContext)
{
@@ -91,13 +101,12 @@ public override void Initialize(AnalysisContext analysisContext)
var namespaceComponentToNamespaceNameDictionary = new Dictionary(StringComparer.OrdinalIgnoreCase);
UpdateNamespaceTable(namespaceComponentToNamespaceNameDictionary, namespaceNamesInCompilation.ToImmutableSortedSet());
- InitializeWellKnownSystemNamespaceTable();
foreach (INamedTypeSymbol symbol in externallyVisibleNamedTypes)
{
string symbolName = symbol.Name;
- if (s_wellKnownSystemNamespaceTable.ContainsKey(symbolName))
+ if (WellKnownSystemNamespaceTable.ContainsKey(symbolName))
{
- compilationAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(SystemRule, symbolName, s_wellKnownSystemNamespaceTable[symbolName]));
+ compilationAnalysisContext.ReportDiagnostic(symbol.CreateDiagnostic(SystemRule, symbolName, WellKnownSystemNamespaceTable[symbolName]));
}
else if (namespaceComponentToNamespaceNameDictionary.ContainsKey(symbolName))
{
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/TypesThatOwnDisposableFieldsShouldBeDisposable.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/TypesThatOwnDisposableFieldsShouldBeDisposable.Fixer.cs
index 21ad3fd8e6..3a6d039a6f 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/TypesThatOwnDisposableFieldsShouldBeDisposable.Fixer.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/TypesThatOwnDisposableFieldsShouldBeDisposable.Fixer.cs
@@ -54,7 +54,7 @@ private static async Task ImplementIDisposable(Document document, Synt
// Find a Dispose method. If one exists make that implement IDisposable, else generate a new method.
var typeSymbol = model.GetDeclaredSymbol(declaration) as INamedTypeSymbol;
- IMethodSymbol disposeMethod = (typeSymbol?.GetMembers("Dispose"))?.OfType()?.Where(m => m.Parameters.Length == 0).FirstOrDefault();
+ IMethodSymbol? disposeMethod = (typeSymbol?.GetMembers("Dispose"))?.OfType()?.Where(m => m.Parameters.Length == 0).FirstOrDefault();
if (disposeMethod != null && disposeMethod.DeclaringSyntaxReferences.Length == 1)
{
SyntaxNode memberPartNode = await disposeMethod.DeclaringSyntaxReferences.Single().GetSyntaxAsync(cancellationToken).ConfigureAwait(false);
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/UriParametersShouldNotBeStrings.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/UriParametersShouldNotBeStrings.Fixer.cs
index 017d2374e2..fd6ca24428 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/UriParametersShouldNotBeStrings.Fixer.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/UriParametersShouldNotBeStrings.Fixer.cs
@@ -39,7 +39,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
SemanticModel model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- INamedTypeSymbol uriType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemUri);
+ INamedTypeSymbol? uriType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemUri);
if (uriType == null)
{
return;
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/UseEventsWhereAppropriate.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/UseEventsWhereAppropriate.cs
index 87b652fa4d..7a049a9552 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/UseEventsWhereAppropriate.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/UseEventsWhereAppropriate.cs
@@ -88,7 +88,7 @@ private static bool HasEventLikeName(IMethodSymbol method)
{
WordParser parser = new WordParser(method.Name, WordParserOptions.SplitCompoundWords);
- string word = parser.NextWord();
+ string? word = parser.NextWord();
// Check for 'FireXXX', 'RaiseXXX'
if (string.Equals(word, "fire", StringComparison.OrdinalIgnoreCase) ||
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/UseGenericEventHandlerInstances.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/UseGenericEventHandlerInstances.cs
index b59920cdcc..1eda911968 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/UseGenericEventHandlerInstances.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/UseGenericEventHandlerInstances.cs
@@ -2,7 +2,7 @@
using System;
using System.Collections.Immutable;
-using System.Diagnostics;
+using System.Diagnostics.CodeAnalysis;
using System.Linq;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
@@ -67,7 +67,10 @@ public abstract class UseGenericEventHandlerInstancesAnalyzer : DiagnosticAnalyz
customTags: FxCopWellKnownDiagnosticTags.PortedFxCopRule);
public override ImmutableArray SupportedDiagnostics => ImmutableArray.Create(RuleForDelegates, RuleForEvents, RuleForEvents2);
- protected abstract bool IsAssignableTo(Compilation compilation, ITypeSymbol fromSymbol, ITypeSymbol toSymbol);
+ protected abstract bool IsAssignableTo(
+ [NotNullWhen(returnValue: true)] ITypeSymbol? fromSymbol,
+ [NotNullWhen(returnValue: true)] ITypeSymbol? toSymbol,
+ Compilation compilation);
public override void Initialize(AnalysisContext analysisContext)
{
@@ -77,7 +80,7 @@ public override void Initialize(AnalysisContext analysisContext)
analysisContext.RegisterCompilationStartAction(
(context) =>
{
- INamedTypeSymbol eventArgs = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemEventArgs);
+ INamedTypeSymbol? eventArgs = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemEventArgs);
if (eventArgs == null)
{
return;
@@ -95,7 +98,7 @@ public override void Initialize(AnalysisContext analysisContext)
bool IsEventArgsParameter(IParameterSymbol parameter)
{
var type = parameter.Type;
- if (IsAssignableTo(context.Compilation, type, eventArgs))
+ if (IsAssignableTo(type, eventArgs, context.Compilation))
{
return true;
}
@@ -111,8 +114,6 @@ bool IsEventArgsParameter(IParameterSymbol parameter)
bool IsValidNonGenericEventHandler(IMethodSymbol delegateInvokeMethod)
{
- Debug.Assert(delegateInvokeMethod != null);
-
return delegateInvokeMethod.ReturnsVoid &&
delegateInvokeMethod.Parameters.Length == 2 &&
delegateInvokeMethod.Parameters[0].Type.SpecialType == SpecialType.System_Object &&
@@ -133,7 +134,7 @@ bool IsValidNonGenericEventHandler(IMethodSymbol delegateInvokeMethod)
}
}, SymbolKind.NamedType);
- INamedTypeSymbol comSourceInterfacesAttribute = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesComSourceInterfacesAttribute);
+ INamedTypeSymbol? comSourceInterfacesAttribute = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesComSourceInterfacesAttribute);
bool ContainingTypeHasComSourceInterfacesAttribute(IEventSymbol eventSymbol) =>
comSourceInterfacesAttribute != null &&
eventSymbol.ContainingType.GetAttributes().Any(a => Equals(a.AttributeClass, comSourceInterfacesAttribute));
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/AvoidDeadConditionalCode.cs b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/AvoidDeadConditionalCode.cs
index b2480fbe24..caf9bcb21e 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/AvoidDeadConditionalCode.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/AvoidDeadConditionalCode.cs
@@ -88,13 +88,12 @@ public override void Initialize(AnalysisContext context)
var valueContentAnalysisResult = ValueContentAnalysis.TryGetOrComputeResult(cfg, owningSymbol, wellKnownTypeProvider,
operationBlockContext.Options, AlwaysTrueFalseOrNullRule, operationBlockContext.CancellationToken,
out var copyAnalysisResultOpt, out var pointsToAnalysisResult);
- if (valueContentAnalysisResult == null)
+ if (valueContentAnalysisResult == null ||
+ pointsToAnalysisResult == null)
{
continue;
}
- Debug.Assert(pointsToAnalysisResult != null);
-
foreach (var operation in cfg.DescendantOperations())
{
// Skip implicit operations.
@@ -168,6 +167,8 @@ PredicateValueKind GetPredicateKind(IOperation operation)
operation.Kind == OperationKind.Invocation ||
operation.Kind == OperationKind.IsNull ||
operation.Kind == OperationKind.IsPattern);
+ RoslynDebug.Assert(pointsToAnalysisResult != null);
+ RoslynDebug.Assert(valueContentAnalysisResult != null);
if (operation is IBinaryOperation binaryOperation &&
binaryOperation.IsComparisonOperator() ||
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/AvoidUninstantiatedInternalClasses.cs b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/AvoidUninstantiatedInternalClasses.cs
index c597860b7d..43acb5832b 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/AvoidUninstantiatedInternalClasses.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/AvoidUninstantiatedInternalClasses.cs
@@ -44,8 +44,8 @@ public override void Initialize(AnalysisContext analysisContext)
analysisContext.RegisterCompilationStartAction(startContext =>
{
- var instantiatedTypes = new ConcurrentDictionary();
- var internalTypes = new ConcurrentDictionary();
+ var instantiatedTypes = new ConcurrentDictionary();
+ var internalTypes = new ConcurrentDictionary();
var compilation = startContext.Compilation;
@@ -58,7 +58,7 @@ public override void Initialize(AnalysisContext analysisContext)
// instantiated by any friend assembly, but we didn't report the issue) than
// to have false positives.
var internalsVisibleToAttributeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeCompilerServicesInternalsVisibleToAttribute);
- if (AssemblyExposesInternals(compilation, internalsVisibleToAttributeSymbol))
+ if (compilation.Assembly.HasAttribute(internalsVisibleToAttributeSymbol))
{
return;
}
@@ -200,16 +200,6 @@ static IEnumerable GetAllNamedTypeConstraints(ITypeParameterSy
});
}
- private static bool AssemblyExposesInternals(
- Compilation compilation,
- INamedTypeSymbol internalsVisibleToAttributeSymbol)
- {
- ISymbol assemblySymbol = compilation.Assembly;
- var attributes = assemblySymbol.GetAttributes();
- return attributes.Any(
- attr => attr.AttributeClass.Equals(internalsVisibleToAttributeSymbol));
- }
-
private bool HasInstantiatedNestedType(INamedTypeSymbol type, IEnumerable instantiatedTypes)
{
// We don't care whether a private nested type is instantiated, because if it
@@ -235,13 +225,13 @@ private bool HasInstantiatedNestedType(INamedTypeSymbol type, IEnumerable IsEntryPoint(m, taskSymbol, genericTaskSymbol));
}
- private static bool IsEntryPoint(IMethodSymbol method, ITypeSymbol taskSymbol, ITypeSymbol genericTaskSymbol)
+ private static bool IsEntryPoint(IMethodSymbol method, ITypeSymbol? taskSymbol, ITypeSymbol? genericTaskSymbol)
{
if (!method.IsStatic)
{
@@ -355,7 +345,7 @@ private static bool IsEntryPoint(IMethodSymbol method, ITypeSymbol taskSymbol, I
return true;
}
- private static bool IsSupportedReturnType(IMethodSymbol method, ITypeSymbol taskSymbol, ITypeSymbol genericTaskSymbol)
+ private static bool IsSupportedReturnType(IMethodSymbol method, ITypeSymbol? taskSymbol, ITypeSymbol? genericTaskSymbol)
{
if (method.ReturnType.SpecialType == SpecialType.System_Int32)
{
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/CodeMetricsAnalyzer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/CodeMetricsAnalyzer.cs
index 5021534be0..724bd6cd45 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/CodeMetricsAnalyzer.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/CodeMetricsAnalyzer.cs
@@ -3,6 +3,7 @@
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
+using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Threading;
@@ -128,9 +129,9 @@ public override void Initialize(AnalysisContext analysisContext)
if (!TryGetRuleIdToThresholdMap(
compilationContext.Options.AdditionalFiles,
compilationContext.CancellationToken,
- out AdditionalText additionalTextOpt,
- out ImmutableDictionary> ruleIdToThresholdMap,
- out List invalidFileDiagnostics) &&
+ out AdditionalText? additionalTextOpt,
+ out ImmutableDictionary>? ruleIdToThresholdMap,
+ out List? invalidFileDiagnostics) &&
invalidFileDiagnostics != null)
{
// Report any invalid additional file diagnostics.
@@ -307,9 +308,9 @@ static bool isApplicableByDefault(string ruleId, SymbolKind symbolKind)
private static bool TryGetRuleIdToThresholdMap(
ImmutableArray additionalFiles,
CancellationToken cancellationToken,
- out AdditionalText additionalText,
- out ImmutableDictionary> ruleIdToThresholdMap,
- out List invalidFileDiagnostics)
+ [NotNullWhen(returnValue: true)] out AdditionalText? additionalText,
+ [NotNullWhen(returnValue: true)] out ImmutableDictionary>? ruleIdToThresholdMap,
+ out List? invalidFileDiagnostics)
{
invalidFileDiagnostics = null;
ruleIdToThresholdMap = null;
@@ -321,7 +322,7 @@ static bool isApplicableByDefault(string ruleId, SymbolKind symbolKind)
TryParseCodeMetricsConfigurationFile(additionalText, cancellationToken, out ruleIdToThresholdMap, out invalidFileDiagnostics);
}
- private static AdditionalText TryGetCodeMetricsConfigurationFile(ImmutableArray additionalFiles, CancellationToken cancellationToken)
+ private static AdditionalText? TryGetCodeMetricsConfigurationFile(ImmutableArray additionalFiles, CancellationToken cancellationToken)
{
StringComparer comparer = StringComparer.Ordinal;
foreach (AdditionalText textFile in additionalFiles)
@@ -341,8 +342,8 @@ private static AdditionalText TryGetCodeMetricsConfigurationFile(ImmutableArray<
private static bool TryParseCodeMetricsConfigurationFile(
AdditionalText additionalText,
CancellationToken cancellationToken,
- out ImmutableDictionary> ruleIdToThresholdMap,
- out List invalidFileDiagnostics)
+ [NotNullWhen(returnValue: true)] out ImmutableDictionary>? ruleIdToThresholdMap,
+ out List? invalidFileDiagnostics)
{
// Parse the additional file with Metric rule ID (which may contain an optional parenthesized SymbolKind suffix) and custom threshold.
// # FORMAT:
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/DoNotIgnoreMethodResults.cs b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/DoNotIgnoreMethodResults.cs
index 4251d7a205..8bdbb49e1a 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/DoNotIgnoreMethodResults.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/DoNotIgnoreMethodResults.cs
@@ -130,9 +130,9 @@ public override void Initialize(AnalysisContext analysisContext)
analysisContext.RegisterCompilationStartAction(compilationContext =>
{
- INamedTypeSymbol expectedExceptionType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingExpectedExceptionAttribute);
- INamedTypeSymbol nunitAssertType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.NUnitFrameworkAssert);
- INamedTypeSymbol xunitAssertType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.XunitAssert);
+ INamedTypeSymbol? expectedExceptionType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingExpectedExceptionAttribute);
+ INamedTypeSymbol? nunitAssertType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.NUnitFrameworkAssert);
+ INamedTypeSymbol? xunitAssertType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.XunitAssert);
compilationContext.RegisterOperationBlockStartAction(osContext =>
{
@@ -144,8 +144,8 @@ public override void Initialize(AnalysisContext analysisContext)
osContext.RegisterOperationAction(opContext =>
{
IOperation expression = ((IExpressionStatementOperation)opContext.Operation).Operation;
- DiagnosticDescriptor rule = null;
- string targetMethodName = null;
+ DiagnosticDescriptor? rule = null;
+ string? targetMethodName = null;
switch (expression.Kind)
{
case OperationKind.ObjectCreation:
@@ -201,9 +201,9 @@ public override void Initialize(AnalysisContext analysisContext)
});
}
- private static bool ShouldSkipAnalyzing(OperationAnalysisContext operationContext, INamedTypeSymbol expectedExceptionType, INamedTypeSymbol xunitAssertType, INamedTypeSymbol nunitAssertType)
+ private static bool ShouldSkipAnalyzing(OperationAnalysisContext operationContext, INamedTypeSymbol? expectedExceptionType, INamedTypeSymbol? xunitAssertType, INamedTypeSymbol? nunitAssertType)
{
- static bool IsThrowsArgument(IParameterSymbol parameterSymbol, string argumentName, ImmutableHashSet methodNames, INamedTypeSymbol assertSymbol)
+ static bool IsThrowsArgument(IParameterSymbol parameterSymbol, string argumentName, ImmutableHashSet methodNames, INamedTypeSymbol? assertSymbol)
{
return parameterSymbol.Name == argumentName &&
parameterSymbol.ContainingSymbol is IMethodSymbol methodSymbol &&
@@ -284,7 +284,7 @@ bool IsXunitThrowsArgument(IParameterSymbol parameterSymbol)
}
else
{
- IArgumentOperation argumentOperation = enclosingBlock.GetAncestor(OperationKind.Argument);
+ IArgumentOperation? argumentOperation = enclosingBlock.GetAncestor(OperationKind.Argument);
if (argumentOperation == null)
{
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/ReviewUnusedParameters.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/ReviewUnusedParameters.Fixer.cs
index 8b68d0d082..c65fa734dc 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/ReviewUnusedParameters.Fixer.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/ReviewUnusedParameters.Fixer.cs
@@ -169,9 +169,9 @@ private static bool IsSafeMethodToRemoveParameter(ISymbol methodDeclarationSymbo
case SymbolKind.Property:
return false;
case SymbolKind.Method:
- var methodSymbol = methodDeclarationSymbol as IMethodSymbol;
+ var methodSymbol = (IMethodSymbol)methodDeclarationSymbol;
// Should not remove parameter for a conversion operator.
- return (methodSymbol.MethodKind != MethodKind.Conversion);
+ return methodSymbol.MethodKind != MethodKind.Conversion;
default:
return true;
}
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/ReviewUnusedParameters.cs b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/ReviewUnusedParameters.cs
index ec9816f7f8..ba955047ac 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/ReviewUnusedParameters.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/ReviewUnusedParameters.cs
@@ -50,19 +50,19 @@ public override void Initialize(AnalysisContext context)
context.RegisterCompilationStartAction(compilationStartContext =>
{
- INamedTypeSymbol eventsArgSymbol = compilationStartContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemEventArgs);
+ INamedTypeSymbol? eventsArgSymbol = compilationStartContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemEventArgs);
// Ignore conditional methods (FxCop compat - One conditional will often call another conditional method as its only use of a parameter)
- INamedTypeSymbol conditionalAttributeSymbol = compilationStartContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDiagnosticsConditionalAttribute);
+ INamedTypeSymbol? conditionalAttributeSymbol = compilationStartContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDiagnosticsConditionalAttribute);
// Ignore methods with special serialization attributes (FxCop compat - All serialization methods need to take 'StreamingContext')
- INamedTypeSymbol onDeserializingAttribute = compilationStartContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationOnDeserializingAttribute);
- INamedTypeSymbol onDeserializedAttribute = compilationStartContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationOnDeserializedAttribute);
- INamedTypeSymbol onSerializingAttribute = compilationStartContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationOnSerializingAttribute);
- INamedTypeSymbol onSerializedAttribute = compilationStartContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationOnSerializedAttribute);
- INamedTypeSymbol obsoleteAttribute = compilationStartContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemObsoleteAttribute);
+ INamedTypeSymbol? onDeserializingAttribute = compilationStartContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationOnDeserializingAttribute);
+ INamedTypeSymbol? onDeserializedAttribute = compilationStartContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationOnDeserializedAttribute);
+ INamedTypeSymbol? onSerializingAttribute = compilationStartContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationOnSerializingAttribute);
+ INamedTypeSymbol? onSerializedAttribute = compilationStartContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationOnSerializedAttribute);
+ INamedTypeSymbol? obsoleteAttribute = compilationStartContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemObsoleteAttribute);
- ImmutableHashSet attributeSetForMethodsToIgnore = ImmutableHashSet.Create(
+ ImmutableHashSet attributeSetForMethodsToIgnore = ImmutableHashSet.Create(
conditionalAttributeSymbol,
onDeserializedAttribute,
onDeserializingAttribute,
@@ -118,9 +118,9 @@ public override void Initialize(AnalysisContext context)
IMethodSymbol method,
OperationBlockStartAnalysisContext startOperationBlockContext,
UnusedParameterDictionary unusedMethodParameters,
- INamedTypeSymbol eventsArgSymbol,
+ INamedTypeSymbol? eventsArgSymbol,
ISet methodsUsedAsDelegates,
- ImmutableHashSet attributeSetForMethodsToIgnore)
+ ImmutableHashSet attributeSetForMethodsToIgnore)
{
// We only care about methods with parameters.
if (method.Parameters.IsEmpty)
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/UseNameofInPlaceOfString.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/UseNameofInPlaceOfString.Fixer.cs
index b57124e88b..40f5281d68 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/UseNameofInPlaceOfString.Fixer.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/UseNameofInPlaceOfString.Fixer.cs
@@ -1,7 +1,6 @@
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
-using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
@@ -32,10 +31,14 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
var root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
var diagnostics = context.Diagnostics;
var diagnosticSpan = context.Span;
+
// getInnerModeNodeForTie = true so we are replacing the string literal node and not the whole argument node
var nodeToReplace = root.FindNode(diagnosticSpan, getInnermostNodeForTie: true);
+ if (nodeToReplace == null)
+ {
+ return;
+ }
- Debug.Assert(nodeToReplace != null);
var stringText = nodeToReplace.FindToken(diagnosticSpan.Start).ValueText;
context.RegisterCodeFix(CodeAction.Create(
MicrosoftCodeQualityAnalyzersResources.UseNameOfInPlaceOfStringTitle,
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/AbstractRemoveEmptyFinalizers.cs b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/AbstractRemoveEmptyFinalizers.cs
index d5a6d8f206..d26f1e48eb 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/AbstractRemoveEmptyFinalizers.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/AbstractRemoveEmptyFinalizers.cs
@@ -55,8 +55,8 @@ public override void Initialize(AnalysisContext analysisContext)
});
}
- protected static bool InvocationIsConditional(IMethodSymbol methodSymbol, INamedTypeSymbol conditionalAttributeSymbol) =>
- methodSymbol.GetAttributes().Any(n => n.AttributeClass.Equals(conditionalAttributeSymbol));
+ protected static bool InvocationIsConditional(IMethodSymbol methodSymbol, INamedTypeSymbol? conditionalAttributeSymbol) =>
+ methodSymbol.HasAttribute(conditionalAttributeSymbol);
protected abstract bool IsEmptyFinalizer(SyntaxNode methodBody, CodeBlockAnalysisContext analysisContext);
}
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/DoNotCallOverridableMethodsInConstructors.cs b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/DoNotCallOverridableMethodsInConstructors.cs
index 851e36751c..0a3adc3d81 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/DoNotCallOverridableMethodsInConstructors.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/DoNotCallOverridableMethodsInConstructors.cs
@@ -44,8 +44,8 @@ public override void Initialize(AnalysisContext analysisContext)
analysisContext.RegisterCompilationStartAction(compilationContext =>
{
- INamedTypeSymbol webUiControlType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemWebUIControl);
- INamedTypeSymbol componentModelComponentType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemComponentModelComponent);
+ INamedTypeSymbol? webUiControlType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemWebUIControl);
+ INamedTypeSymbol? componentModelComponentType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemComponentModelComponent);
compilationContext.RegisterOperationBlockStartAction(context =>
{
@@ -61,7 +61,7 @@ public override void Initialize(AnalysisContext analysisContext)
private static void AnalyzeOperation(OperationAnalysisContext context, INamedTypeSymbol containingType)
{
- var operation = context.Operation as IInvocationOperation;
+ var operation = (IInvocationOperation)context.Operation;
IMethodSymbol method = operation.TargetMethod;
if (method != null &&
(method.IsAbstract || method.IsVirtual) &&
@@ -72,7 +72,7 @@ private static void AnalyzeOperation(OperationAnalysisContext context, INamedTyp
}
}
- private static bool ShouldOmitThisDiagnostic(ISymbol symbol, INamedTypeSymbol webUiControlType, INamedTypeSymbol componentModelComponentType)
+ private static bool ShouldOmitThisDiagnostic(ISymbol symbol, INamedTypeSymbol? webUiControlType, INamedTypeSymbol? componentModelComponentType)
{
// This diagnostic is only relevant in constructors.
// TODO: should this apply to instance field initializers for VB?
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/MarkMembersAsStatic.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/MarkMembersAsStatic.Fixer.cs
index 46b6472fd8..2aacf76065 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/MarkMembersAsStatic.Fixer.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/MarkMembersAsStatic.Fixer.cs
@@ -25,8 +25,8 @@ public abstract class MarkMembersAsStaticFixer : CodeFixProvider
{
private static readonly SyntaxAnnotation s_annotationForFixedDeclaration = new SyntaxAnnotation();
- protected abstract IEnumerable GetTypeArguments(SyntaxNode node);
- protected abstract SyntaxNode GetExpressionOfInvocation(SyntaxNode invocation);
+ protected abstract IEnumerable? GetTypeArguments(SyntaxNode node);
+ protected abstract SyntaxNode? GetExpressionOfInvocation(SyntaxNode invocation);
protected virtual SyntaxNode GetSyntaxNodeToReplace(IMemberReferenceOperation memberReference)
=> memberReference.Syntax;
@@ -134,7 +134,7 @@ private async Task<(Solution newSolution, bool allReferencesFixed)> UpdateRefere
}
var operation = semanticModel.GetOperationWalkingUpParentChain(referenceNode, cancellationToken);
- SyntaxNode nodeToReplaceOpt = null;
+ SyntaxNode? nodeToReplaceOpt = null;
switch (operation)
{
case IMemberReferenceOperation memberReference:
@@ -213,7 +213,7 @@ static bool IsReplacableOperation(IOperation operation)
return false;
}
- ISymbol GetSymbolForNodeToReplace(SyntaxNode nodeToReplace, SemanticModel semanticModel)
+ ISymbol? GetSymbolForNodeToReplace(SyntaxNode nodeToReplace, SemanticModel semanticModel)
{
var symbolInfo = semanticModel.GetSymbolInfo(nodeToReplace, cancellationToken);
var symbolForNodeToReplace = symbolInfo.Symbol;
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/MarkMembersAsStatic.cs b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/MarkMembersAsStatic.cs
index a862d98084..0b771f234d 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/MarkMembersAsStatic.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/MarkMembersAsStatic.cs
@@ -229,9 +229,9 @@ private static bool IsExplicitlyVisibleFromCom(IMethodSymbol methodSymbol, Compi
private static ImmutableArray GetSkippedAttributes(Compilation compilation)
{
- ImmutableArray.Builder builder = null;
+ ImmutableArray.Builder? builder = null;
- void Add(INamedTypeSymbol symbol)
+ void Add(INamedTypeSymbol? symbol)
{
if (symbol != null)
{
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/UseLiteralsWhereAppropriate.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/UseLiteralsWhereAppropriate.Fixer.cs
index 2590c15e83..7f1f781118 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/UseLiteralsWhereAppropriate.Fixer.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/UseLiteralsWhereAppropriate.Fixer.cs
@@ -91,7 +91,7 @@ private async Task ToConstantDeclarationAsync(Document document, Synta
return editor.GetChangedDocument();
}
- protected abstract SyntaxNode GetFieldDeclaration(SyntaxNode syntaxNode);
+ protected abstract SyntaxNode? GetFieldDeclaration(SyntaxNode syntaxNode);
protected abstract bool IsStaticKeyword(SyntaxToken syntaxToken);
protected abstract bool IsReadonlyKeyword(SyntaxToken syntaxToken);
protected abstract SyntaxToken GetConstKeywordToken();
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/UseLiteralsWhereAppropriate.cs b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/UseLiteralsWhereAppropriate.cs
index 54de51fe5a..b22d9b4d8c 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/UseLiteralsWhereAppropriate.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/UseLiteralsWhereAppropriate.cs
@@ -61,6 +61,7 @@ public override void Initialize(AnalysisContext analysisContext)
var lastField = fieldInitializer?.InitializedFields.LastOrDefault();
var fieldInitializerValue = fieldInitializer?.Value;
if (fieldInitializerValue == null ||
+ lastField == null ||
lastField.IsConst ||
!lastField.IsReadOnly ||
!fieldInitializerValue.ConstantValue.HasValue ||
diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/ValidateArgumentsOfPublicMethods.cs b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/ValidateArgumentsOfPublicMethods.cs
index ff75ea8559..908de98b65 100644
--- a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/ValidateArgumentsOfPublicMethods.cs
+++ b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/ValidateArgumentsOfPublicMethods.cs
@@ -82,7 +82,7 @@ public override void Initialize(AnalysisContext context)
}
// Perform analysis of all direct/indirect parameter usages in the method to get all non-validated usages that can cause a null dereference.
- ImmutableDictionary hazardousParameterUsages = null;
+ ImmutableDictionary? hazardousParameterUsages = null;
foreach (var operationBlock in operationBlockContext.OperationBlocks)
{
if (operationBlock is IBlockOperation topmostBlock)
diff --git a/src/Microsoft.CodeQuality.Analyzers/VisualBasic/ApiDesignGuidelines/BasicUseGenericEventHandlerInstances.vb b/src/Microsoft.CodeQuality.Analyzers/VisualBasic/ApiDesignGuidelines/BasicUseGenericEventHandlerInstances.vb
index a3d7747d0e..401a135df8 100644
--- a/src/Microsoft.CodeQuality.Analyzers/VisualBasic/ApiDesignGuidelines/BasicUseGenericEventHandlerInstances.vb
+++ b/src/Microsoft.CodeQuality.Analyzers/VisualBasic/ApiDesignGuidelines/BasicUseGenericEventHandlerInstances.vb
@@ -11,7 +11,7 @@ Namespace Microsoft.CodeQuality.VisualBasic.Analyzers.ApiDesignGuidelines
Public Class BasicUseGenericEventHandlerInstancesAnalyzer
Inherits UseGenericEventHandlerInstancesAnalyzer
- Protected Overrides Function IsAssignableTo(compilation As Compilation, fromSymbol As ITypeSymbol, toSymbol As ITypeSymbol) As Boolean
+ Protected Overrides Function IsAssignableTo(fromSymbol As ITypeSymbol, toSymbol As ITypeSymbol, compilation As Compilation) As Boolean
Return fromSymbol IsNot Nothing AndAlso toSymbol IsNot Nothing AndAlso DirectCast(compilation, VisualBasicCompilation).ClassifyConversion(fromSymbol, toSymbol).IsWidening
End Function
End Class
diff --git a/src/Microsoft.CodeQuality.Analyzers/VisualBasic/QualityGuidelines/BasicRemoveEmptyFinalizersAnalyzer.vb b/src/Microsoft.CodeQuality.Analyzers/VisualBasic/QualityGuidelines/BasicRemoveEmptyFinalizersAnalyzer.vb
index a7ff4b3934..1c46ca2c33 100644
--- a/src/Microsoft.CodeQuality.Analyzers/VisualBasic/QualityGuidelines/BasicRemoveEmptyFinalizersAnalyzer.vb
+++ b/src/Microsoft.CodeQuality.Analyzers/VisualBasic/QualityGuidelines/BasicRemoveEmptyFinalizersAnalyzer.vb
@@ -1,4 +1,5 @@
-Imports Analyzer.Utilities
+' Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
+
Imports Analyzer.Utilities.Extensions
Imports Microsoft.CodeAnalysis
Imports Microsoft.CodeAnalysis.Diagnostics
diff --git a/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpDoNotUseCountWhenAnyCanBeUsed.Fixer.cs b/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpDoNotUseCountWhenAnyCanBeUsed.Fixer.cs
index bd876f0fd7..ff6d417299 100644
--- a/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpDoNotUseCountWhenAnyCanBeUsed.Fixer.cs
+++ b/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpDoNotUseCountWhenAnyCanBeUsed.Fixer.cs
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Composition;
+using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -26,21 +27,25 @@ public sealed class CSharpDoNotUseCountWhenAnyCanBeUsedFixer : DoNotUseCountWhen
/// If this method returns , contains the arguments from Any to be used on Count.
/// if a fixer was found., otherwise.
///
- protected override bool TryGetFixer(SyntaxNode node, string operation, bool isAsync, out SyntaxNode expression, out IEnumerable arguments)
+ protected override bool TryGetFixer(
+ SyntaxNode node,
+ string operation,
+ bool isAsync,
+ [NotNullWhen(returnValue: true)] out SyntaxNode? expression,
+ [NotNullWhen(returnValue: true)] out IEnumerable? arguments)
{
switch (operation)
{
case DoNotUseCountWhenAnyCanBeUsedAnalyzer.OperationEqualsInstance:
{
if (node is InvocationExpressionSyntax invocation &&
- invocation.Expression is MemberAccessExpressionSyntax member)
- {
- GetExpressionAndInvocationArguments(
+ invocation.Expression is MemberAccessExpressionSyntax member &&
+ TryGetExpressionAndInvocationArguments(
sourceExpression: member.Expression,
isAsync: isAsync,
expression: out expression,
- arguments: out arguments);
-
+ arguments: out arguments))
+ {
return true;
}
@@ -49,14 +54,13 @@ protected override bool TryGetFixer(SyntaxNode node, string operation, bool isAs
case DoNotUseCountWhenAnyCanBeUsedAnalyzer.OperationEqualsArgument:
{
if (node is InvocationExpressionSyntax invocation &&
- invocation.ArgumentList.Arguments.Count == 1)
- {
- GetExpressionAndInvocationArguments(
+ invocation.ArgumentList.Arguments.Count == 1 &&
+ TryGetExpressionAndInvocationArguments(
sourceExpression: invocation.ArgumentList.Arguments[0].Expression,
isAsync: isAsync,
expression: out expression,
- arguments: out arguments);
-
+ arguments: out arguments))
+ {
return true;
}
@@ -64,14 +68,13 @@ protected override bool TryGetFixer(SyntaxNode node, string operation, bool isAs
}
case DoNotUseCountWhenAnyCanBeUsedAnalyzer.OperationBinaryLeft:
{
- if (node is BinaryExpressionSyntax binary)
- {
- GetExpressionAndInvocationArguments(
+ if (node is BinaryExpressionSyntax binary &&
+ TryGetExpressionAndInvocationArguments(
sourceExpression: binary.Left,
isAsync: isAsync,
expression: out expression,
- arguments: out arguments);
-
+ arguments: out arguments))
+ {
return true;
}
@@ -79,14 +82,13 @@ protected override bool TryGetFixer(SyntaxNode node, string operation, bool isAs
}
case DoNotUseCountWhenAnyCanBeUsedAnalyzer.OperationBinaryRight:
{
- if (node is BinaryExpressionSyntax binary)
- {
- GetExpressionAndInvocationArguments(
+ if (node is BinaryExpressionSyntax binary &&
+ TryGetExpressionAndInvocationArguments(
sourceExpression: binary.Right,
isAsync: isAsync,
expression: out expression,
- arguments: out arguments);
-
+ arguments: out arguments))
+ {
return true;
}
@@ -99,14 +101,18 @@ protected override bool TryGetFixer(SyntaxNode node, string operation, bool isAs
return false;
}
- private static void GetExpressionAndInvocationArguments(ExpressionSyntax sourceExpression, bool isAsync, out SyntaxNode expression, out IEnumerable arguments)
+ private static bool TryGetExpressionAndInvocationArguments(
+ ExpressionSyntax sourceExpression,
+ bool isAsync,
+ [NotNullWhen(returnValue: true)] out SyntaxNode? expression,
+ [NotNullWhen(returnValue: true)] out IEnumerable? arguments)
{
while (sourceExpression is ParenthesizedExpressionSyntax parenthesizedExpression)
{
sourceExpression = parenthesizedExpression.Expression;
}
- InvocationExpressionSyntax invocationExpression = null;
+ InvocationExpressionSyntax? invocationExpression = null;
if (isAsync)
{
@@ -124,11 +130,12 @@ private static void GetExpressionAndInvocationArguments(ExpressionSyntax sourceE
{
expression = default;
arguments = default;
- return;
+ return false;
}
expression = ((MemberAccessExpressionSyntax)invocationExpression.Expression).Expression;
arguments = invocationExpression.ArgumentList.ChildNodes();
+ return true;
}
}
}
diff --git a/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs b/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs
index 99bf9b2f2a..891a2b8996 100644
--- a/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs
+++ b/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Composition;
+using System.Diagnostics.CodeAnalysis;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CodeFixes;
using Microsoft.CodeAnalysis.CSharp.Syntax;
@@ -25,7 +26,10 @@ public sealed class CSharpUsePropertyInsteadOfCountMethodWhenAvailableFixer : Us
/// The name node for the invocation node.
/// if a and were found;
/// otherwise.
- protected override bool TryGetExpression(SyntaxNode invocationNode, out SyntaxNode memberAccessNode, out SyntaxNode nameNode)
+ protected override bool TryGetExpression(
+ SyntaxNode invocationNode,
+ [NotNullWhen(returnValue: true)] out SyntaxNode? memberAccessNode,
+ [NotNullWhen(returnValue: true)] out SyntaxNode? nameNode)
{
if (invocationNode is InvocationExpressionSyntax invocationExpression)
{
diff --git a/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.cs b/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.cs
index f33002576d..fd3d11876a 100644
--- a/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.cs
+++ b/src/Microsoft.NetCore.Analyzers/CSharp/Performance/CSharpUsePropertyInsteadOfCountMethodWhenAvailable.cs
@@ -42,7 +42,7 @@ internal CSharpOperationActionsHandler(OperationActionsContext context)
{
}
- protected override ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation)
+ protected override ITypeSymbol? GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation)
{
var method = invocationOperation.TargetMethod;
diff --git a/src/Microsoft.NetCore.Analyzers/CSharp/Runtime/CSharpMarkAllNonSerializableFields.Fixer.cs b/src/Microsoft.NetCore.Analyzers/CSharp/Runtime/CSharpMarkAllNonSerializableFields.Fixer.cs
index 117d2a3fb7..13e0d8d767 100644
--- a/src/Microsoft.NetCore.Analyzers/CSharp/Runtime/CSharpMarkAllNonSerializableFields.Fixer.cs
+++ b/src/Microsoft.NetCore.Analyzers/CSharp/Runtime/CSharpMarkAllNonSerializableFields.Fixer.cs
@@ -11,7 +11,7 @@ namespace Microsoft.NetCore.CSharp.Analyzers.Runtime
[ExportCodeFixProvider(LanguageNames.CSharp, Name = "CA2237 CodeFix provider"), Shared]
public class CSharpMarkAllNonSerializableFieldsFixer : MarkAllNonSerializableFieldsFixer
{
- protected override SyntaxNode GetFieldDeclarationNode(SyntaxNode node)
+ protected override SyntaxNode? GetFieldDeclarationNode(SyntaxNode node)
{
SyntaxNode fieldNode = node;
while (fieldNode != null && fieldNode.Kind() != SyntaxKind.FieldDeclaration)
diff --git a/src/Microsoft.NetCore.Analyzers/CSharp/Runtime/CSharpUseOrdinalStringComparison.Fixer.cs b/src/Microsoft.NetCore.Analyzers/CSharp/Runtime/CSharpUseOrdinalStringComparison.Fixer.cs
index 9453458ff7..2ab2760147 100644
--- a/src/Microsoft.NetCore.Analyzers/CSharp/Runtime/CSharpUseOrdinalStringComparison.Fixer.cs
+++ b/src/Microsoft.NetCore.Analyzers/CSharp/Runtime/CSharpUseOrdinalStringComparison.Fixer.cs
@@ -47,11 +47,10 @@ protected override bool IsInIdentifierNameContext(SyntaxNode node)
protected override async Task FixIdentifierName(Document document, SyntaxGenerator generator, SyntaxNode root, SyntaxNode identifier, CancellationToken cancellationToken)
{
- InvocationExpressionSyntax invokeParent = identifier?.Parent?.FirstAncestorOrSelf();
- if (invokeParent != null)
+ if (identifier?.Parent?.FirstAncestorOrSelf() is InvocationExpressionSyntax invokeParent)
{
SemanticModel model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
- if (model.GetSymbolInfo((IdentifierNameSyntax)identifier, cancellationToken).Symbol is IMethodSymbol methodSymbol && CanAddStringComparison(methodSymbol, model))
+ if (model.GetSymbolInfo((IdentifierNameSyntax)identifier!, cancellationToken).Symbol is IMethodSymbol methodSymbol && CanAddStringComparison(methodSymbol, model))
{
// append a new StringComparison.Ordinal argument
SyntaxNode newArg = generator.Argument(CreateOrdinalMemberAccess(generator, model))
diff --git a/src/Microsoft.NetCore.Analyzers/CSharp/Runtime/CSharpUseOrdinalStringComparison.cs b/src/Microsoft.NetCore.Analyzers/CSharp/Runtime/CSharpUseOrdinalStringComparison.cs
index 82d0fadb6c..d2d1a8630e 100644
--- a/src/Microsoft.NetCore.Analyzers/CSharp/Runtime/CSharpUseOrdinalStringComparison.cs
+++ b/src/Microsoft.NetCore.Analyzers/CSharp/Runtime/CSharpUseOrdinalStringComparison.cs
@@ -16,7 +16,7 @@ protected override Location GetMethodNameLocation(SyntaxNode invocationNode)
{
Debug.Assert(invocationNode.IsKind(SyntaxKind.InvocationExpression));
- var invocation = invocationNode as InvocationExpressionSyntax;
+ var invocation = (InvocationExpressionSyntax)invocationNode;
if (invocation.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression))
{
return ((MemberAccessExpressionSyntax)invocation.Expression).Name.GetLocation();
diff --git a/src/Microsoft.NetCore.Analyzers/Core/Data/ReviewSqlQueriesForSecurityVulnerabilities.cs b/src/Microsoft.NetCore.Analyzers/Core/Data/ReviewSqlQueriesForSecurityVulnerabilities.cs
index 5a55ec9eb8..7fcd0f251b 100644
--- a/src/Microsoft.NetCore.Analyzers/Core/Data/ReviewSqlQueriesForSecurityVulnerabilities.cs
+++ b/src/Microsoft.NetCore.Analyzers/Core/Data/ReviewSqlQueriesForSecurityVulnerabilities.cs
@@ -41,9 +41,9 @@ public override void Initialize(AnalysisContext context)
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(compilationContext =>
{
- INamedTypeSymbol iDbCommandType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataIDbCommand);
- INamedTypeSymbol iDataAdapterType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataIDataAdapter);
- IPropertySymbol commandTextProperty = iDbCommandType?.GetMembers("CommandText").OfType().FirstOrDefault();
+ INamedTypeSymbol? iDbCommandType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataIDbCommand);
+ INamedTypeSymbol? iDataAdapterType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataIDataAdapter);
+ IPropertySymbol? commandTextProperty = iDbCommandType?.GetMembers("CommandText").OfType().FirstOrDefault();
if (iDbCommandType == null ||
iDataAdapterType == null ||
diff --git a/src/Microsoft.NetCore.Analyzers/Core/InteropServices/PInvokeDiagnosticAnalyzer.cs b/src/Microsoft.NetCore.Analyzers/Core/InteropServices/PInvokeDiagnosticAnalyzer.cs
index d7817d1135..ce72be2f89 100644
--- a/src/Microsoft.NetCore.Analyzers/Core/InteropServices/PInvokeDiagnosticAnalyzer.cs
+++ b/src/Microsoft.NetCore.Analyzers/Core/InteropServices/PInvokeDiagnosticAnalyzer.cs
@@ -52,25 +52,25 @@ public override void Initialize(AnalysisContext analysisContext)
analysisContext.RegisterCompilationStartAction(
(context) =>
{
- INamedTypeSymbol dllImportType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesDllImportAttribute);
+ INamedTypeSymbol? dllImportType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesDllImportAttribute);
if (dllImportType == null)
{
return;
}
- INamedTypeSymbol marshalAsType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesMarshalAsAttribute);
+ INamedTypeSymbol? marshalAsType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesMarshalAsAttribute);
if (marshalAsType == null)
{
return;
}
- INamedTypeSymbol stringBuilderType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemTextStringBuilder);
+ INamedTypeSymbol? stringBuilderType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemTextStringBuilder);
if (stringBuilderType == null)
{
return;
}
- INamedTypeSymbol unmanagedType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesUnmanagedType);
+ INamedTypeSymbol? unmanagedType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesUnmanagedType);
if (unmanagedType == null)
{
return;
diff --git a/src/Microsoft.NetCore.Analyzers/Core/InteropServices/SpecifyMarshalingForPInvokeStringArguments.Fixer.cs b/src/Microsoft.NetCore.Analyzers/Core/InteropServices/SpecifyMarshalingForPInvokeStringArguments.Fixer.cs
index 6a575cf2ce..d9a7e39950 100644
--- a/src/Microsoft.NetCore.Analyzers/Core/InteropServices/SpecifyMarshalingForPInvokeStringArguments.Fixer.cs
+++ b/src/Microsoft.NetCore.Analyzers/Core/InteropServices/SpecifyMarshalingForPInvokeStringArguments.Fixer.cs
@@ -31,10 +31,10 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
}
SemanticModel model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false);
- INamedTypeSymbol charSetType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesCharSet);
- INamedTypeSymbol dllImportType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesDllImportAttribute);
- INamedTypeSymbol marshalAsType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesMarshalAsAttribute);
- INamedTypeSymbol unmanagedType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesUnmanagedType);
+ INamedTypeSymbol? charSetType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesCharSet);
+ INamedTypeSymbol? dllImportType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesDllImportAttribute);
+ INamedTypeSymbol? marshalAsType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesMarshalAsAttribute);
+ INamedTypeSymbol? unmanagedType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesUnmanagedType);
if (charSetType == null || dllImportType == null || marshalAsType == null || unmanagedType == null)
{
return;
diff --git a/src/Microsoft.NetCore.Analyzers/Core/Performance/DoNotUseCountWhenAnyCanBeUsed.Fixer.cs b/src/Microsoft.NetCore.Analyzers/Core/Performance/DoNotUseCountWhenAnyCanBeUsed.Fixer.cs
index d20a4d4b24..2770e29507 100644
--- a/src/Microsoft.NetCore.Analyzers/Core/Performance/DoNotUseCountWhenAnyCanBeUsed.Fixer.cs
+++ b/src/Microsoft.NetCore.Analyzers/Core/Performance/DoNotUseCountWhenAnyCanBeUsed.Fixer.cs
@@ -2,6 +2,7 @@
using System.Collections.Generic;
using System.Collections.Immutable;
+using System.Diagnostics.CodeAnalysis;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis;
@@ -77,7 +78,12 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
/// If this method returns , contains the expression to be used to invoke Any.
/// If this method returns , contains the arguments from Any to be used on Count.
/// if a fixer was found., otherwise.
- protected abstract bool TryGetFixer(SyntaxNode node, string operation, bool isAsync, out SyntaxNode expression, out IEnumerable arguments);
+ protected abstract bool TryGetFixer(
+ SyntaxNode node,
+ string operation,
+ bool isAsync,
+ [NotNullWhen(returnValue: true)] out SyntaxNode? expression,
+ [NotNullWhen(returnValue: true)] out IEnumerable? arguments);
private class DoNotUseCountWhenAnyCanBeUsedCodeAction : CodeAction
{
diff --git a/src/Microsoft.NetCore.Analyzers/Core/Performance/DoNotUseCountWhenAnyCanBeUsed.cs b/src/Microsoft.NetCore.Analyzers/Core/Performance/DoNotUseCountWhenAnyCanBeUsed.cs
index 86fc78ee21..90d3b510c7 100644
--- a/src/Microsoft.NetCore.Analyzers/Core/Performance/DoNotUseCountWhenAnyCanBeUsed.cs
+++ b/src/Microsoft.NetCore.Analyzers/Core/Performance/DoNotUseCountWhenAnyCanBeUsed.cs
@@ -2,6 +2,7 @@
using System;
using System.Collections.Immutable;
+using System.Diagnostics.CodeAnalysis;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis;
@@ -278,7 +279,7 @@ public void AnalyzeInvocationOperation(OperationAnalysisContext context)
return;
}
- var propertiesBuilder = ImmutableDictionary.CreateBuilder(StringComparer.Ordinal);
+ var propertiesBuilder = ImmutableDictionary.CreateBuilder(StringComparer.Ordinal);
propertiesBuilder.Add(OperationKey, operationKey);
propertiesBuilder.Add(ShouldNegateKey, null);
if (this._isAsync) propertiesBuilder.Add(IsAsyncKey, null);
@@ -317,7 +318,7 @@ public void AnalyzeBinaryOperation(OperationAnalysisContext context)
return;
}
- var propertiesBuilder = ImmutableDictionary.CreateBuilder(StringComparer.Ordinal);
+ var propertiesBuilder = ImmutableDictionary.CreateBuilder(StringComparer.Ordinal);
propertiesBuilder.Add(OperationKey, operationKey);
if (shouldNegate) propertiesBuilder.Add(ShouldNegateKey, null);
if (this._isAsync) propertiesBuilder.Add(IsAsyncKey, null);
@@ -354,7 +355,7 @@ private static bool IsEqualsMethod(IMethodSymbol methodSymbol)
///
/// if the value of the invocation of one of the in the
/// is being compared with 0 using ; otherwise, .
- private bool IsCountEqualsZero(IInvocationOperation invocationOperation, out string methodName)
+ private bool IsCountEqualsZero(IInvocationOperation invocationOperation, [NotNullWhen(returnValue: true)] out string? methodName)
{
if (!TryGetZeroOrOneConstant(invocationOperation.Arguments[0].Value, out var constant) || constant != 0)
{
@@ -372,7 +373,7 @@ private bool IsCountEqualsZero(IInvocationOperation invocationOperation, out str
/// The invocation operation.
/// if 0 is being compared with the value of the invocation of one of the in the
/// using ; otherwise, .
- private bool IsZeroEqualsCount(IInvocationOperation invocationOperation, out string methodName)
+ private bool IsZeroEqualsCount(IInvocationOperation invocationOperation, [NotNullWhen(returnValue: true)] out string? methodName)
{
if (!TryGetZeroOrOneConstant(invocationOperation.Instance, out var constant) || constant != 0)
{
@@ -391,7 +392,7 @@ private bool IsZeroEqualsCount(IInvocationOperation invocationOperation, out str
/// If the value of the invocation of one of the in the , contains the method name; otherwise.
/// if the value of the invocation of one of the in the
/// is being compared with 0 or 1 using comparison operators; otherwise, .
- private bool IsLeftCountComparison(IBinaryOperation binaryOperation, out string methodName, out bool shouldNegate)
+ private bool IsLeftCountComparison(IBinaryOperation binaryOperation, [NotNullWhen(returnValue: true)] out string? methodName, out bool shouldNegate)
{
methodName = null;
shouldNegate = false;
@@ -448,7 +449,7 @@ private bool IsLeftCountComparison(IBinaryOperation binaryOperation, out string
/// If the value of the invocation of one of the in the , contains the method name; otherwise.
/// if 0 or 1 is being compared with the value of the invocation of one of the in the
/// using comparison operators; otherwise, .
- private bool IsRightCountComparison(IBinaryOperation binaryOperation, out string methodName, out bool shouldNegate)
+ private bool IsRightCountComparison(IBinaryOperation binaryOperation, [NotNullWhen(returnValue: true)] out string? methodName, out bool shouldNegate)
{
methodName = null;
shouldNegate = false;
@@ -582,7 +583,7 @@ private static bool TryGetZeroOrOneConstant(IOperation operation, out int consta
/// If the is an invocation of one of the in the , contains the method name; otherwise.
/// if the is an invocation of one of the in the ;
/// otherwise.
- private bool IsCountMethodInvocation(IOperation operation, out string methodName)
+ private bool IsCountMethodInvocation(IOperation operation, [NotNullWhen(returnValue: true)] out string? methodName)
{
methodName = null;
diff --git a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs
index 121f92316e..69d9cbf4a5 100644
--- a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs
+++ b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.Fixer.cs
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Immutable;
+using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
@@ -69,7 +70,10 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context)
/// The name node for the invocation node.
/// if a and were found;
/// otherwise.
- protected abstract bool TryGetExpression(SyntaxNode invocationNode, out SyntaxNode memberAccessNode, out SyntaxNode nameNode);
+ protected abstract bool TryGetExpression(
+ SyntaxNode invocationNode,
+ [NotNullWhen(returnValue: true)] out SyntaxNode? memberAccessNode,
+ [NotNullWhen(returnValue: true)] out SyntaxNode? nameNode);
///
/// Implements the for replacing the use of
diff --git a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs
index 7913b7a85b..94454a9f08 100644
--- a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs
+++ b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs
@@ -88,9 +88,9 @@ private void OnCompilationStart(CompilationStartAnalysisContext context)
///
protected sealed class OperationActionsContext
{
- private readonly Lazy _immutableArrayType;
- private readonly Lazy _iCollectionCountProperty;
- private readonly Lazy _iCollectionOfType;
+ private readonly Lazy _immutableArrayType;
+ private readonly Lazy _iCollectionCountProperty;
+ private readonly Lazy _iCollectionOfType;
///
/// Initializes a new instance of the class.
@@ -101,9 +101,9 @@ public OperationActionsContext(Compilation compilation, INamedTypeSymbol enumera
{
Compilation = compilation;
EnumerableType = enumerableType;
- _immutableArrayType = new Lazy(() => Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsImmutableImmutableArray), true);
- _iCollectionCountProperty = new Lazy(ResolveICollectionCountProperty, true);
- _iCollectionOfType = new Lazy(() => Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericICollection1), true);
+ _immutableArrayType = new Lazy(() => Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsImmutableImmutableArray), true);
+ _iCollectionCountProperty = new Lazy(ResolveICollectionCountProperty, true);
+ _iCollectionOfType = new Lazy(() => Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericICollection1), true);
}
///
@@ -118,27 +118,27 @@ public OperationActionsContext(Compilation compilation, INamedTypeSymbol enumera
/// Gets the property.
///
/// The property.
- private IPropertySymbol ICollectionCountProperty => _iCollectionCountProperty.Value;
+ private IPropertySymbol? ICollectionCountProperty => _iCollectionCountProperty.Value;
///
/// Gets the type of the type.
///
/// The type.
- private INamedTypeSymbol ICollectionOfTType => _iCollectionOfType.Value;
+ private INamedTypeSymbol? ICollectionOfTType => _iCollectionOfType.Value;
///
/// Gets the type of the type.
///
/// The type.
- internal INamedTypeSymbol ImmutableArrayType => _immutableArrayType.Value;
+ internal INamedTypeSymbol? ImmutableArrayType => _immutableArrayType.Value;
///
/// Gets the type of the property, if one and only one exists.
///
/// The property.
- private IPropertySymbol ResolveICollectionCountProperty()
+ private IPropertySymbol? ResolveICollectionCountProperty()
{
- IPropertySymbol countProperty = null;
+ IPropertySymbol? countProperty = null;
if (Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsICollection) is INamedTypeSymbol iCollectionType)
{
@@ -194,7 +194,7 @@ internal bool IsICollectionOfTImplementation(ITypeSymbol invocationTarget)
return false;
}
- if (isCollectionOfTInterface(invocationTarget))
+ if (isCollectionOfTInterface(invocationTarget, ICollectionOfTType))
{
return true;
}
@@ -209,7 +209,7 @@ internal bool IsICollectionOfTImplementation(ITypeSymbol invocationTarget)
foreach (var @interface in invocationTarget.AllInterfaces)
{
if (@interface.OriginalDefinition is INamedTypeSymbol originalInterfaceDefinition &&
- isCollectionOfTInterface(originalInterfaceDefinition))
+ isCollectionOfTInterface(originalInterfaceDefinition, ICollectionOfTType))
{
return true;
}
@@ -220,7 +220,7 @@ internal bool IsICollectionOfTImplementation(ITypeSymbol invocationTarget)
foreach (var @interface in invocationTarget.AllInterfaces)
{
if (@interface.OriginalDefinition is INamedTypeSymbol originalInterfaceDefinition &&
- isCollectionOfTInterface(originalInterfaceDefinition))
+ isCollectionOfTInterface(originalInterfaceDefinition, ICollectionOfTType))
{
if (invocationTarget.FindImplementationForInterfaceMember(@interface.GetMembers(CountPropertyName)[0]) is IPropertySymbol propertyImplementation &&
!propertyImplementation.ExplicitInterfaceImplementations.Any())
@@ -233,8 +233,8 @@ internal bool IsICollectionOfTImplementation(ITypeSymbol invocationTarget)
return false;
- bool isCollectionOfTInterface(ITypeSymbol type)
- => this.ICollectionOfTType.Equals(type.OriginalDefinition);
+ static bool isCollectionOfTInterface(ITypeSymbol type, ITypeSymbol iCollectionOfTType)
+ => iCollectionOfTType.Equals(type.OriginalDefinition);
}
///
@@ -291,14 +291,14 @@ internal void AnalyzeInvocationOperation(OperationAnalysisContext context)
///
/// The invocation operation.
/// The of the receiver of the extension method.
- protected abstract ITypeSymbol GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation);
+ protected abstract ITypeSymbol? GetEnumerableCountInvocationTargetType(IInvocationOperation invocationOperation);
///
/// Gets the replacement property.
///
/// The invocation target.
/// The name of the replacement property.
- private string GetReplacementProperty(ITypeSymbol invocationTarget)
+ private string? GetReplacementProperty(ITypeSymbol invocationTarget)
{
if ((invocationTarget.TypeKind == TypeKind.Array) || Context.IsImmutableArrayType(invocationTarget))
{
diff --git a/src/Microsoft.NetCore.Analyzers/Core/Resources/MarkAssembliesWithNeutralResourcesLanguage.cs b/src/Microsoft.NetCore.Analyzers/Core/Resources/MarkAssembliesWithNeutralResourcesLanguage.cs
index 179f529c4c..203f0383bd 100644
--- a/src/Microsoft.NetCore.Analyzers/Core/Resources/MarkAssembliesWithNeutralResourcesLanguage.cs
+++ b/src/Microsoft.NetCore.Analyzers/Core/Resources/MarkAssembliesWithNeutralResourcesLanguage.cs
@@ -96,7 +96,7 @@ protected static bool CheckResxGeneratedFile(SemanticModel model, SyntaxNode att
return false;
}
- INamedTypeSymbol generatedCode = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCodeDomCompilerGeneratedCodeAttribute);
+ INamedTypeSymbol? generatedCode = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCodeDomCompilerGeneratedCodeAttribute);
if (model.GetSymbolInfo(attribute, cancellationToken).Symbol?.ContainingType?.Equals(generatedCode) != true)
{
return false;
@@ -123,8 +123,8 @@ protected static bool CheckResxGeneratedFile(SemanticModel model, SyntaxNode att
private static bool TryCheckNeutralResourcesLanguageAttribute(CompilationAnalysisContext context, out AttributeData attributeData)
{
- INamedTypeSymbol attribute = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemResourcesNeutralResourcesLanguageAttribute);
- INamedTypeSymbol @string = context.Compilation.GetSpecialType(SpecialType.System_String);
+ INamedTypeSymbol? attribute = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemResourcesNeutralResourcesLanguageAttribute);
+ INamedTypeSymbol? @string = context.Compilation.GetSpecialType(SpecialType.System_String);
IEnumerable attributes = context.Compilation.Assembly.GetAttributes().Where(d => d.AttributeClass?.Equals(attribute) == true);
foreach (AttributeData data in attributes)
diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/AttributeStringLiteralsShouldParseCorrectly.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/AttributeStringLiteralsShouldParseCorrectly.cs
index 79a3fbda2e..8a312fe2c6 100644
--- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/AttributeStringLiteralsShouldParseCorrectly.cs
+++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/AttributeStringLiteralsShouldParseCorrectly.cs
@@ -88,7 +88,7 @@ public override void Initialize(AnalysisContext analysisContext)
{
case SymbolKind.NamedType:
{
- var namedType = symbol as INamedTypeSymbol;
+ var namedType = (INamedTypeSymbol)symbol;
AnalyzeSymbols(saContext.ReportDiagnostic, namedType.TypeParameters);
@@ -102,7 +102,7 @@ public override void Initialize(AnalysisContext analysisContext)
case SymbolKind.Method:
{
- var methodSymbol = symbol as IMethodSymbol;
+ var methodSymbol = (IMethodSymbol)symbol;
if (!methodSymbol.IsAccessorMethod())
{
AnalyzeSymbols(saContext.ReportDiagnostic, methodSymbol.Parameters);
@@ -114,7 +114,7 @@ public override void Initialize(AnalysisContext analysisContext)
case SymbolKind.Property:
{
- var propertySymbol = symbol as IPropertySymbol;
+ var propertySymbol = (IPropertySymbol)symbol;
AnalyzeSymbols(saContext.ReportDiagnostic, propertySymbol.Parameters);
return;
}
@@ -228,7 +228,7 @@ private static void Analyze(Action reportDiagnostic, AttributeData a
}
}
- private static ValueValidator GetValueValidator(string name)
+ private static ValueValidator? GetValueValidator(string name)
{
foreach (var valueValidator in s_tokensToValueValidator)
{
@@ -244,7 +244,7 @@ private static ValueValidator GetValueValidator(string name)
internal class ValueValidator
{
- private readonly string _ignoredName;
+ private readonly string? _ignoredName;
public ImmutableArray AcceptedTokens { get; }
public string TypeName { get; }
@@ -255,7 +255,7 @@ public bool IsIgnoredName(string name)
return _ignoredName != null && string.Equals(_ignoredName, name, StringComparison.OrdinalIgnoreCase);
}
- public ValueValidator(ImmutableArray acceptedTokens, string typeName, Func isValidValue, string ignoredName = null)
+ public ValueValidator(ImmutableArray acceptedTokens, string typeName, Func isValidValue, string? ignoredName = null)
{
_ignoredName = ignoredName;
diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidUnsealedAttributes.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidUnsealedAttributes.cs
index 3229b61279..4df1761488 100644
--- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidUnsealedAttributes.cs
+++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidUnsealedAttributes.cs
@@ -40,7 +40,7 @@ public override void Initialize(AnalysisContext analysisContext)
analysisContext.RegisterCompilationStartAction(compilationContext =>
{
- INamedTypeSymbol attributeType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemAttribute);
+ INamedTypeSymbol? attributeType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemAttribute);
if (attributeType == null)
{
return;
diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidZeroLengthArrayAllocations.Fixer.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidZeroLengthArrayAllocations.Fixer.cs
index d7c07365fa..467c7bb268 100644
--- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidZeroLengthArrayAllocations.Fixer.cs
+++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidZeroLengthArrayAllocations.Fixer.cs
@@ -51,18 +51,24 @@ private static async Task ConvertToArrayEmpty(Document document, Synta
SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
SyntaxGenerator generator = editor.Generator;
- ITypeSymbol elementType = GetArrayElementType(nodeToFix, semanticModel, cancellationToken);
+ INamedTypeSymbol? arrayTypeSymbol = semanticModel.Compilation.GetOrCreateTypeByMetadataName(AvoidZeroLengthArrayAllocationsAnalyzer.ArrayTypeName);
+ if (arrayTypeSymbol == null)
+ {
+ return document;
+ }
+
+ ITypeSymbol? elementType = GetArrayElementType(nodeToFix, semanticModel, cancellationToken);
if (elementType == null)
{
return document;
}
- SyntaxNode arrayEmptyInvocation = GenerateArrayEmptyInvocation(generator, elementType, semanticModel).WithTriviaFrom(nodeToFix);
+ SyntaxNode arrayEmptyInvocation = GenerateArrayEmptyInvocation(generator, arrayTypeSymbol, elementType).WithTriviaFrom(nodeToFix);
editor.ReplaceNode(nodeToFix, arrayEmptyInvocation);
return editor.GetChangedDocument();
}
- private static ITypeSymbol GetArrayElementType(SyntaxNode arrayCreationExpression, SemanticModel semanticModel, CancellationToken cancellationToken)
+ private static ITypeSymbol? GetArrayElementType(SyntaxNode arrayCreationExpression, SemanticModel semanticModel, CancellationToken cancellationToken)
{
var typeInfo = semanticModel.GetTypeInfo(arrayCreationExpression, cancellationToken);
// When Type is null in cases like 'T[] goo = { }', use ConvertedType instead (https://github.com/dotnet/roslyn/issues/23545).
@@ -72,9 +78,8 @@ private static ITypeSymbol GetArrayElementType(SyntaxNode arrayCreationExpressio
return arrayType?.ElementType;
}
- private static SyntaxNode GenerateArrayEmptyInvocation(SyntaxGenerator generator, ITypeSymbol elementType, SemanticModel semanticModel)
+ private static SyntaxNode GenerateArrayEmptyInvocation(SyntaxGenerator generator, INamedTypeSymbol arrayTypeSymbol, ITypeSymbol elementType)
{
- INamedTypeSymbol arrayTypeSymbol = semanticModel.Compilation.GetOrCreateTypeByMetadataName(AvoidZeroLengthArrayAllocationsAnalyzer.ArrayTypeName);
SyntaxNode arrayEmptyName = generator.MemberAccessExpression(
generator.TypeExpressionForStaticMemberAccess(arrayTypeSymbol),
generator.GenericName(AvoidZeroLengthArrayAllocationsAnalyzer.ArrayEmptyMethodName, elementType));
diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidZeroLengthArrayAllocations.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidZeroLengthArrayAllocations.cs
index 7f180e32f9..f6807a8ba2 100644
--- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidZeroLengthArrayAllocations.cs
+++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidZeroLengthArrayAllocations.cs
@@ -51,7 +51,7 @@ public sealed override void Initialize(AnalysisContext context)
// Only if it is, register the syntax node action provided by the derived implementations.
context.RegisterCompilationStartAction(ctx =>
{
- INamedTypeSymbol typeSymbol = ctx.Compilation.GetOrCreateTypeByMetadataName(ArrayTypeName);
+ INamedTypeSymbol? typeSymbol = ctx.Compilation.GetOrCreateTypeByMetadataName(ArrayTypeName);
if (typeSymbol != null && typeSymbol.DeclaredAccessibility == Accessibility.Public)
{
if (typeSymbol.GetMembers(ArrayEmptyMethodName).FirstOrDefault() is IMethodSymbol methodSymbol && methodSymbol.DeclaredAccessibility == Accessibility.Public &&
@@ -102,6 +102,11 @@ private static void AnalyzeOperation(OperationAnalysisContext context, Func.Empty;
if (parent is IInvocationOperation invocation)
{
@@ -163,7 +168,7 @@ private static bool IsCompilerGeneratedParamsArray(IArrayCreationOperation array
return lastArgument != null && lastArgument.Value.Syntax == arrayCreationExpression.Syntax && AreEquivalentZeroLengthArrayCreations(arrayCreationExpression, lastArgument.Value as IArrayCreationOperation);
}
- private static bool AreEquivalentZeroLengthArrayCreations(IArrayCreationOperation first, IArrayCreationOperation second)
+ private static bool AreEquivalentZeroLengthArrayCreations(IArrayCreationOperation? first, IArrayCreationOperation? second)
{
if (first == null || second == null)
{
diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/CallGCSuppressFinalizeCorrectly.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/CallGCSuppressFinalizeCorrectly.cs
index 4d1f1c1241..6c10881b13 100644
--- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/CallGCSuppressFinalizeCorrectly.cs
+++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/CallGCSuppressFinalizeCorrectly.cs
@@ -121,7 +121,6 @@ private enum SuppressFinalizeUsage
private readonly SuppressFinalizeUsage _expectedUsage;
private bool _suppressFinalizeCalled;
- private SemanticModel _semanticModel;
public SuppressFinalizeAnalyzer(IMethodSymbol methodSymbol, IMethodSymbol gcSuppressFinalizeMethodSymbol, Compilation compilation)
{
@@ -139,11 +138,6 @@ public void Analyze(OperationAnalysisContext analysisContext)
{
_suppressFinalizeCalled = true;
- if (_semanticModel == null)
- {
- _semanticModel = analysisContext.Compilation.GetSemanticModel(analysisContext.Operation.Syntax.SyntaxTree);
- }
-
// Check for GC.SuppressFinalize outside of IDisposable.Dispose()
if (_expectedUsage == SuppressFinalizeUsage.MustNotCall)
{
@@ -159,7 +153,7 @@ public void Analyze(OperationAnalysisContext analysisContext)
return;
}
- if (!(_semanticModel.GetSymbolInfo(invocationExpression.Arguments.Single().Value.Syntax).Symbol is IParameterSymbol parameterSymbol) || !parameterSymbol.IsThis)
+ if (!(invocationExpression.SemanticModel.GetSymbolInfo(invocationExpression.Arguments.Single().Value.Syntax).Symbol is IParameterSymbol parameterSymbol) || !parameterSymbol.IsThis)
{
analysisContext.ReportDiagnostic(invocationExpression.Syntax.CreateDiagnostic(
NotPassedThisRule,
diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/DisposableFieldsShouldBeDisposed.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/DisposableFieldsShouldBeDisposed.cs
index 98378ba9a3..57f98b27eb 100644
--- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/DisposableFieldsShouldBeDisposed.cs
+++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/DisposableFieldsShouldBeDisposed.cs
@@ -44,7 +44,7 @@ public override void Initialize(AnalysisContext context)
context.RegisterCompilationStartAction(compilationContext =>
{
- if (!DisposeAnalysisHelper.TryGetOrCreate(compilationContext.Compilation, out DisposeAnalysisHelper disposeAnalysisHelper))
+ if (!DisposeAnalysisHelper.TryGetOrCreate(compilationContext.Compilation, out DisposeAnalysisHelper? disposeAnalysisHelper))
{
return;
}
@@ -53,7 +53,7 @@ public override void Initialize(AnalysisContext context)
void addOrUpdateFieldDisposedValue(IFieldSymbol field, bool disposed)
{
Debug.Assert(!field.IsStatic);
- Debug.Assert(field.Type.IsDisposable(disposeAnalysisHelper.IDisposable));
+ Debug.Assert(field.Type.IsDisposable(disposeAnalysisHelper!.IDisposable));
fieldDisposeValueMap.AddOrUpdate(field,
addValue: disposed,
@@ -94,7 +94,7 @@ void addOrUpdateFieldDisposedValue(IFieldSymbol field, bool disposed)
if (disposeAnalysisHelper.HasAnyDisposableCreationDescendant(operationBlockStartContext.OperationBlocks, containingMethod))
{
- PointsToAnalysisResult lazyPointsToAnalysisResult = null;
+ PointsToAnalysisResult? lazyPointsToAnalysisResult = null;
operationBlockStartContext.RegisterOperationAction(operationContext =>
{
@@ -122,6 +122,12 @@ void addOrUpdateFieldDisposedValue(IFieldSymbol field, bool disposed)
if (lazyPointsToAnalysisResult == null)
{
var cfg = operationBlockStartContext.OperationBlocks.GetControlFlowGraph();
+ if (cfg == null)
+ {
+ hasErrors = true;
+ return;
+ }
+
var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(operationContext.Compilation);
var interproceduralAnalysisConfig = InterproceduralAnalysisConfiguration.Create(
operationBlockStartContext.Options, Rule, InterproceduralAnalysisKind.None, operationBlockStartContext.CancellationToken);
@@ -162,6 +168,8 @@ void addOrUpdateFieldDisposedValue(IFieldSymbol field, bool disposed)
operationBlockStartContext.Options, Rule, trackInstanceFields: true, trackExceptionPaths: false, cancellationToken: operationBlockStartContext.CancellationToken,
disposeAnalysisResult: out var disposeAnalysisResult, pointsToAnalysisResult: out var pointsToAnalysisResult))
{
+ RoslynDebug.Assert(disposeAnalysisResult.TrackedInstanceFieldPointsToMap != null);
+
BasicBlock exitBlock = disposeAnalysisResult.ControlFlowGraph.GetExit();
foreach (var fieldWithPointsToValue in disposeAnalysisResult.TrackedInstanceFieldPointsToMap)
{
@@ -233,13 +241,13 @@ bool ShouldAnalyze(INamedTypeSymbol namedType)
// We only want to analyze types which are disposable (implement System.IDisposable directly or indirectly)
// and have at least one disposable field.
return !hasErrors &&
- namedType.IsDisposable(disposeAnalysisHelper.IDisposable) &&
+ namedType.IsDisposable(disposeAnalysisHelper!.IDisposable) &&
!disposeAnalysisHelper.GetDisposableFields(namedType).IsEmpty &&
!namedType.IsConfiguredToSkipAnalysis(compilationContext.Options, Rule, compilationContext.Compilation, compilationContext.CancellationToken);
}
bool IsDisposeMethod(IMethodSymbol method)
- => method.GetDisposeMethodKind(disposeAnalysisHelper.IDisposable, disposeAnalysisHelper.Task) != DisposeMethodKind.None;
+ => method.GetDisposeMethodKind(disposeAnalysisHelper!.IDisposable, disposeAnalysisHelper.Task) != DisposeMethodKind.None;
bool HasDisposeMethod(INamedTypeSymbol namedType)
{
diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/DisposableTypesShouldDeclareFinalizer.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/DisposableTypesShouldDeclareFinalizer.cs
index 669bf04871..65f097ea41 100644
--- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/DisposableTypesShouldDeclareFinalizer.cs
+++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/DisposableTypesShouldDeclareFinalizer.cs
@@ -46,7 +46,7 @@ public override void Initialize(AnalysisContext analysisContext)
{
Compilation compilation = compilationStartAnalysisContext.Compilation;
- ImmutableHashSet nativeResourceTypes = ImmutableHashSet.Create(
+ ImmutableHashSet nativeResourceTypes = ImmutableHashSet.Create(
compilation.GetSpecialType(SpecialType.System_IntPtr),
compilation.GetSpecialType(SpecialType.System_UIntPtr),
compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesHandleRef)
diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/DisposeMethodsShouldCallBaseClassDispose.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/DisposeMethodsShouldCallBaseClassDispose.cs
index a70cc02f46..bb8845b7d3 100644
--- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/DisposeMethodsShouldCallBaseClassDispose.cs
+++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/DisposeMethodsShouldCallBaseClassDispose.cs
@@ -46,7 +46,7 @@ public override void Initialize(AnalysisContext context)
context.RegisterCompilationStartAction(compilationContext =>
{
- if (!DisposeAnalysisHelper.TryGetOrCreate(compilationContext.Compilation, out DisposeAnalysisHelper disposeAnalysisHelper))
+ if (!DisposeAnalysisHelper.TryGetOrCreate(compilationContext.Compilation, out DisposeAnalysisHelper? disposeAnalysisHelper))
{
return;
}
diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/DisposeObjectsBeforeLosingScope.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/DisposeObjectsBeforeLosingScope.cs
index e77c1d1e5e..b546ca0f1c 100644
--- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/DisposeObjectsBeforeLosingScope.cs
+++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/DisposeObjectsBeforeLosingScope.cs
@@ -77,7 +77,7 @@ public override void Initialize(AnalysisContext context)
context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None);
context.RegisterCompilationStartAction(compilationContext =>
{
- if (!DisposeAnalysisHelper.TryGetOrCreate(compilationContext.Compilation, out DisposeAnalysisHelper disposeAnalysisHelper))
+ if (!DisposeAnalysisHelper.TryGetOrCreate(compilationContext.Compilation, out var disposeAnalysisHelper))
{
return;
}
@@ -123,7 +123,7 @@ public override void Initialize(AnalysisContext context)
if (trackExceptionPaths)
{
// Compute diagnostics for undisposed objects at handled exception exit paths.
- var disposeDataAtHandledExceptionPaths = disposeAnalysisResult.ExceptionPathsExitBlockOutputOpt.Data;
+ var disposeDataAtHandledExceptionPaths = disposeAnalysisResult.ExceptionPathsExitBlockOutputOpt!.Data;
ComputeDiagnostics(disposeDataAtHandledExceptionPaths,
notDisposedDiagnostics, mayBeNotDisposedDiagnostics, disposeAnalysisResult, pointsToAnalysisResult,
disposeAnalysisKind, isDisposeDataForExceptionPaths: true);
@@ -197,7 +197,7 @@ bool SkipInterproceduralAnalysis(IMethodSymbol invokedMethod)
bool CanBeDisposable(ITypeSymbol type)
=> type.SpecialType == SpecialType.System_Object ||
- type.DerivesFrom(disposeAnalysisHelper.IDisposable) ||
+ type.DerivesFrom(disposeAnalysisHelper!.IDisposable) ||
type.TypeKind == TypeKind.Delegate;
}
});
diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/DoNotLockOnObjectsWithWeakIdentity.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/DoNotLockOnObjectsWithWeakIdentity.cs
index d2e7bc75c5..9c821dc20e 100644
--- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/DoNotLockOnObjectsWithWeakIdentity.cs
+++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/DoNotLockOnObjectsWithWeakIdentity.cs
@@ -51,8 +51,8 @@ public override void Initialize(AnalysisContext analysisContext)
compilationStartContext.RegisterOperationAction(context =>
{
var lockStatement = (ILockOperation)context.Operation;
- ITypeSymbol type = lockStatement.LockedValue?.Type;
- if (type != null && TypeHasWeakIdentity(type, compilation))
+ if (lockStatement.LockedValue?.Type is ITypeSymbol type &&
+ TypeHasWeakIdentity(type, compilation))
{
context.ReportDiagnostic(lockStatement.LockedValue.Syntax.CreateDiagnostic(Rule, type.ToDisplayString()));
}
@@ -69,13 +69,13 @@ private static bool TypeHasWeakIdentity(ITypeSymbol type, Compilation compilatio
return type is IArrayTypeSymbol arrayType && IsPrimitiveType(arrayType.ElementType);
case TypeKind.Class:
case TypeKind.TypeParameter:
- INamedTypeSymbol marshalByRefObjectTypeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemMarshalByRefObject);
- INamedTypeSymbol executionEngineExceptionTypeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemExecutionEngineException);
- INamedTypeSymbol outOfMemoryExceptionTypeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemOutOfMemoryException);
- INamedTypeSymbol stackOverflowExceptionTypeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemStackOverflowException);
- INamedTypeSymbol memberInfoTypeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemReflectionMemberInfo);
- INamedTypeSymbol parameterInfoTypeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemReflectionParameterInfo);
- INamedTypeSymbol threadTypeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingThread);
+ INamedTypeSymbol? marshalByRefObjectTypeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemMarshalByRefObject);
+ INamedTypeSymbol? executionEngineExceptionTypeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemExecutionEngineException);
+ INamedTypeSymbol? outOfMemoryExceptionTypeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemOutOfMemoryException);
+ INamedTypeSymbol? stackOverflowExceptionTypeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemStackOverflowException);
+ INamedTypeSymbol? memberInfoTypeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemReflectionMemberInfo);
+ INamedTypeSymbol? parameterInfoTypeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemReflectionParameterInfo);
+ INamedTypeSymbol? threadTypeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingThread);
return
type.SpecialType == SpecialType.System_String ||
type.Equals(executionEngineExceptionTypeSymbol) ||
diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/DoNotPassLiteralsAsLocalizedParameters.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/DoNotPassLiteralsAsLocalizedParameters.cs
index b48d0a4598..122d318d95 100644
--- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/DoNotPassLiteralsAsLocalizedParameters.cs
+++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/DoNotPassLiteralsAsLocalizedParameters.cs
@@ -53,9 +53,9 @@ public override void Initialize(AnalysisContext context)
context.RegisterCompilationStartAction(compilationContext =>
{
- INamedTypeSymbol localizableStateAttributeSymbol = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemComponentModelLocalizableAttribute);
- INamedTypeSymbol conditionalAttributeSymbol = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDiagnosticsConditionalAttribute);
- INamedTypeSymbol systemConsoleSymbol = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemConsole);
+ INamedTypeSymbol? localizableStateAttributeSymbol = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemComponentModelLocalizableAttribute);
+ INamedTypeSymbol? conditionalAttributeSymbol = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDiagnosticsConditionalAttribute);
+ INamedTypeSymbol? systemConsoleSymbol = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemConsole);
ImmutableHashSet typesToIgnore = GetTypesToIgnore(compilationContext.Compilation);
compilationContext.RegisterOperationBlockStartAction(operationBlockStartContext =>
@@ -67,13 +67,13 @@ public override void Initialize(AnalysisContext context)
return;
}
- var lazyValueContentResult = new Lazy>(
+ var lazyValueContentResult = new Lazy?>(
valueFactory: ComputeValueContentAnalysisResult, isThreadSafe: false);
operationBlockStartContext.RegisterOperationAction(operationContext =>
{
var argument = (IArgumentOperation)operationContext.Operation;
- IMethodSymbol targetMethod = null;
+ IMethodSymbol? targetMethod = null;
switch (argument.Parent)
{
case IInvocationOperation invocation:
@@ -108,10 +108,10 @@ public override void Initialize(AnalysisContext context)
return;
// Local functions
- bool ShouldAnalyze(ISymbol symbol)
+ bool ShouldAnalyze(ISymbol? symbol)
=> symbol != null && !symbol.IsConfiguredToSkipAnalysis(operationBlockStartContext.Options, Rule, operationBlockStartContext.Compilation, operationBlockStartContext.CancellationToken);
- void AnalyzeArgument(IParameterSymbol parameter, IPropertySymbol containingPropertySymbolOpt, IOperation operation, Action reportDiagnostic)
+ void AnalyzeArgument(IParameterSymbol parameter, IPropertySymbol? containingPropertySymbolOpt, IOperation operation, Action reportDiagnostic)
{
if (ShouldBeLocalized(parameter.OriginalDefinition, containingPropertySymbolOpt?.OriginalDefinition, localizableStateAttributeSymbol, conditionalAttributeSymbol, systemConsoleSymbol, typesToIgnore) &&
lazyValueContentResult.Value != null)
@@ -126,7 +126,7 @@ void AnalyzeArgument(IParameterSymbol parameter, IPropertySymbol containingPrope
return;
}
- var stringLiteralValues = stringContentValue.LiteralValues.Select(l => (string)l);
+ var stringLiteralValues = stringContentValue.LiteralValues.Cast();
// FxCop compat: Do not fire if the literal value came from a default parameter value
if (stringContentValue.LiteralValues.Count == 1 &&
@@ -144,7 +144,7 @@ void AnalyzeArgument(IParameterSymbol parameter, IPropertySymbol containingPrope
}
// FxCop compat: Filter out xml string literals.
- var filteredStrings = stringLiteralValues.Where(literal => !LooksLikeXmlTag(literal));
+ IEnumerable filteredStrings = stringLiteralValues.Where(literal => literal != null && !LooksLikeXmlTag(literal))!;
if (filteredStrings.Any())
{
// Method '{0}' passes a literal string as parameter '{1}' of a call to '{2}'. Retrieve the following string(s) from a resource table instead: "{3}".
@@ -159,7 +159,7 @@ void AnalyzeArgument(IParameterSymbol parameter, IPropertySymbol containingPrope
}
}
- DataFlowAnalysisResult ComputeValueContentAnalysisResult()
+ DataFlowAnalysisResult? ComputeValueContentAnalysisResult()
{
var cfg = operationBlockStartContext.OperationBlocks.GetControlFlowGraph();
if (cfg != null)
@@ -214,10 +214,10 @@ private static ImmutableHashSet GetTypesToIgnore(Compilation c
private static bool ShouldBeLocalized(
IParameterSymbol parameterSymbol,
- IPropertySymbol containingPropertySymbolOpt,
- INamedTypeSymbol localizableStateAttributeSymbol,
- INamedTypeSymbol conditionalAttributeSymbol,
- INamedTypeSymbol systemConsoleSymbol,
+ IPropertySymbol? containingPropertySymbolOpt,
+ INamedTypeSymbol? localizableStateAttributeSymbol,
+ INamedTypeSymbol? conditionalAttributeSymbol,
+ INamedTypeSymbol? systemConsoleSymbol,
ImmutableHashSet typesToIgnore)
{
Debug.Assert(parameterSymbol.ContainingSymbol.Kind == SymbolKind.Method);
@@ -290,7 +290,6 @@ private static ImmutableHashSet GetTypesToIgnore(Compilation c
private static LocalizableAttributeState GetLocalizableAttributeState(ISymbol symbol, INamedTypeSymbol localizableAttributeTypeSymbol)
{
- Debug.Assert(localizableAttributeTypeSymbol != null);
if (symbol == null)
{
return LocalizableAttributeState.Undefined;
@@ -308,8 +307,6 @@ private static LocalizableAttributeState GetLocalizableAttributeState(ISymbol sy
private static LocalizableAttributeState GetLocalizableAttributeStateCore(ImmutableArray attributeList, INamedTypeSymbol localizableAttributeTypeSymbol)
{
- Debug.Assert(localizableAttributeTypeSymbol != null);
-
var localizableAttribute = attributeList.FirstOrDefault(attr => localizableAttributeTypeSymbol.Equals(attr.AttributeClass));
if (localizableAttribute != null &&
localizableAttribute.AttributeConstructor.Parameters.Length == 1 &&
@@ -360,10 +357,15 @@ private static bool LooksLikeXmlTag(string literal)
///