Skip to content

Commit

Permalink
Update Microsoft.CodeAnalysis.Analyzers to use Roslyn 3.7.0
Browse files Browse the repository at this point in the history
  • Loading branch information
sharwell committed Jun 22, 2023
1 parent 21a5c52 commit f9e4348
Show file tree
Hide file tree
Showing 33 changed files with 141 additions and 46 deletions.
3 changes: 3 additions & 0 deletions Directory.Build.props
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,9 @@
<!-- When building in source build mode, treat this set of warnings not as errors.-->
<!-- Some crefs reference internal APIs not present in the reference package. -->
<NoWarn>$(NoWarn);CS1574;CS8602</NoWarn>
<!-- Source build reference assemblies are not correctly annotated.
https://github.com/dotnet/source-build/issues/3531 -->
<NoWarn>$(NoWarn);CS8603</NoWarn>
</PropertyGroup>

<PropertyGroup>
Expand Down
2 changes: 1 addition & 1 deletion eng/Versions.props
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@
<MicrosoftCodeAnalysisVersionForResxSourceGenerators>4.0.1</MicrosoftCodeAnalysisVersionForResxSourceGenerators>
<MicrosoftCodeAnalysisVersionForNetAnalyzers>3.3.1</MicrosoftCodeAnalysisVersionForNetAnalyzers>
<MicrosoftCodeAnalysisVersionForTextAnalyzers>3.3.1</MicrosoftCodeAnalysisVersionForTextAnalyzers>
<MicrosoftCodeAnalysisVersionForCodeAnalysisAnalyzers>3.3.1</MicrosoftCodeAnalysisVersionForCodeAnalysisAnalyzers>
<MicrosoftCodeAnalysisVersionForCodeAnalysisAnalyzers>3.7.0</MicrosoftCodeAnalysisVersionForCodeAnalysisAnalyzers>
<MicrosoftCodeAnalysisVersionForToolsAndUtilities>3.3.1</MicrosoftCodeAnalysisVersionForToolsAndUtilities>
<!-- Versions for tests and general utility execution. -->
<!-- This version is for utility and executable assemblies. The version here should not overlap with any of the surface
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,9 @@ public sealed class CSharpPreferIsKindFix : PreferIsKindFix
protected override SyntaxNode? TryGetNodeToFix(SyntaxNode root, TextSpan span)
{
var binaryExpression = root.FindNode(span, getInnermostNodeForTie: true).FirstAncestorOrSelf<BinaryExpressionSyntax>();
if (binaryExpression is null)
return null;

if (binaryExpression.Left.IsKind(SyntaxKind.InvocationExpression) ||
binaryExpression.Left.IsKind(SyntaxKind.ConditionalAccessExpression))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
using Microsoft.CodeAnalysis.Analyzers.FixAnalyzers;
using Microsoft.CodeAnalysis.CodeActions;
Expand All @@ -28,7 +29,7 @@ public sealed override FixAllProvider GetFixAllProvider()

public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
SyntaxNode root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
SyntaxToken token = root.FindToken(context.Span.Start);
if (!token.Span.IntersectsWith(context.Span))
{
Expand All @@ -52,7 +53,7 @@ private static async Task<Document> AddMethodAsync(Document document, SyntaxNode
var editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false);
var generator = editor.Generator;

var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var model = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var typeIsSealed = ((INamedTypeSymbol)model.GetDeclaredSymbol(classDecl, cancellationToken)).IsSealed;

INamedTypeSymbol? codeFixProviderSymbol = model.Compilation.GetOrCreateTypeByMetadataName(FixerWithFixAllAnalyzer.CodeFixProviderMetadataName);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,7 @@ private static void AnalyzeSymbol(SymbolAnalysisContext context)
// We are doing a string comparison of the name here because we don't care where the attribute comes from.
// CodeAnalysis.dll itself has this attribute and if the user assembly also had it, symbol equality will fail
// but we should still issue the error.
if (attributes.Any(a => a.AttributeClass.Name.Equals(InternalImplementationOnlyAttributeName, StringComparison.Ordinal)
if (attributes.Any(a => a.AttributeClass is { Name: InternalImplementationOnlyAttributeName }
&& a.AttributeClass.ToDisplayString().Equals(InternalImplementationOnlyAttributeFullName, StringComparison.Ordinal)) &&
!iface.ContainingAssembly.GivesAccessTo(namedTypeSymbol.ContainingAssembly))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -271,7 +271,7 @@ private static bool IsSymbolType(IOperation? operation, INamedTypeSymbol? symbol
private static bool IsSymbolType(ITypeSymbol typeSymbol, INamedTypeSymbol? symbolType)
=> typeSymbol != null
&& (SymbolEqualityComparer.Default.Equals(typeSymbol, symbolType)
|| typeSymbol.AllInterfaces.Contains(symbolType));
|| typeSymbol.AllInterfaces.Any(SymbolEqualityComparer.Default.Equals, symbolType));

private static bool IsSymbolClassType(IOperation operation)
{
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.

using System.Collections.Immutable;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using Analyzer.Utilities;
using Analyzer.Utilities.Extensions;
Expand Down Expand Up @@ -146,6 +147,12 @@ private static bool IsRegisteredExtension(INamedTypeSymbol extension, [NotNullWh

foreach (var attribute in extension.GetAttributes())
{
// Only examine extension registrations in source
Debug.Assert(attribute.ApplicationSyntaxReference is not null,
$"Expected attributes returned by {nameof(ISymbol.GetAttributes)} (as opposed to {nameof(ITypeSymbolExtensions.GetApplicableAttributes)}) to have a non-null application.");
if (attribute.ApplicationSyntaxReference is null)
continue;

if (!attribute.AttributeClass.Inherits(registrationAttributeType))
continue;

Expand Down Expand Up @@ -173,7 +180,7 @@ private static void CheckLanguage(TypedConstant argument, ref bool supportsCShar
{
if (argument is { Kind: TypedConstantKind.Primitive, Type.SpecialType: SpecialType.System_String })
{
string supportedLanguage = (string)argument.Value;
var supportedLanguage = (string?)argument.Value;
if (supportedLanguage == LanguageNames.CSharp)
{
supportsCSharp = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -243,9 +243,9 @@ private ImmutableHashSet<INamedTypeSymbol> GetUsedNamedTypes(INamedTypeSymbol na
return builder.ToImmutableAndFree();
}

private static void AddUsedNamedTypeCore(ITypeSymbol typeOpt, PooledHashSet<INamedTypeSymbol> builder, ref bool hasAccessToTypeFromWorkspaceAssemblies)
private static void AddUsedNamedTypeCore(ITypeSymbol? type, PooledHashSet<INamedTypeSymbol> builder, ref bool hasAccessToTypeFromWorkspaceAssemblies)
{
if (typeOpt is INamedTypeSymbol usedType &&
if (type is INamedTypeSymbol usedType &&
usedType.TypeKind != TypeKind.Error)
{
builder.Add(usedType);
Expand All @@ -259,9 +259,9 @@ private static void AddUsedNamedTypeCore(ITypeSymbol typeOpt, PooledHashSet<INam

if (usedType.IsGenericType)
{
foreach (var type in usedType.TypeArguments)
foreach (var typeArgument in usedType.TypeArguments)
{
AddUsedNamedTypeCore(type, builder, ref hasAccessToTypeFromWorkspaceAssemblies);
AddUsedNamedTypeCore(typeArgument, builder, ref hasAccessToTypeFromWorkspaceAssemblies);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ private static void CheckLanguage(TypedConstant argument, ref bool supportsCShar
argument.Type != null &&
argument.Type.SpecialType == SpecialType.System_String)
{
string supportedLanguage = (string)argument.Value;
var supportedLanguage = (string?)argument.Value;
if (supportedLanguage == LanguageNames.CSharp)
{
supportsCSharp = true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ internal static IEnumerable<TClassDeclarationSyntax> GetClassDeclarationNodes(IN
{
if (syntax != null)
{
TClassDeclarationSyntax classDecl = syntax.FirstAncestorOrSelf<TClassDeclarationSyntax>(ascendOutOfTrivia: false);
TClassDeclarationSyntax? classDecl = syntax.FirstAncestorOrSelf<TClassDeclarationSyntax>(ascendOutOfTrivia: false);
if (classDecl != null)
{
yield return classDecl;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,7 @@ protected override void AnalyzeNode(SymbolAnalysisContext symbolContext, TFieldD

foreach (TTypeSyntax typeNode in typeNodes)
{
ITypeSymbol type = semanticModel.GetTypeInfo(typeNode, symbolContext.CancellationToken).Type;
ITypeSymbol? type = semanticModel.GetTypeInfo(typeNode, symbolContext.CancellationToken).Type;
if (type != null)
{
foreach (ITypeSymbol innerType in type.GetBaseTypesAndThis())
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -692,7 +692,8 @@ DiagnosticIds.DefineDiagnosticMessageCorrectlyRuleId or

filePath = null;
fileSpan = null;
if (!diagnostic.Properties.TryGetValue(DefineDescriptorArgumentCorrectlyFixAdditionalDocumentLocationInfo, out var locationInfo))
if (!diagnostic.Properties.TryGetValue(DefineDescriptorArgumentCorrectlyFixAdditionalDocumentLocationInfo, out var locationInfo)
|| locationInfo is null)
{
return false;
}
Expand Down Expand Up @@ -918,7 +919,7 @@ private static bool TryGetNonEmptyConstantStringValue(
if (fieldDeclaration.Language == LanguageNames.VisualBasic)
{
// For VB, the field initializer is on the parent node.
fieldDeclaration = fieldDeclaration.Parent;
fieldDeclaration = fieldDeclaration.Parent!;
}

foreach (var node in fieldDeclaration.DescendantNodes())
Expand Down Expand Up @@ -1279,7 +1280,7 @@ ConcurrentDictionary<string, ConcurrentBag<Location>> UpdateNamedTypeFactory(str
}
}

private static bool IsReservedDiagnosticId(string ruleId, string assemblyName)
private static bool IsReservedDiagnosticId(string ruleId, string? assemblyName)
{
if (ruleId.Length < 3)
{
Expand All @@ -1300,7 +1301,19 @@ private static bool IsReservedDiagnosticId(string ruleId, string assemblyName)
return false;
}

return !isCARule || !CADiagnosticIdAllowedAssemblies.Contains(assemblyName);
if (!isCARule)
{
// This is a reserved compiler diagnostic ID (CS or BC prefix)
return true;
}

if (assemblyName is null)
{
// This is a reserved code analysis ID (CA prefix) being reported from an unspecified assembly
return true;
}

return !CADiagnosticIdAllowedAssemblies.Contains(assemblyName);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,7 @@ private static bool TryParseCategoryAndAllowedIdsInfoFile(
invalidFileDiagnostics = null;

var builder = ImmutableDictionary.CreateBuilder<string, ImmutableArray<(string? prefix, int start, int end)>>();
var lines = additionalText.GetText(cancellationToken).Lines;
var lines = additionalText.GetTextOrEmpty(cancellationToken).Lines;
foreach (var line in lines)
{
var contents = line.ToString();
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -176,8 +176,8 @@ private static bool TryGetReleaseTrackingData(

var diagnostics = new List<Diagnostic>();
using var reportedInvalidLines = PooledHashSet<TextLine>.GetInstance();
shippedData = ReadReleaseTrackingData(shippedText.Path, shippedText.GetText(cancellationToken), OnDuplicateEntryInRelease, OnInvalidEntry, isShippedFile: true);
unshippedData = ReadReleaseTrackingData(unshippedText.Path, unshippedText.GetText(cancellationToken), OnDuplicateEntryInRelease, OnInvalidEntry, isShippedFile: false);
shippedData = ReadReleaseTrackingData(shippedText.Path, shippedText.GetTextOrEmpty(cancellationToken), OnDuplicateEntryInRelease, OnInvalidEntry, isShippedFile: true);
unshippedData = ReadReleaseTrackingData(unshippedText.Path, unshippedText.GetTextOrEmpty(cancellationToken), OnDuplicateEntryInRelease, OnInvalidEntry, isShippedFile: false);

invalidFileDiagnostics = diagnostics;
return invalidFileDiagnostics.Count == 0;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using System.Linq;
using System.Threading;
using System.Xml.Linq;
using Analyzer.Utilities.Extensions;
using Analyzer.Utilities.PooledObjects;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Text;
Expand Down Expand Up @@ -67,7 +68,7 @@ private static bool HasResxAdditionalFiles(AnalyzerOptions options)
const string valueTagPrefix = @"<value>";
const string valueTagSuffix = @"</value>";
var builder = ImmutableDictionary.CreateBuilder<string, (string value, Location location)>();
var sourceText = file.GetText(cancellationToken);
var sourceText = file.GetTextOrEmpty(cancellationToken);
var sourceTextStr = sourceText.ToString();
var parsedDocument = XDocument.Parse(sourceTextStr, LoadOptions.PreserveWhitespace);
foreach (var dataElement in parsedDocument.Descendants("data"))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@ public FixAllAdditionalDocumentChangeAction(FixAllScope fixAllScope, Solution so
public override string Title { get; }
public override string EquivalenceKey { get; }

protected override async Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken)
protected override async Task<Solution?> GetChangedSolutionAsync(CancellationToken cancellationToken)
{
var updatedUnshippedText = new List<(DocumentId, SourceText)>();

Expand Down Expand Up @@ -168,7 +168,7 @@ public FixAllAddAdditionalDocumentsAction(ImmutableArray<ProjectId> projectIds,
public override string Title => CodeAnalysisDiagnosticsResources.EnableAnalyzerReleaseTrackingRuleTitle;
public override string EquivalenceKey => CodeAnalysisDiagnosticsResources.EnableAnalyzerReleaseTrackingRuleTitle;

protected override async Task<Solution> GetChangedSolutionAsync(CancellationToken cancellationToken)
protected override async Task<Solution?> GetChangedSolutionAsync(CancellationToken cancellationToken)
{
var newSolution = _solution;
foreach (var projectId in _projectIds)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ private static bool IsAddEntryToUnshippedFileDiagnostic(Diagnostic diagnostic, [
{
if (diagnostic.Properties != null &&
diagnostic.Properties.TryGetValue(DiagnosticDescriptorCreationAnalyzer.EntryToAddPropertyName, out entryToAdd) &&
!string.IsNullOrEmpty(entryToAdd))
!RoslynString.IsNullOrEmpty(entryToAdd))
{
return true;
}
Expand All @@ -136,7 +136,7 @@ private static bool IsUpdateEntryToUnshippedFileDiagnostic(
{
if (diagnostic.Properties != null &&
diagnostic.Properties.TryGetValue(DiagnosticDescriptorCreationAnalyzer.EntryToUpdatePropertyName, out entryToUpdate) &&
!string.IsNullOrEmpty(entryToUpdate) &&
!RoslynString.IsNullOrEmpty(entryToUpdate) &&
TryGetRuleIdForEntry(entryToUpdate, out ruleId))
{
return true;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ public abstract class ApplyDiagnosticAnalyzerAttributeFix : CodeFixProvider

public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context)
{
SyntaxNode root = await context.Document.GetSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
SyntaxNode root = await context.Document.GetRequiredSyntaxRootAsync(context.CancellationToken).ConfigureAwait(false);
SyntaxToken token = root.FindToken(context.Span.Start);
if (!token.Span.IntersectsWith(context.Span))
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,8 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context)

private async Task<Document> ConvertToEqualsAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var expression = root.FindNode(sourceSpan, getInnermostNodeForTie: true);
var rawOperation = semanticModel.GetOperation(expression, cancellationToken);

Expand All @@ -72,8 +72,8 @@ private async Task<Document> ConvertToEqualsAsync(Document document, TextSpan so

private async Task<Document> CallOverloadWithEqualityComparerAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var expression = root.FindNode(sourceSpan, getInnermostNodeForTie: true);
var rawOperation = semanticModel.GetOperation(expression, cancellationToken);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,14 +39,14 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context)

private async Task<Document> ConfigureGeneratedCodeAnalysisAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken)
{
var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var semanticModel = await document.GetRequiredSemanticModelAsync(cancellationToken).ConfigureAwait(false);
var generatedCodeAnalysisFlags = semanticModel.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftCodeAnalysisDiagnosticsGeneratedCodeAnalysisFlags);
if (generatedCodeAnalysisFlags is null)
{
return document;
}

var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var root = await document.GetRequiredSyntaxRootAsync(cancellationToken).ConfigureAwait(false);
var analysisContextParameter = root.FindNode(sourceSpan, getInnermostNodeForTie: true);

var generator = SyntaxGenerator.GetGenerator(document);
Expand Down
Loading

0 comments on commit f9e4348

Please sign in to comment.