diff --git a/eng/Versions.props b/eng/Versions.props index 8b282448a2..43e903f320 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -21,6 +21,7 @@ 2.9.0 3.3.1-beta3-final + 2.9.6 2.9.5 3.0.0-beta2.19218.3+e96bad97 3.3.0-beta2-19376-02 diff --git a/src/BannedSymbols.txt b/src/BannedSymbols.txt new file mode 100644 index 0000000000..39851aa431 --- /dev/null +++ b/src/BannedSymbols.txt @@ -0,0 +1 @@ +M:Microsoft.CodeAnalysis.Compilation.GetTypeByMetadataName(System.String); Use WellKnownTypeProvider instead diff --git a/src/Directory.Build.targets b/src/Directory.Build.targets index 10418dc1c3..7c58598a92 100644 --- a/src/Directory.Build.targets +++ b/src/Directory.Build.targets @@ -20,6 +20,11 @@ + + + + + $(MSBuildAllProjects);$(MSBuildThisFileDirectory)..\build\Analyzers_ShippingRules.ruleset diff --git a/src/MetaCompilation.Analyzers/Core/CodeFixProvider.cs b/src/MetaCompilation.Analyzers/Core/CodeFixProvider.cs index 47496adfc6..6a676486ec 100644 --- a/src/MetaCompilation.Analyzers/Core/CodeFixProvider.cs +++ b/src/MetaCompilation.Analyzers/Core/CodeFixProvider.cs @@ -7,6 +7,8 @@ using System.Linq; using System.Threading; using System.Threading.Tasks; +using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; @@ -1183,7 +1185,7 @@ private async Task MissingInitAsync(Document document, ClassDeclaratio SemanticModel semanticModel = await document.GetSemanticModelAsync().ConfigureAwait(false); - INamedTypeSymbol notImplementedException = semanticModel.Compilation.GetTypeByMetadataName("System.NotImplementedException"); + INamedTypeSymbol notImplementedException = semanticModel.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNotImplementedException); SyntaxList statements = new SyntaxList(); string name = "context"; SyntaxNode initializeDeclaration = CodeFixHelper.BuildInitialize(generator, notImplementedException, statements, name); @@ -1553,7 +1555,7 @@ private async Task MissingAccessorAsync(Document document, PropertyDec SemanticModel semanticModel = await document.GetSemanticModelAsync().ConfigureAwait(false); - INamedTypeSymbol notImplementedException = semanticModel.Compilation.GetTypeByMetadataName("System.NotImplementedException"); + INamedTypeSymbol notImplementedException = semanticModel.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNotImplementedException); SyntaxNode[] throwStatement = new[] { generator.ThrowStatement(generator.ObjectCreationExpression(notImplementedException)) }; SyntaxNode type = generator.GetType(declaration); PropertyDeclarationSyntax newPropertyDeclaration = generator.PropertyDeclaration("SupportedDiagnostics", type, Accessibility.Public, DeclarationModifiers.Override, throwStatement) as PropertyDeclarationSyntax; @@ -1726,7 +1728,7 @@ private async Task AddSuppDiagAsync(Document document, ClassDeclaratio SyntaxGenerator generator = SyntaxGenerator.GetGenerator(document); SemanticModel semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - INamedTypeSymbol notImplementedException = semanticModel.Compilation.GetTypeByMetadataName("System.NotImplementedException"); + INamedTypeSymbol notImplementedException = semanticModel.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNotImplementedException); PropertyDeclarationSyntax propertyDeclaration = CodeFixHelper.CreateSupportedDiagnostics(generator, notImplementedException); var newNodes = new SyntaxList(); @@ -2379,7 +2381,7 @@ internal static SyntaxNode CreateAnalysisMethod(SyntaxGenerator generator, strin TypeSyntax type = SyntaxFactory.ParseTypeName("SyntaxNodeAnalysisContext"); SyntaxNode[] parameters = new[] { generator.ParameterDeclaration("context", type) }; SyntaxList statements = new SyntaxList(); - INamedTypeSymbol notImplementedException = semanticModel.Compilation.GetTypeByMetadataName("System.NotImplementedException"); + INamedTypeSymbol notImplementedException = semanticModel.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNotImplementedException); statements = statements.Add(generator.ThrowStatement(generator.ObjectCreationExpression(notImplementedException))); SyntaxNode newMethodDeclaration = generator.MethodDeclaration(methodName, parameters: parameters, accessibility: Accessibility.Private, statements: statements); diff --git a/src/MetaCompilation.Analyzers/Core/DiagnosticAnalyzer.cs b/src/MetaCompilation.Analyzers/Core/DiagnosticAnalyzer.cs index 25676d3b7f..7c7977b168 100644 --- a/src/MetaCompilation.Analyzers/Core/DiagnosticAnalyzer.cs +++ b/src/MetaCompilation.Analyzers/Core/DiagnosticAnalyzer.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.Collections.Immutable; using System.Linq; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -2607,7 +2608,7 @@ private bool CheckMethods(InvocationExpressionSyntax invocationExpression, Compi ReportDiagnostic(context, IncorrectAnalysisReturnTypeRule, analysisMethodSyntax.Identifier.GetLocation(), analysisMethodSyntax.Identifier.ValueText); return false; } - else if (analysisMethod.Parameters.Length != 1 || !Equals(analysisMethod.Parameters.First().Type, context.Compilation.GetTypeByMetadataName("Microsoft.CodeAnalysis.Diagnostics.SyntaxNodeAnalysisContext"))) + else if (analysisMethod.Parameters.Length != 1 || !Equals(analysisMethod.Parameters.First().Type, context.Compilation.GetOrCreateTypeByMetadataName("Microsoft.CodeAnalysis.Diagnostics.SyntaxNodeAnalysisContext"))) { ReportDiagnostic(context, IncorrectAnalysisParameterRule, analysisMethodSyntax.ParameterList.GetLocation(), analysisMethodSyntax.Identifier.ValueText); return false; @@ -2766,7 +2767,7 @@ private CheckInitializeInfo CheckInitialize(CompilationAnalysisContext context) private BlockSyntax InitializeOverview(CompilationAnalysisContext context) { ImmutableArray parameters = _initializeSymbol.Parameters; - if (parameters.Length != 1 || !Equals(parameters[0].Type, context.Compilation.GetTypeByMetadataName("Microsoft.CodeAnalysis.Diagnostics.AnalysisContext")) + if (parameters.Length != 1 || !Equals(parameters[0].Type, context.Compilation.GetOrCreateTypeByMetadataName("Microsoft.CodeAnalysis.Diagnostics.AnalysisContext")) || _initializeSymbol.DeclaredAccessibility != Accessibility.Public || !_initializeSymbol.IsOverride || !_initializeSymbol.ReturnsVoid) { ReportDiagnostic(context, IncorrectInitSigRule, _initializeSymbol.Locations[0], _initializeSymbol.Name); @@ -2866,9 +2867,9 @@ internal protected void AddMethod(SymbolAnalysisContext context) return; } - if (!Equals(sym.ContainingType.BaseType, context.Compilation.GetTypeByMetadataName("Microsoft.CodeAnalysis.Diagnostics.DiagnosticAnalyzer"))) + if (!Equals(sym.ContainingType.BaseType, context.Compilation.GetOrCreateTypeByMetadataName("Microsoft.CodeAnalysis.Diagnostics.DiagnosticAnalyzer"))) { - if (!Equals(sym.ContainingType.BaseType, context.Compilation.GetTypeByMetadataName("Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider"))) + if (!Equals(sym.ContainingType.BaseType, context.Compilation.GetOrCreateTypeByMetadataName("Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider"))) { return; } @@ -2918,9 +2919,9 @@ internal protected void AddProperty(SymbolAnalysisContext context) return; } - if (!Equals(sym.ContainingType.BaseType, context.Compilation.GetTypeByMetadataName("Microsoft.CodeAnalysis.Diagnostics.DiagnosticAnalyzer"))) + if (!Equals(sym.ContainingType.BaseType, context.Compilation.GetOrCreateTypeByMetadataName("Microsoft.CodeAnalysis.Diagnostics.DiagnosticAnalyzer"))) { - if (!Equals(sym.ContainingType.BaseType, context.Compilation.GetTypeByMetadataName("Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider"))) + if (!Equals(sym.ContainingType.BaseType, context.Compilation.GetOrCreateTypeByMetadataName("Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider"))) { return; } @@ -2967,7 +2968,7 @@ internal protected void AddField(SymbolAnalysisContext context) return; } - if (!Equals(sym.ContainingType.BaseType, context.Compilation.GetTypeByMetadataName("Microsoft.CodeAnalysis.Diagnostics.DiagnosticAnalyzer"))) + if (!Equals(sym.ContainingType.BaseType, context.Compilation.GetOrCreateTypeByMetadataName("Microsoft.CodeAnalysis.Diagnostics.DiagnosticAnalyzer"))) { return; } @@ -2995,7 +2996,7 @@ internal protected void AddClass(SymbolAnalysisContext context) return; } - if (!Equals(sym.BaseType, context.Compilation.GetTypeByMetadataName("Microsoft.CodeAnalysis.Diagnostics.DiagnosticAnalyzer"))) + if (!Equals(sym.BaseType, context.Compilation.GetOrCreateTypeByMetadataName("Microsoft.CodeAnalysis.Diagnostics.DiagnosticAnalyzer"))) { if (sym.ContainingType == null) { @@ -3007,7 +3008,7 @@ internal protected void AddClass(SymbolAnalysisContext context) return; } - if (Equals(sym.ContainingType.BaseType, context.Compilation.GetTypeByMetadataName("Microsoft.CodeAnalysis.Diagnostics.DiagnosticAnalyzer"))) + if (Equals(sym.ContainingType.BaseType, context.Compilation.GetOrCreateTypeByMetadataName("Microsoft.CodeAnalysis.Diagnostics.DiagnosticAnalyzer"))) { if (_otherAnalyzerClassSymbols.Contains(sym)) { @@ -3021,7 +3022,7 @@ internal protected void AddClass(SymbolAnalysisContext context) } } - if (Equals(sym.BaseType, context.Compilation.GetTypeByMetadataName("Microsoft.CodeAnalysis.Diagnostics.DiagnosticAnalyzer"))) + if (Equals(sym.BaseType, context.Compilation.GetOrCreateTypeByMetadataName("Microsoft.CodeAnalysis.Diagnostics.DiagnosticAnalyzer"))) { _analyzerClassSymbol = sym; } diff --git a/src/MetaCompilation.Analyzers/Core/MetaCompilation.Analyzers.csproj b/src/MetaCompilation.Analyzers/Core/MetaCompilation.Analyzers.csproj index b5e212d1d2..aea6868e7a 100644 --- a/src/MetaCompilation.Analyzers/Core/MetaCompilation.Analyzers.csproj +++ b/src/MetaCompilation.Analyzers/Core/MetaCompilation.Analyzers.csproj @@ -12,4 +12,5 @@ + diff --git a/src/Microsoft.CodeAnalysis.Analyzers/CSharp/CSharpImmutableObjectMethodAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/CSharp/CSharpImmutableObjectMethodAnalyzer.cs index df7585866a..1e020a0e51 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/CSharp/CSharpImmutableObjectMethodAnalyzer.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/CSharp/CSharpImmutableObjectMethodAnalyzer.cs @@ -50,11 +50,11 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(compilationContext => { - INamedTypeSymbol solutionSymbol = compilationContext.Compilation.GetTypeByMetadataName(SolutionFullName); - INamedTypeSymbol projectSymbol = compilationContext.Compilation.GetTypeByMetadataName(ProjectFullName); - INamedTypeSymbol documentSymbol = compilationContext.Compilation.GetTypeByMetadataName(DocumentFullName); - INamedTypeSymbol syntaxNodeSymbol = compilationContext.Compilation.GetTypeByMetadataName(SyntaxNodeFullName); - INamedTypeSymbol compilationSymbol = compilationContext.Compilation.GetTypeByMetadataName(CompilationFullName); + 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 diff --git a/src/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpRegisterActionAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpRegisterActionAnalyzer.cs index 237a83692f..61f823d81b 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpRegisterActionAnalyzer.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/CSharp/MetaAnalyzers/CSharpRegisterActionAnalyzer.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; @@ -22,8 +23,8 @@ public class CSharpRegisterActionAnalyzer : RegisterActionAnalyzer AddMethodAsync(Document document, SyntaxNode var model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); var typeIsSealed = ((INamedTypeSymbol)model.GetDeclaredSymbol(classDecl)).IsSealed; - INamedTypeSymbol codeFixProviderSymbol = model.Compilation.GetTypeByMetadataName(FixerWithFixAllAnalyzer.CodeFixProviderMetadataName); + INamedTypeSymbol codeFixProviderSymbol = model.Compilation.GetOrCreateTypeByMetadataName(FixerWithFixAllAnalyzer.CodeFixProviderMetadataName); IMethodSymbol getFixAllProviderMethod = codeFixProviderSymbol.GetMembers(FixerWithFixAllAnalyzer.GetFixAllProviderMethodName).OfType().First(); var returnStatement = generator.ReturnStatement(generator.MemberAccessExpression( generator.IdentifierName("WellKnownFixAllProviders"), "BatchFixer")); diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/FixAnalyzers/FixerWithFixAllAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/FixAnalyzers/FixerWithFixAllAnalyzer.cs index dc8aa7de5b..7f2bdea96b 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/FixAnalyzers/FixerWithFixAllAnalyzer.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/FixAnalyzers/FixerWithFixAllAnalyzer.cs @@ -86,7 +86,7 @@ private void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext con { context.CancellationToken.ThrowIfCancellationRequested(); - INamedTypeSymbol codeFixProviderSymbol = context.Compilation.GetTypeByMetadataName(CodeFixProviderMetadataName); + INamedTypeSymbol codeFixProviderSymbol = context.Compilation.GetOrCreateTypeByMetadataName(CodeFixProviderMetadataName); if (codeFixProviderSymbol == null) { return; @@ -98,7 +98,7 @@ private void CreateAnalyzerWithinCompilation(CompilationStartAnalysisContext con return; } - INamedTypeSymbol codeActionSymbol = context.Compilation.GetTypeByMetadataName(CodeActionMetadataName); + INamedTypeSymbol codeActionSymbol = context.Compilation.GetOrCreateTypeByMetadataName(CodeActionMetadataName); if (codeActionSymbol == null) { return; diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/CompareSymbolsCorrectlyAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/CompareSymbolsCorrectlyAnalyzer.cs index 6ecc1217d5..f065f316b6 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/CompareSymbolsCorrectlyAnalyzer.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/CompareSymbolsCorrectlyAnalyzer.cs @@ -41,7 +41,7 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(context => { var compilation = context.Compilation; - var symbolType = compilation.GetTypeByMetadataName(s_symbolTypeFullName); + var symbolType = compilation.GetOrCreateTypeByMetadataName(s_symbolTypeFullName); if (symbolType is null) { return; @@ -203,6 +203,6 @@ private static bool IsExplicitCastToObject(IOperation operation) } public static bool UseSymbolEqualityComparer(Compilation compilation) - => compilation.GetTypeByMetadataName(SymbolEqualityComparerName) is object; + => compilation.GetOrCreateTypeByMetadataName(SymbolEqualityComparerName) is object; } } diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ConfigureGeneratedCodeAnalysisAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ConfigureGeneratedCodeAnalysisAnalyzer.cs index d7ef6dd26f..50ac08ba23 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ConfigureGeneratedCodeAnalysisAnalyzer.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ConfigureGeneratedCodeAnalysisAnalyzer.cs @@ -4,6 +4,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; @@ -42,7 +43,7 @@ protected override DiagnosticAnalyzerSymbolAnalyzer GetDiagnosticAnalyzerSymbolA { var compilation = compilationContext.Compilation; - var analysisContext = compilation.GetTypeByMetadataName(AnalysisContextFullName); + var analysisContext = compilation.GetOrCreateTypeByMetadataName(AnalysisContextFullName); if (analysisContext is null) { return null; diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAPIUsageAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAPIUsageAnalyzer.cs index 410b1594fc..d3866f9b0c 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAPIUsageAnalyzer.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAPIUsageAnalyzer.cs @@ -57,13 +57,13 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(compilationStartContext => { - if (compilationStartContext.Compilation.GetTypeByMetadataName(CodeActionMetadataName) == null) + if (compilationStartContext.Compilation.GetOrCreateTypeByMetadataName(CodeActionMetadataName) == null) { // No reference to core Workspaces assembly. return; } - INamedTypeSymbol diagnosticAnalyzer = compilationStartContext.Compilation.GetTypeByMetadataName(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 5af63f6068..8c68ea2d08 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAttributeAnalyzer.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAttributeAnalyzer.cs @@ -133,7 +133,7 @@ protected override void AnalyzeDiagnosticAnalyzer(SymbolAnalysisContext symbolCo // then the analyzer is pretty likely a language-agnostic analyzer. Compilation compilation = symbolContext.Compilation; string compilationTypeNameToCheck = supportsCSharp ? CSharpCompilationFullName : BasicCompilationFullName; - INamedTypeSymbol compilationType = compilation.GetTypeByMetadataName(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.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerCorrectnessAnalyzer.cs index fcd6edd09b..7a7fd2f534 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerCorrectnessAnalyzer.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerCorrectnessAnalyzer.cs @@ -1,5 +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 Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers @@ -53,8 +54,8 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(compilationContext => { - INamedTypeSymbol diagnosticAnalyzer = compilationContext.Compilation.GetTypeByMetadataName(DiagnosticAnalyzerTypeFullName); - INamedTypeSymbol diagnosticAnalyzerAttribute = compilationContext.Compilation.GetTypeByMetadataName(DiagnosticAnalyzerAttributeFullName); + INamedTypeSymbol diagnosticAnalyzer = compilationContext.Compilation.GetOrCreateTypeByMetadataName(DiagnosticAnalyzerTypeFullName); + INamedTypeSymbol diagnosticAnalyzerAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(DiagnosticAnalyzerAttributeFullName); if (diagnosticAnalyzer == null || diagnosticAnalyzerAttribute == null) { diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerFieldsAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerFieldsAnalyzer.cs index 617b7cccb2..9f9b5f9aa3 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerFieldsAnalyzer.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerFieldsAnalyzer.cs @@ -48,19 +48,19 @@ protected override DiagnosticAnalyzerSymbolAnalyzer GetDiagnosticAnalyzerSymbolA { Compilation compilation = compilationContext.Compilation; - INamedTypeSymbol compilationType = compilation.GetTypeByMetadataName(s_compilationTypeFullName); + INamedTypeSymbol compilationType = compilation.GetOrCreateTypeByMetadataName(s_compilationTypeFullName); if (compilationType == null) { return null; } - INamedTypeSymbol symbolType = compilation.GetTypeByMetadataName(s_symbolTypeFullName); + INamedTypeSymbol symbolType = compilation.GetOrCreateTypeByMetadataName(s_symbolTypeFullName); if (symbolType == null) { return null; } - INamedTypeSymbol operationType = compilation.GetTypeByMetadataName(s_operationTypeFullName); + INamedTypeSymbol operationType = compilation.GetOrCreateTypeByMetadataName(s_operationTypeFullName); if (operationType == null) { return null; diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzer.cs index ac1da94afb..9c056ddb11 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzer.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticDescriptorCreationAnalyzer.cs @@ -9,6 +9,7 @@ using System.Linq; using System.Threading; using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.Text; @@ -139,7 +140,7 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(compilationContext => { - INamedTypeSymbol diagnosticDescriptorType = compilationContext.Compilation.GetTypeByMetadataName(DiagnosticAnalyzerCorrectnessAnalyzer.DiagnosticDescriptorFullName); + INamedTypeSymbol diagnosticDescriptorType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(DiagnosticAnalyzerCorrectnessAnalyzer.DiagnosticDescriptorFullName); if (diagnosticDescriptorType == null) { return; diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/EnableConcurrentExecutionAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/EnableConcurrentExecutionAnalyzer.cs index 601f25c22b..f0fbf74e17 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/EnableConcurrentExecutionAnalyzer.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/EnableConcurrentExecutionAnalyzer.cs @@ -4,6 +4,7 @@ using System.Diagnostics.CodeAnalysis; using System.Linq; using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; @@ -42,7 +43,7 @@ protected override DiagnosticAnalyzerSymbolAnalyzer GetDiagnosticAnalyzerSymbolA { var compilation = compilationContext.Compilation; - var analysisContext = compilation.GetTypeByMetadataName(AnalysisContextFullName); + var analysisContext = compilation.GetOrCreateTypeByMetadataName(AnalysisContextFullName); if (analysisContext is null) { return null; diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ConfigureGeneratedCodeAnalysisFix.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ConfigureGeneratedCodeAnalysisFix.cs index cf0750a1a9..cbecba1c17 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ConfigureGeneratedCodeAnalysisFix.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/Fixers/ConfigureGeneratedCodeAnalysisFix.cs @@ -6,6 +6,7 @@ using System.Threading; using System.Threading.Tasks; using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.Diagnostics; @@ -41,7 +42,7 @@ public override Task RegisterCodeFixesAsync(CodeFixContext context) private async Task ConfigureGeneratedCodeAnalysisAsync(Document document, TextSpan sourceSpan, CancellationToken cancellationToken) { var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - var generatedCodeAnalysisFlags = semanticModel.Compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftCodeAnalysisDiagnosticsGeneratedCodeAnalysisFlags); + var generatedCodeAnalysisFlags = semanticModel.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftCodeAnalysisDiagnosticsGeneratedCodeAnalysisFlags); if (generatedCodeAnalysisFlags is null) { return document; diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/RegisterActionAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/RegisterActionAnalyzer.cs index d8d4f1e3f7..1c63d764d6 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/RegisterActionAnalyzer.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/RegisterActionAnalyzer.cs @@ -7,6 +7,7 @@ using System.Linq; using System.Threading; using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers @@ -120,31 +121,31 @@ protected override DiagnosticAnalyzerSymbolAnalyzer GetDiagnosticAnalyzerSymbolA { Compilation compilation = compilationContext.Compilation; - INamedTypeSymbol analysisContext = compilation.GetTypeByMetadataName(AnalysisContextFullName); + INamedTypeSymbol analysisContext = compilation.GetOrCreateTypeByMetadataName(AnalysisContextFullName); if (analysisContext == null) { return null; } - INamedTypeSymbol compilationStartAnalysisContext = compilation.GetTypeByMetadataName(CompilationStartAnalysisContextFullName); + INamedTypeSymbol compilationStartAnalysisContext = compilation.GetOrCreateTypeByMetadataName(CompilationStartAnalysisContextFullName); if (compilationStartAnalysisContext == null) { return null; } - INamedTypeSymbol codeBlockStartAnalysisContext = compilation.GetTypeByMetadataName(CodeBlockStartAnalysisContextFullName); + INamedTypeSymbol codeBlockStartAnalysisContext = compilation.GetOrCreateTypeByMetadataName(CodeBlockStartAnalysisContextFullName); if (codeBlockStartAnalysisContext == null) { return null; } - INamedTypeSymbol operationBlockStartAnalysisContext = compilation.GetTypeByMetadataName(OperationBlockStartAnalysisContextFullName); + INamedTypeSymbol operationBlockStartAnalysisContext = compilation.GetOrCreateTypeByMetadataName(OperationBlockStartAnalysisContextFullName); if (operationBlockStartAnalysisContext == null) { return null; } - INamedTypeSymbol symbolKind = compilation.GetTypeByMetadataName(SymbolKindFullName); + INamedTypeSymbol symbolKind = compilation.GetOrCreateTypeByMetadataName(SymbolKindFullName); if (symbolKind == null) { return null; diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ReportDiagnosticAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ReportDiagnosticAnalyzer.cs index 099c6c35ea..f70bf8d2c4 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ReportDiagnosticAnalyzer.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/ReportDiagnosticAnalyzer.cs @@ -39,61 +39,61 @@ protected override DiagnosticAnalyzerSymbolAnalyzer GetDiagnosticAnalyzerSymbolA { Compilation compilation = compilationContext.Compilation; - INamedTypeSymbol compilationEndAnalysisContext = compilation.GetTypeByMetadataName(CompilationEndAnalysisContextFullName); + INamedTypeSymbol compilationEndAnalysisContext = compilation.GetOrCreateTypeByMetadataName(CompilationEndAnalysisContextFullName); if (compilationEndAnalysisContext == null) { return null; } - INamedTypeSymbol codeBlockAnalysisContext = compilation.GetTypeByMetadataName(CodeBlockAnalysisContextFullName); + INamedTypeSymbol codeBlockAnalysisContext = compilation.GetOrCreateTypeByMetadataName(CodeBlockAnalysisContextFullName); if (codeBlockAnalysisContext == null) { return null; } - INamedTypeSymbol operationBlockAnalysisContext = compilation.GetTypeByMetadataName(OperationBlockAnalysisContextFullName); + INamedTypeSymbol operationBlockAnalysisContext = compilation.GetOrCreateTypeByMetadataName(OperationBlockAnalysisContextFullName); if (operationBlockAnalysisContext == null) { return null; } - INamedTypeSymbol operationAnalysisContext = compilation.GetTypeByMetadataName(OperationAnalysisContextFullName); + INamedTypeSymbol operationAnalysisContext = compilation.GetOrCreateTypeByMetadataName(OperationAnalysisContextFullName); if (operationAnalysisContext == null) { return null; } - INamedTypeSymbol semanticModelAnalysisContext = compilation.GetTypeByMetadataName(SemanticModelAnalysisContextFullName); + INamedTypeSymbol semanticModelAnalysisContext = compilation.GetOrCreateTypeByMetadataName(SemanticModelAnalysisContextFullName); if (semanticModelAnalysisContext == null) { return null; } - INamedTypeSymbol symbolAnalysisContext = compilation.GetTypeByMetadataName(SymbolAnalysisContextFullName); + INamedTypeSymbol symbolAnalysisContext = compilation.GetOrCreateTypeByMetadataName(SymbolAnalysisContextFullName); if (symbolAnalysisContext == null) { return null; } - INamedTypeSymbol syntaxNodeAnalysisContext = compilation.GetTypeByMetadataName(SyntaxNodeAnalysisContextFullName); + INamedTypeSymbol syntaxNodeAnalysisContext = compilation.GetOrCreateTypeByMetadataName(SyntaxNodeAnalysisContextFullName); if (syntaxNodeAnalysisContext == null) { return null; } - INamedTypeSymbol syntaxTreeAnalysisContext = compilation.GetTypeByMetadataName(SyntaxTreeAnalysisContextFullName); + INamedTypeSymbol syntaxTreeAnalysisContext = compilation.GetOrCreateTypeByMetadataName(SyntaxTreeAnalysisContextFullName); if (syntaxTreeAnalysisContext == null) { return null; } - INamedTypeSymbol diagnosticType = compilation.GetTypeByMetadataName(DiagnosticFullName); + INamedTypeSymbol diagnosticType = compilation.GetOrCreateTypeByMetadataName(DiagnosticFullName); if (diagnosticType == null) { return null; } - INamedTypeSymbol diagnosticDescriptorType = compilation.GetTypeByMetadataName(DiagnosticDescriptorFullName); + INamedTypeSymbol diagnosticDescriptorType = compilation.GetOrCreateTypeByMetadataName(DiagnosticDescriptorFullName); if (diagnosticDescriptorType == null) { return null; diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/UpgradeMSBuildWorkspaceAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/UpgradeMSBuildWorkspaceAnalyzer.cs index b615912e10..440020edb7 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/UpgradeMSBuildWorkspaceAnalyzer.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/UpgradeMSBuildWorkspaceAnalyzer.cs @@ -2,6 +2,7 @@ using System.Collections.Immutable; using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.Analyzers @@ -94,7 +95,7 @@ private void AnalyzeAssemblyReferences(CompilationStartAnalysisContext context) } // If this compilation contains the type, Microsoft.CodeAnalysis.MSBuild.MSBuildWorkspace, we're done. - var msbuildWorkspace = context.Compilation.GetTypeByMetadataName(MSBuildWorkspaceFullName); + var msbuildWorkspace = context.Compilation.GetOrCreateTypeByMetadataName(MSBuildWorkspaceFullName); if (msbuildWorkspace != null) { return; diff --git a/src/Microsoft.CodeAnalysis.Analyzers/VisualBasic/MetaAnalyzers/BasicRegisterActionAnalyzer.vb b/src/Microsoft.CodeAnalysis.Analyzers/VisualBasic/MetaAnalyzers/BasicRegisterActionAnalyzer.vb index 1c368651a5..caabbb3474 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/VisualBasic/MetaAnalyzers/BasicRegisterActionAnalyzer.vb +++ b/src/Microsoft.CodeAnalysis.Analyzers/VisualBasic/MetaAnalyzers/BasicRegisterActionAnalyzer.vb @@ -1,5 +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. +Imports Analyzer.Utilities.Extensions Imports Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Syntax @@ -18,8 +19,8 @@ Namespace Microsoft.CodeAnalysis.VisualBasic.Analyzers.MetaAnalyzers codeBlockStartAnalysisContext As INamedTypeSymbol, operationBlockStartAnalysisContext As INamedTypeSymbol, symbolKind As INamedTypeSymbol) As RegisterActionCodeBlockAnalyzer - Dim basicSyntaxKind = compilation.GetTypeByMetadataName(BasicSyntaxKindFullName) - Dim csharpSyntaxKind = compilation.GetTypeByMetadataName(CSharpSyntaxKindFullName) + Dim basicSyntaxKind = compilation.GetOrCreateTypeByMetadataName(BasicSyntaxKindFullName) + Dim csharpSyntaxKind = compilation.GetOrCreateTypeByMetadataName(CSharpSyntaxKindFullName) Return New BasicRegisterActionCodeBlockAnalyzer(basicSyntaxKind, csharpSyntaxKind, analysisContext, compilationStartAnalysisContext, codeBlockStartAnalysisContext, operationBlockStartAnalysisContext, symbolKind) End Function diff --git a/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/RestrictedInternalsVisibleToAnalyzer.cs b/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/RestrictedInternalsVisibleToAnalyzer.cs index 5fb03deaa2..1b030a97e4 100644 --- a/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/RestrictedInternalsVisibleToAnalyzer.cs +++ b/src/Microsoft.CodeAnalysis.BannedApiAnalyzers/Core/RestrictedInternalsVisibleToAnalyzer.cs @@ -108,7 +108,7 @@ private void OnCompilationStart(CompilationStartAnalysisContext compilationConte private static ImmutableDictionary> GetRestrictedInternalsVisibleToMap(Compilation compilation) { - var restrictedInternalsVisibleToAttribute = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeCompilerServicesRestrictedInternalsVisibleToAttribute); + var restrictedInternalsVisibleToAttribute = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeCompilerServicesRestrictedInternalsVisibleToAttribute); if (restrictedInternalsVisibleToAttribute == null) { return ImmutableDictionary>.Empty; diff --git a/src/Microsoft.CodeQuality.Analyzers/CSharp/QualityGuidelines/CSharpRemoveEmptyFinalizersAnalyzer.cs b/src/Microsoft.CodeQuality.Analyzers/CSharp/QualityGuidelines/CSharpRemoveEmptyFinalizersAnalyzer.cs index e978a93d84..865bb6ded0 100644 --- a/src/Microsoft.CodeQuality.Analyzers/CSharp/QualityGuidelines/CSharpRemoveEmptyFinalizersAnalyzer.cs +++ b/src/Microsoft.CodeQuality.Analyzers/CSharp/QualityGuidelines/CSharpRemoveEmptyFinalizersAnalyzer.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 Analyzer.Utilities; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -81,7 +82,7 @@ private static bool IsConditionalInvocation(InvocationExpressionSyntax invocatio return false; } - var conditionalAttributeSymbol = semanticModel.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemDiagnosticsConditionalAttribute); + var conditionalAttributeSymbol = semanticModel.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDiagnosticsConditionalAttribute); return InvocationIsConditional(invocationSymbol, conditionalAttributeSymbol); } } diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/CancellationTokenParametersMustComeLast.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/CancellationTokenParametersMustComeLast.cs index 2baeb51abe..3e8ef8cc4f 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.GetTypeByMetadataName(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 9da14daff3..e878e0df8b 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.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsICollection); - INamedTypeSymbol genericICollectionType = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericICollection1); + 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.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationDataMemberAttribute); + INamedTypeSymbol dataMemberAttribute = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationDataMemberAttribute); ImmutableHashSet immutableInterfaces = GetIImmutableInterfaces(context.Compilation); if (iCollectionType == null || @@ -139,11 +139,11 @@ private static bool Inherits(ITypeSymbol symbol, ITypeSymbol baseType) private static ImmutableHashSet GetIImmutableInterfaces(Compilation compilation) { var builder = ImmutableHashSet.CreateBuilder(); - AddIfNotNull(compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsImmutableIImmutableDictionary)); - AddIfNotNull(compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsImmutableIImmutableList)); - AddIfNotNull(compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsImmutableIImmutableQueue)); - AddIfNotNull(compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsImmutableIImmutableSet)); - AddIfNotNull(compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsImmutableIImmutableStack)); + AddIfNotNull(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsImmutableIImmutableDictionary)); + AddIfNotNull(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsImmutableIImmutableList)); + AddIfNotNull(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsImmutableIImmutableQueue)); + AddIfNotNull(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsImmutableIImmutableSet)); + AddIfNotNull(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsImmutableIImmutableStack)); return builder.ToImmutable(); // Local functions. diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/CollectionsShouldImplementGenericInterface.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/CollectionsShouldImplementGenericInterface.cs index c7c3123985..fbb7fa68fb 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/CollectionsShouldImplementGenericInterface.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/CollectionsShouldImplementGenericInterface.cs @@ -58,12 +58,12 @@ public override void Initialize(AnalysisContext analysisContext) analysisContext.RegisterCompilationStartAction( (context) => { - INamedTypeSymbol iCollectionType = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsICollection); - INamedTypeSymbol genericICollectionType = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericICollection1); - INamedTypeSymbol iEnumerableType = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsIEnumerable); - INamedTypeSymbol genericIEnumerableType = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericIEnumerable1); - INamedTypeSymbol iListType = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsIList); - INamedTypeSymbol genericIListType = context.Compilation.GetTypeByMetadataName(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 && diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DefineAccessorsForAttributeArguments.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DefineAccessorsForAttributeArguments.cs index 02157f8095..630ad117fa 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DefineAccessorsForAttributeArguments.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DefineAccessorsForAttributeArguments.cs @@ -65,7 +65,7 @@ public override void Initialize(AnalysisContext analysisContext) analysisContext.RegisterCompilationStartAction(compilationContext => { - INamedTypeSymbol attributeType = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemAttribute); + INamedTypeSymbol attributeType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemAttribute); if (attributeType == null) { return; diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DoNotDirectlyAwaitATask.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DoNotDirectlyAwaitATask.cs index a2f4e368df..d92f84d864 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DoNotDirectlyAwaitATask.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DoNotDirectlyAwaitATask.cs @@ -90,8 +90,8 @@ private static void AnalyzeOperation(OperationAnalysisContext context, Immutable private static ImmutableArray GetTaskTypes(Compilation compilation) { - INamedTypeSymbol taskType = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTask); - INamedTypeSymbol taskOfTType = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksGenericTask); + INamedTypeSymbol taskType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTask); + INamedTypeSymbol taskOfTType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksGenericTask); return ImmutableArray.Create(taskType, taskOfTType); } diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DoNotRaiseExceptionsInUnexpectedLocations.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DoNotRaiseExceptionsInUnexpectedLocations.cs index f9dbe66ce3..d14ae34451 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DoNotRaiseExceptionsInUnexpectedLocations.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/DoNotRaiseExceptionsInUnexpectedLocations.cs @@ -293,7 +293,7 @@ private static bool IsGetHashCodeInterfaceImplementation(IMethodSymbol method, C } - INamedTypeSymbol iHashCodeProvider = compilation.GetTypeByMetadataName(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.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumStorageShouldBeInt32.cs index 3955be65c4..eb80776473 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.GetTypeByMetadataName(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 e9b8238772..4a6710060b 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumWithFlagsAttribute.Fixer.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumWithFlagsAttribute.Fixer.cs @@ -8,6 +8,7 @@ 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; @@ -29,7 +30,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) { SemanticModel model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); - INamedTypeSymbol flagsAttributeType = model.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemFlagsAttribute); + INamedTypeSymbol flagsAttributeType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemFlagsAttribute); if (flagsAttributeType == null) { return; diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumWithFlagsAttribute.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumWithFlagsAttribute.cs index 8250ab6fa7..dc8e7ed6a1 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumWithFlagsAttribute.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumWithFlagsAttribute.cs @@ -70,7 +70,7 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(compilationStartContext => { - var flagsAttributeType = compilationStartContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemFlagsAttribute); + var flagsAttributeType = compilationStartContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemFlagsAttribute); if (flagsAttributeType == null) { return; diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumsShouldHavePluralNames.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumsShouldHavePluralNames.cs index 036a144bfc..a3590b361a 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.GetTypeByMetadataName(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 ddeaeccdf3..abd32ab12c 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumsShouldHaveZeroValue.Fixer.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumsShouldHaveZeroValue.Fixer.cs @@ -26,7 +26,7 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) { SemanticModel model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); - INamedTypeSymbol flagsAttributeType = model.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemFlagsAttribute); + INamedTypeSymbol flagsAttributeType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemFlagsAttribute); if (flagsAttributeType == null) { return; diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumsShouldHaveZeroValue.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/EnumsShouldHaveZeroValue.cs index 500a394cbc..00c81ca350 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.GetTypeByMetadataName(WellKnownTypeNames.SystemFlagsAttribute); + INamedTypeSymbol flagsAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemFlagsAttribute); if (flagsAttribute == null) { return; diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ExceptionsShouldBePublic.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ExceptionsShouldBePublic.cs index 100fbd9914..8d96d31fb6 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ExceptionsShouldBePublic.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ExceptionsShouldBePublic.cs @@ -54,7 +54,7 @@ private static void AnalyzeCompilationStart(CompilationStartAnalysisContext csCo { // Get named type symbols for targetted exception types ImmutableHashSet exceptionTypes = s_exceptionTypeNames - .Select(name => csContext.Compilation.GetTypeByMetadataName(name)) + .Select(name => csContext.Compilation.GetOrCreateTypeByMetadataName(name)) .Where(t => t != null) .ToImmutableHashSet(); diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/IdentifiersShouldHaveCorrectSuffix.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/IdentifiersShouldHaveCorrectSuffix.cs index 3852f2b227..041ea0aeee 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/IdentifiersShouldHaveCorrectSuffix.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/IdentifiersShouldHaveCorrectSuffix.cs @@ -85,7 +85,7 @@ private static void AnalyzeCompilationStart(CompilationStartAnalysisContext cont foreach (var (typeName, suffix, canSuffixBeCollection) in s_baseTypesAndTheirSuffix) { - var wellKnownNamedType = context.Compilation.GetTypeByMetadataName(typeName); + var wellKnownNamedType = context.Compilation.GetOrCreateTypeByMetadataName(typeName); if (wellKnownNamedType != null && wellKnownNamedType.OriginalDefinition != null) { @@ -146,7 +146,7 @@ private static void AnalyzeCompilationStart(CompilationStartAnalysisContext cont } , SymbolKind.NamedType); - var eventArgsType = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemEventArgs); + var eventArgsType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemEventArgs); if (eventArgsType != null) { context.RegisterSymbolAction((saContext) => diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/IdentifiersShouldNotHaveIncorrectSuffix.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/IdentifiersShouldNotHaveIncorrectSuffix.cs index f60b7b1c32..4328c56d7f 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/IdentifiersShouldNotHaveIncorrectSuffix.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/IdentifiersShouldNotHaveIncorrectSuffix.cs @@ -130,7 +130,7 @@ public override void Initialize(AnalysisContext analysisContext) ImmutableArray typeNames = s_suffixToBaseTypeNamesDictionary[suffix]; ImmutableArray namedTypeSymbolArray = ImmutableArray.CreateRange( - typeNames.Select(typeName => compilationStartAnalysisContext.Compilation.GetTypeByMetadataName(typeName)?.OriginalDefinition).WhereNotNull()); + typeNames.Select(typeName => compilationStartAnalysisContext.Compilation.GetOrCreateTypeByMetadataName(typeName)?.OriginalDefinition).WhereNotNull()); suffixToBaseTypeDictionaryBuilder.Add(suffix, namedTypeSymbolArray); } diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ImplementIDisposableCorrectly.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ImplementIDisposableCorrectly.cs index e4a1c4bdd2..df7a9f6699 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ImplementIDisposableCorrectly.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ImplementIDisposableCorrectly.cs @@ -140,7 +140,7 @@ public override void Initialize(AnalysisContext analysisContext) return; } - INamedTypeSymbol garbageCollectorType = context.Compilation.GetTypeByMetadataName(GarbageCollectorTypeName); + INamedTypeSymbol garbageCollectorType = context.Compilation.GetOrCreateTypeByMetadataName(GarbageCollectorTypeName); if (garbageCollectorType == null) { return; diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ImplementStandardExceptionConstructors.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ImplementStandardExceptionConstructors.cs index ae0f08c79c..fc5ac15fd8 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ImplementStandardExceptionConstructors.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ImplementStandardExceptionConstructors.cs @@ -62,7 +62,7 @@ public override void Initialize(AnalysisContext analysisContext) private void AnalyzeCompilationSymbol(CompilationStartAnalysisContext context) { - var exceptionType = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemException); + var exceptionType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemException); if (exceptionType == null) { return; diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/MarkAssembliesWithAttributesDiagnosticAnalyzer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/MarkAssembliesWithAttributesDiagnosticAnalyzer.cs index acc0fae333..a6bdc0c07c 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/MarkAssembliesWithAttributesDiagnosticAnalyzer.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/MarkAssembliesWithAttributesDiagnosticAnalyzer.cs @@ -51,8 +51,8 @@ public override void Initialize(AnalysisContext analysisContext) private static void AnalyzeCompilation(CompilationAnalysisContext context) { - var assemblyVersionAttributeSymbol = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemReflectionAssemblyVersionAttribute); - var assemblyComplianceAttributeSymbol = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCLSCompliantAttribute); + var assemblyVersionAttributeSymbol = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemReflectionAssemblyVersionAttribute); + var assemblyComplianceAttributeSymbol = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCLSCompliantAttribute); if (assemblyVersionAttributeSymbol == null && assemblyComplianceAttributeSymbol == null) { @@ -61,7 +61,7 @@ private static void AnalyzeCompilation(CompilationAnalysisContext context) bool assemblyVersionAttributeFound = false; bool assemblyComplianceAttributeFound = false; - var razorCompiledItemAttribute = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftAspNetCoreRazorHostingRazorCompiledItemAttribute); + var razorCompiledItemAttribute = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftAspNetCoreRazorHostingRazorCompiledItemAttribute); // Check all assembly level attributes for the target attribute foreach (AttributeData attribute in context.Compilation.Assembly.GetAttributes()) diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/MarkAssembliesWithComVisible.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/MarkAssembliesWithComVisible.cs index 80e8339b43..1ab262fd8e 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/MarkAssembliesWithComVisible.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/MarkAssembliesWithComVisible.cs @@ -53,7 +53,7 @@ private static void AnalyzeCompilation(CompilationAnalysisContext context) { if (AssemblyHasPublicTypes(context.Compilation.Assembly)) { - INamedTypeSymbol comVisibleAttributeSymbol = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesComVisibleAttribute); + INamedTypeSymbol comVisibleAttributeSymbol = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesComVisibleAttribute); if (comVisibleAttributeSymbol == null) { return; diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/MarkAttributesWithAttributeUsage.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/MarkAttributesWithAttributeUsage.cs index ee672ee03a..9e00f90688 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.GetTypeByMetadataName(WellKnownTypeNames.SystemAttribute); - INamedTypeSymbol attributeUsageAttributeType = compilationContext.Compilation.GetTypeByMetadataName(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 9174f66f01..c989cb0efd 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/NestedTypesShouldNotBeVisible.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/NestedTypesShouldNotBeVisible.cs @@ -58,9 +58,9 @@ public override void Initialize(AnalysisContext analysisContext) Compilation compilation = compilationStartContext.Compilation; INamedTypeSymbol enumeratorType = compilation.GetSpecialType(SpecialType.System_Collections_IEnumerator); - INamedTypeSymbol dataSetType = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemDataDataSet); - INamedTypeSymbol dataTableType = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemDataDataTable); - INamedTypeSymbol dataRowType = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemDataDataRow); + INamedTypeSymbol dataSetType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataDataSet); + INamedTypeSymbol dataTableType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataDataTable); + INamedTypeSymbol dataRowType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataDataRow); compilationStartContext.RegisterSymbolAction( symbolAnalysisContext => diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideEqualsAndOperatorEqualsOnValueTypes.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideEqualsAndOperatorEqualsOnValueTypes.cs index d7da259a50..0c73f741e4 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideEqualsAndOperatorEqualsOnValueTypes.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideEqualsAndOperatorEqualsOnValueTypes.cs @@ -54,8 +54,8 @@ public override void Initialize(AnalysisContext analysisContext) analysisContext.RegisterCompilationStartAction(compilationStartContext => { - var iEnumerator = compilationStartContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsIEnumerator); - var genericIEnumerator = compilationStartContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericIEnumerator1); + var iEnumerator = compilationStartContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsIEnumerator); + var genericIEnumerator = compilationStartContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericIEnumerator1); compilationStartContext.RegisterSymbolAction(context => { diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideMethodsOnComparableTypes.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/OverrideMethodsOnComparableTypes.cs index 32fa22ccca..2a1c80aca0 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.GetTypeByMetadataName(WellKnownTypeNames.SystemIComparable); - INamedTypeSymbol genericComparableType = compilationContext.Compilation.GetTypeByMetadataName(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) diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ProvideObsoleteAttributeMessage.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/ProvideObsoleteAttributeMessage.cs index 4634635286..41beae89c7 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.GetTypeByMetadataName(WellKnownTypeNames.SystemObsoleteAttribute); + INamedTypeSymbol obsoleteAttributeType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemObsoleteAttribute); if (obsoleteAttributeType == null) { return; diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/UriParametersShouldNotBeStrings.Fixer.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/UriParametersShouldNotBeStrings.Fixer.cs index 3b0b2171e7..017d2374e2 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/UriParametersShouldNotBeStrings.Fixer.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/UriParametersShouldNotBeStrings.Fixer.cs @@ -6,6 +6,7 @@ using System.Threading; using System.Threading.Tasks; using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; @@ -38,7 +39,7 @@ public sealed override async Task RegisterCodeFixesAsync(CodeFixContext context) SemanticModel model = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - INamedTypeSymbol uriType = model.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemUri); + INamedTypeSymbol uriType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemUri); if (uriType == null) { return; diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/UseGenericEventHandlerInstances.cs b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/UseGenericEventHandlerInstances.cs index cf630cec68..b59920cdcc 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/UseGenericEventHandlerInstances.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/ApiDesignGuidelines/UseGenericEventHandlerInstances.cs @@ -77,14 +77,14 @@ public override void Initialize(AnalysisContext analysisContext) analysisContext.RegisterCompilationStartAction( (context) => { - INamedTypeSymbol eventArgs = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemEventArgs); + INamedTypeSymbol eventArgs = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemEventArgs); if (eventArgs == null) { return; } // Only analyze compilations that have a generic event handler defined. - if (context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemEventHandler1) == null) + if (context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemEventHandler1) == null) { return; } @@ -133,9 +133,7 @@ bool IsValidNonGenericEventHandler(IMethodSymbol delegateInvokeMethod) } }, SymbolKind.NamedType); -#pragma warning disable CS0618 // Type or member is obsolete - INamedTypeSymbol comSourceInterfacesAttribute = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesComSourceInterfacesAttribute); -#pragma warning restore CS0618 // Type or member is obsolete + 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/AvoidUninstantiatedInternalClasses.cs b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/AvoidUninstantiatedInternalClasses.cs index 5047f83d58..c597860b7d 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/AvoidUninstantiatedInternalClasses.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/AvoidUninstantiatedInternalClasses.cs @@ -57,19 +57,19 @@ public override void Initialize(AnalysisContext analysisContext) // better to have false negatives (which would happen if the type were *not* // instantiated by any friend assembly, but we didn't report the issue) than // to have false positives. - var internalsVisibleToAttributeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeCompilerServicesInternalsVisibleToAttribute); + var internalsVisibleToAttributeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeCompilerServicesInternalsVisibleToAttribute); if (AssemblyExposesInternals(compilation, internalsVisibleToAttributeSymbol)) { return; } - var systemAttributeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemAttribute); - var iConfigurationSectionHandlerSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemConfigurationIConfigurationSectionHandler); - var configurationSectionSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemConfigurationConfigurationSection); - var safeHandleSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesSafeHandle); - var traceListenerSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemDiagnosticsTraceListener); - var mef1ExportAttributeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionExportAttribute); - var mef2ExportAttributeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCompositionExportAttribute); + var systemAttributeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemAttribute); + var iConfigurationSectionHandlerSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemConfigurationIConfigurationSectionHandler); + var configurationSectionSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemConfigurationConfigurationSection); + var safeHandleSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesSafeHandle); + var traceListenerSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDiagnosticsTraceListener); + var mef1ExportAttributeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionExportAttribute); + var mef2ExportAttributeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCompositionExportAttribute); startContext.RegisterOperationAction(context => { @@ -318,7 +318,7 @@ private static bool ContainsEntryPoint(INamedTypeSymbol type, Compilation compil } var taskSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTask); - var genericTaskSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksGenericTask); + var genericTaskSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksGenericTask); // TODO: Handle the case where Compilation.Options.MainTypeName matches this type. // TODO: Test: can't have type parameters. diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/AvoidUnusedPrivateFields.cs b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/AvoidUnusedPrivateFields.cs index 6ce16c5116..3367b68603 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/AvoidUnusedPrivateFields.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/AvoidUnusedPrivateFields.cs @@ -3,6 +3,7 @@ using System.Collections.Concurrent; using System.Collections.Immutable; using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; using Analyzer.Utilities.PooledObjects; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; @@ -49,7 +50,7 @@ public override void Initialize(AnalysisContext analysisContext) ConcurrentDictionary referencedPrivateFields = new ConcurrentDictionary(); ImmutableHashSet specialAttributes = GetSpecialAttributes(compilationContext.Compilation); - var structLayoutAttribute = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesStructLayoutAttribute); + var structLayoutAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesStructLayoutAttribute); compilationContext.RegisterSymbolAction( (symbolContext) => @@ -132,19 +133,19 @@ private static ImmutableHashSet GetSpecialAttributes(Compilati { var specialAttributes = PooledHashSet.GetInstance(); - var fieldOffsetAttribute = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesFieldOffsetAttribute); + var fieldOffsetAttribute = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesFieldOffsetAttribute); if (fieldOffsetAttribute != null) { specialAttributes.Add(fieldOffsetAttribute); } - var mefV1Attribute = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionExportAttribute); + var mefV1Attribute = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionExportAttribute); if (mefV1Attribute != null) { specialAttributes.Add(mefV1Attribute); } - var mefV2Attribute = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCompositionExportAttribute); + var mefV2Attribute = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCompositionExportAttribute); if (mefV2Attribute != null) { specialAttributes.Add(mefV2Attribute); diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/DoNotIgnoreMethodResults.cs b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/DoNotIgnoreMethodResults.cs index b96e8658c1..4251d7a205 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.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingExpectedExceptionAttribute); - INamedTypeSymbol nunitAssertType = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.NUnitFrameworkAssert); - INamedTypeSymbol xunitAssertType = compilationContext.Compilation.GetTypeByMetadataName(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 => { @@ -319,7 +319,7 @@ private static bool IsHResultOrErrorCodeReturningMethod(IMethodSymbol method) private static bool IsPureMethod(IMethodSymbol method, Compilation compilation) { - return method.GetAttributes().Any(attr => attr.AttributeClass.Equals(compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemDiagnosticsContractsPureAttribute))); + return method.GetAttributes().Any(attr => attr.AttributeClass.Equals(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDiagnosticsContractsPureAttribute))); } } } \ No newline at end of file diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/ReviewUnusedParameters.cs b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/ReviewUnusedParameters.cs index 7a7228f689..ec9816f7f8 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/ReviewUnusedParameters.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/Maintainability/ReviewUnusedParameters.cs @@ -50,17 +50,17 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(compilationStartContext => { - INamedTypeSymbol eventsArgSymbol = compilationStartContext.Compilation.GetTypeByMetadataName(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.GetTypeByMetadataName(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.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationOnDeserializingAttribute); - INamedTypeSymbol onDeserializedAttribute = compilationStartContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationOnDeserializedAttribute); - INamedTypeSymbol onSerializingAttribute = compilationStartContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationOnSerializingAttribute); - INamedTypeSymbol onSerializedAttribute = compilationStartContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationOnSerializedAttribute); - INamedTypeSymbol obsoleteAttribute = compilationStartContext.Compilation.GetTypeByMetadataName(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( conditionalAttributeSymbol, diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/DoNotCallOverridableMethodsInConstructors.cs b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/DoNotCallOverridableMethodsInConstructors.cs index f54b3ac29a..851e36751c 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.GetTypeByMetadataName(WellKnownTypeNames.SystemWebUIControl); - INamedTypeSymbol componentModelComponentType = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemComponentModelComponent); + INamedTypeSymbol webUiControlType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemWebUIControl); + INamedTypeSymbol componentModelComponentType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemComponentModelComponent); compilationContext.RegisterOperationBlockStartAction(context => { diff --git a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/MarkMembersAsStatic.cs b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/MarkMembersAsStatic.cs index a975c9ded7..a862d98084 100644 --- a/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/MarkMembersAsStatic.cs +++ b/src/Microsoft.CodeQuality.Analyzers/Core/QualityGuidelines/MarkMembersAsStatic.cs @@ -192,7 +192,7 @@ private static bool ShouldAnalyze(IMethodSymbol methodSymbol, Compilation compil private static bool IsEventArgs(ITypeSymbol type, Compilation compilation) { - if (type.DerivesFrom(compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemEventArgs))) + if (type.DerivesFrom(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemEventArgs))) { return true; } @@ -212,7 +212,7 @@ private static bool IsExplicitlyVisibleFromCom(IMethodSymbol methodSymbol, Compi return false; } - var comVisibleAttribute = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesComVisibleAttribute); + var comVisibleAttribute = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesComVisibleAttribute); if (comVisibleAttribute == null) { return false; @@ -240,26 +240,26 @@ void Add(INamedTypeSymbol symbol) } } - Add(compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemWebServicesWebMethodAttribute)); + Add(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemWebServicesWebMethodAttribute)); // MSTest attributes - Add(compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestInitializeAttribute)); - Add(compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestMethodAttribute)); - Add(compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingDataTestMethodAttribute)); - Add(compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestCleanupAttribute)); + Add(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestInitializeAttribute)); + Add(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestMethodAttribute)); + Add(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingDataTestMethodAttribute)); + Add(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingTestCleanupAttribute)); // XUnit attributes - Add(compilation.GetTypeByMetadataName(WellKnownTypeNames.XunitFactAttribute)); + Add(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.XunitFactAttribute)); // NUnit Attributes - Add(compilation.GetTypeByMetadataName(WellKnownTypeNames.NUnitFrameworkSetUpAttribute)); - Add(compilation.GetTypeByMetadataName(WellKnownTypeNames.NUnitFrameworkOneTimeSetUpAttribute)); - Add(compilation.GetTypeByMetadataName(WellKnownTypeNames.NUnitFrameworkOneTimeTearDownAttribute)); - Add(compilation.GetTypeByMetadataName(WellKnownTypeNames.NUnitFrameworkTestAttribute)); - Add(compilation.GetTypeByMetadataName(WellKnownTypeNames.NUnitFrameworkTestCaseAttribute)); - Add(compilation.GetTypeByMetadataName(WellKnownTypeNames.NUnitFrameworkTestCaseSourceAttribute)); - Add(compilation.GetTypeByMetadataName(WellKnownTypeNames.NUnitFrameworkTheoryAttribute)); - Add(compilation.GetTypeByMetadataName(WellKnownTypeNames.NUnitFrameworkTearDownAttribute)); + Add(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.NUnitFrameworkSetUpAttribute)); + Add(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.NUnitFrameworkOneTimeSetUpAttribute)); + Add(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.NUnitFrameworkOneTimeTearDownAttribute)); + Add(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.NUnitFrameworkTestAttribute)); + Add(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.NUnitFrameworkTestCaseAttribute)); + Add(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.NUnitFrameworkTestCaseSourceAttribute)); + Add(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.NUnitFrameworkTheoryAttribute)); + Add(compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.NUnitFrameworkTearDownAttribute)); return builder?.ToImmutable() ?? ImmutableArray.Empty; } diff --git a/src/Microsoft.CodeQuality.Analyzers/VisualBasic/QualityGuidelines/BasicRemoveEmptyFinalizersAnalyzer.vb b/src/Microsoft.CodeQuality.Analyzers/VisualBasic/QualityGuidelines/BasicRemoveEmptyFinalizersAnalyzer.vb index 8d4c23ddf6..a7ff4b3934 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 +Imports Analyzer.Utilities.Extensions Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic.Syntax @@ -31,7 +32,7 @@ Namespace Microsoft.CodeQuality.VisualBasic.Analyzers.QualityGuidelines Return False End If - Dim conditionalAttributeSymbol = analysisContext.SemanticModel.Compilation.GetTypeByMetadataName(GetType(ConditionalAttribute).FullName) + Dim conditionalAttributeSymbol = analysisContext.SemanticModel.Compilation.GetOrCreateTypeByMetadataName(GetType(ConditionalAttribute).FullName) Return InvocationIsConditional(invocationSymbol, conditionalAttributeSymbol) End If End If diff --git a/src/Microsoft.NetCore.Analyzers/Core/Data/ReviewSqlQueriesForSecurityVulnerabilities.cs b/src/Microsoft.NetCore.Analyzers/Core/Data/ReviewSqlQueriesForSecurityVulnerabilities.cs index 8c728011d4..5a55ec9eb8 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Data/ReviewSqlQueriesForSecurityVulnerabilities.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Data/ReviewSqlQueriesForSecurityVulnerabilities.cs @@ -41,8 +41,8 @@ public override void Initialize(AnalysisContext context) context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.None); context.RegisterCompilationStartAction(compilationContext => { - INamedTypeSymbol iDbCommandType = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemDataIDbCommand); - INamedTypeSymbol iDataAdapterType = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemDataIDataAdapter); + INamedTypeSymbol iDbCommandType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataIDbCommand); + INamedTypeSymbol iDataAdapterType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataIDataAdapter); IPropertySymbol commandTextProperty = iDbCommandType?.GetMembers("CommandText").OfType().FirstOrDefault(); if (iDbCommandType == null || diff --git a/src/Microsoft.NetCore.Analyzers/Core/ImmutableCollections/DoNotCallToImmutableCollectionOnAnImmutableCollectionValue.cs b/src/Microsoft.NetCore.Analyzers/Core/ImmutableCollections/DoNotCallToImmutableCollectionOnAnImmutableCollectionValue.cs index be5feec675..057f337b4a 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/ImmutableCollections/DoNotCallToImmutableCollectionOnAnImmutableCollectionValue.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/ImmutableCollections/DoNotCallToImmutableCollectionOnAnImmutableCollectionValue.cs @@ -55,24 +55,8 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(compilationStartContext => { var compilation = compilationStartContext.Compilation; - var immutableArraySymbol = compilation.GetTypeByMetadataName(ImmutableArrayMetadataName); - if (immutableArraySymbol is null) - { - var systemNamespace = compilation.GlobalNamespace.GetMembers(nameof(System)).OfType().FirstOrDefault(); - var systemCollectionsNamespace = systemNamespace?.GetMembers(nameof(System.Collections)).OfType().FirstOrDefault(); - var systemCollectionsImmutableNamespace = systemCollectionsNamespace?.GetMembers(nameof(System.Collections.Immutable)).OfType().FirstOrDefault(); - if (systemCollectionsImmutableNamespace is null) - { - return; - } - - var immutableArrayTypes = systemCollectionsImmutableNamespace.GetMembers(nameof(ImmutableArray)).OfType().Where(type => type.MetadataName == typeof(ImmutableArray<>).Name).ToArray(); - var localSymbol = immutableArrayTypes.FirstOrDefault(type => type.ContainingAssembly.Equals(compilation.Assembly)); - var publicSymbol = immutableArrayTypes.FirstOrDefault(type => type.DeclaredAccessibility == Accessibility.Public); - var fallbackSymbol = immutableArrayTypes.FirstOrDefault(); - immutableArraySymbol = localSymbol ?? publicSymbol ?? fallbackSymbol; - } - + var wellKnownTypeProvider = WellKnownTypeProvider.GetOrCreate(compilation); + var immutableArraySymbol = wellKnownTypeProvider.GetOrCreateTypeByMetadataName(ImmutableArrayMetadataName); if (immutableArraySymbol is null) { return; diff --git a/src/Microsoft.NetCore.Analyzers/Core/InteropServices/AlwaysConsumeTheValueReturnedByMethodsMarkedWithPreserveSigAttribute.cs b/src/Microsoft.NetCore.Analyzers/Core/InteropServices/AlwaysConsumeTheValueReturnedByMethodsMarkedWithPreserveSigAttribute.cs index 411cdfcb29..bf2e8d6653 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/InteropServices/AlwaysConsumeTheValueReturnedByMethodsMarkedWithPreserveSigAttribute.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/InteropServices/AlwaysConsumeTheValueReturnedByMethodsMarkedWithPreserveSigAttribute.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Immutable; using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; @@ -36,7 +37,7 @@ public sealed override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(compilationContext => { - var preserveSigType = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesPreserveSigAttribute); + var preserveSigType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesPreserveSigAttribute); if (preserveSigType != null) { compilationContext.RegisterSyntaxNodeAction( diff --git a/src/Microsoft.NetCore.Analyzers/Core/InteropServices/PInvokeDiagnosticAnalyzer.cs b/src/Microsoft.NetCore.Analyzers/Core/InteropServices/PInvokeDiagnosticAnalyzer.cs index bdb75352c2..d7817d1135 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.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesDllImportAttribute); + INamedTypeSymbol dllImportType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesDllImportAttribute); if (dllImportType == null) { return; } - INamedTypeSymbol marshalAsType = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesMarshalAsAttribute); + INamedTypeSymbol marshalAsType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesMarshalAsAttribute); if (marshalAsType == null) { return; } - INamedTypeSymbol stringBuilderType = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemTextStringBuilder); + INamedTypeSymbol stringBuilderType = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemTextStringBuilder); if (stringBuilderType == null) { return; } - INamedTypeSymbol unmanagedType = context.Compilation.GetTypeByMetadataName(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 afc5f19548..6a575cf2ce 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/InteropServices/SpecifyMarshalingForPInvokeStringArguments.Fixer.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/InteropServices/SpecifyMarshalingForPInvokeStringArguments.Fixer.cs @@ -6,6 +6,7 @@ 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; @@ -30,10 +31,10 @@ public override async Task RegisterCodeFixesAsync(CodeFixContext context) } SemanticModel model = await context.Document.GetSemanticModelAsync(context.CancellationToken).ConfigureAwait(false); - INamedTypeSymbol charSetType = model.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesCharSet); - INamedTypeSymbol dllImportType = model.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesDllImportAttribute); - INamedTypeSymbol marshalAsType = model.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesMarshalAsAttribute); - INamedTypeSymbol unmanagedType = model.Compilation.GetTypeByMetadataName(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.cs b/src/Microsoft.NetCore.Analyzers/Core/Performance/DoNotUseCountWhenAnyCanBeUsed.cs index 4947e78ba3..86fc78ee21 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Performance/DoNotUseCountWhenAnyCanBeUsed.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Performance/DoNotUseCountWhenAnyCanBeUsed.cs @@ -164,7 +164,7 @@ public override void Initialize(AnalysisContext context) /// The context. private static void OnCompilationStart(CompilationStartAnalysisContext context) { - if (context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemLinqEnumerable) is INamedTypeSymbol enumerableType) + if (context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemLinqEnumerable) is INamedTypeSymbol enumerableType) { var operationActionsHandler = new OperationActionsHandler( targetType: enumerableType, @@ -181,7 +181,7 @@ private static void OnCompilationStart(CompilationStartAnalysisContext context) OperationKind.BinaryOperator); } - if (context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemLinqQueryable) is INamedTypeSymbol queryableType) + if (context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemLinqQueryable) is INamedTypeSymbol queryableType) { var operationActionsHandler = new OperationActionsHandler( targetType: queryableType, @@ -198,7 +198,7 @@ private static void OnCompilationStart(CompilationStartAnalysisContext context) OperationKind.BinaryOperator); } - if (context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftEntityFrameworkCoreEntityFrameworkQueryableExtensions) is INamedTypeSymbol entityFrameworkQueryableExtensionsType) + if (context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftEntityFrameworkCoreEntityFrameworkQueryableExtensions) is INamedTypeSymbol entityFrameworkQueryableExtensionsType) { var operationActionsHandler = new OperationActionsHandler( targetType: entityFrameworkQueryableExtensionsType, @@ -215,7 +215,7 @@ private static void OnCompilationStart(CompilationStartAnalysisContext context) OperationKind.BinaryOperator); } - if (context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemDataEntityQueryableExtensions) is INamedTypeSymbol queryableExtensionsType) + if (context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataEntityQueryableExtensions) is INamedTypeSymbol queryableExtensionsType) { var operationActionsHandler = new OperationActionsHandler( targetType: queryableExtensionsType, diff --git a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs index 0ee817ea05..7913b7a85b 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Performance/UsePropertyInsteadOfCountMethodWhenAvailable.cs @@ -64,7 +64,7 @@ public override void Initialize(AnalysisContext context) /// The context. private void OnCompilationStart(CompilationStartAnalysisContext context) { - if (context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemLinqEnumerable) is INamedTypeSymbol enumerableType) + if (context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemLinqEnumerable) is INamedTypeSymbol enumerableType) { var operationActionsContext = new OperationActionsContext( context.Compilation, @@ -101,9 +101,9 @@ public OperationActionsContext(Compilation compilation, INamedTypeSymbol enumera { Compilation = compilation; EnumerableType = enumerableType; - _immutableArrayType = new Lazy(() => Compilation.GetVisibleTypeByMetadataName(WellKnownTypeNames.SystemCollectionsImmutableImmutableArray), true); + _immutableArrayType = new Lazy(() => Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsImmutableImmutableArray), true); _iCollectionCountProperty = new Lazy(ResolveICollectionCountProperty, true); - _iCollectionOfType = new Lazy(() => Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericICollection1), true); + _iCollectionOfType = new Lazy(() => Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericICollection1), true); } /// @@ -140,7 +140,7 @@ private IPropertySymbol ResolveICollectionCountProperty() { IPropertySymbol countProperty = null; - if (Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsICollection) is INamedTypeSymbol iCollectionType) + if (Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsICollection) is INamedTypeSymbol iCollectionType) { foreach (var member in iCollectionType.GetMembers()) { diff --git a/src/Microsoft.NetCore.Analyzers/Core/Resources/MarkAssembliesWithNeutralResourcesLanguage.cs b/src/Microsoft.NetCore.Analyzers/Core/Resources/MarkAssembliesWithNeutralResourcesLanguage.cs index cddce4d0a9..179f529c4c 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Resources/MarkAssembliesWithNeutralResourcesLanguage.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Resources/MarkAssembliesWithNeutralResourcesLanguage.cs @@ -123,7 +123,7 @@ protected static bool CheckResxGeneratedFile(SemanticModel model, SyntaxNode att private static bool TryCheckNeutralResourcesLanguageAttribute(CompilationAnalysisContext context, out AttributeData attributeData) { - INamedTypeSymbol attribute = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemResourcesNeutralResourcesLanguageAttribute); + 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); diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidUnsealedAttributes.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidUnsealedAttributes.cs index 19f5b10a52..3229b61279 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.GetTypeByMetadataName(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 d300253e4a..d7c07365fa 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidZeroLengthArrayAllocations.Fixer.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/AvoidZeroLengthArrayAllocations.Fixer.cs @@ -6,6 +6,7 @@ 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; @@ -73,7 +74,7 @@ private static ITypeSymbol GetArrayElementType(SyntaxNode arrayCreationExpressio private static SyntaxNode GenerateArrayEmptyInvocation(SyntaxGenerator generator, ITypeSymbol elementType, SemanticModel semanticModel) { - INamedTypeSymbol arrayTypeSymbol = semanticModel.Compilation.GetTypeByMetadataName(AvoidZeroLengthArrayAllocationsAnalyzer.ArrayTypeName); + 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 9148d08b24..7f180e32f9 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.GetTypeByMetadataName(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 && @@ -101,7 +101,7 @@ private static void AnalyzeOperation(OperationAnalysisContext context, Func { var gcSuppressFinalizeMethodSymbol = compilationContext.Compilation - .GetTypeByMetadataName(WellKnownTypeNames.SystemGC) + .GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemGC) ?.GetMembers("SuppressFinalize") .OfType() .FirstOrDefault(); diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/DisposableTypesShouldDeclareFinalizer.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/DisposableTypesShouldDeclareFinalizer.cs index 61a04e35ab..669bf04871 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/DisposableTypesShouldDeclareFinalizer.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/DisposableTypesShouldDeclareFinalizer.cs @@ -49,7 +49,7 @@ public override void Initialize(AnalysisContext analysisContext) ImmutableHashSet nativeResourceTypes = ImmutableHashSet.Create( compilation.GetSpecialType(SpecialType.System_IntPtr), compilation.GetSpecialType(SpecialType.System_UIntPtr), - compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesHandleRef) + compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeInteropServicesHandleRef) ); var disposableType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIDisposable); diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/DoNotLockOnObjectsWithWeakIdentity.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/DoNotLockOnObjectsWithWeakIdentity.cs index dde3a8b99a..d2e7bc75c5 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/DoNotLockOnObjectsWithWeakIdentity.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/DoNotLockOnObjectsWithWeakIdentity.cs @@ -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.GetTypeByMetadataName(WellKnownTypeNames.SystemMarshalByRefObject); - INamedTypeSymbol executionEngineExceptionTypeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemExecutionEngineException); - INamedTypeSymbol outOfMemoryExceptionTypeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemOutOfMemoryException); - INamedTypeSymbol stackOverflowExceptionTypeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemStackOverflowException); - INamedTypeSymbol memberInfoTypeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemReflectionMemberInfo); - INamedTypeSymbol parameterInfoTypeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemReflectionParameterInfo); - INamedTypeSymbol threadTypeSymbol = compilation.GetTypeByMetadataName(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 51956e42fc..b48d0a4598 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.GetTypeByMetadataName(WellKnownTypeNames.SystemComponentModelLocalizableAttribute); - INamedTypeSymbol conditionalAttributeSymbol = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemDiagnosticsConditionalAttribute); - INamedTypeSymbol systemConsoleSymbol = compilationContext.Compilation.GetTypeByMetadataName(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 => @@ -179,31 +179,31 @@ private static ImmutableHashSet GetTypesToIgnore(Compilation c { var builder = PooledHashSet.GetInstance(); - var xmlWriter = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemXmlXmlWriter); + var xmlWriter = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemXmlXmlWriter); if (xmlWriter != null) { builder.Add(xmlWriter); } - var webUILiteralControl = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemWebUILiteralControl); + var webUILiteralControl = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemWebUILiteralControl); if (webUILiteralControl != null) { builder.Add(webUILiteralControl); } - var unitTestingAssert = compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingAssert); + var unitTestingAssert = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingAssert); if (unitTestingAssert != null) { builder.Add(unitTestingAssert); } - var unitTestingCollectionAssert = compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingCollectionAssert); + var unitTestingCollectionAssert = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingCollectionAssert); if (unitTestingCollectionAssert != null) { builder.Add(unitTestingCollectionAssert); } - var unitTestingCollectionStringAssert = compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingStringAssert); + var unitTestingCollectionStringAssert = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualStudioTestToolsUnitTestingStringAssert); if (unitTestingCollectionStringAssert != null) { builder.Add(unitTestingCollectionStringAssert); diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/DoNotRaiseReservedExceptionTypes.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/DoNotRaiseReservedExceptionTypes.cs index be0361644a..6073d7387a 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/DoNotRaiseReservedExceptionTypes.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/DoNotRaiseReservedExceptionTypes.cs @@ -5,6 +5,7 @@ using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis; using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; namespace Microsoft.NetCore.Analyzers.Runtime { @@ -110,7 +111,7 @@ private static ImmutableHashSet CreateSymbolSet(Compilation co HashSet set = null; foreach (string exp in exceptionNames) { - INamedTypeSymbol symbol = compilation.GetTypeByMetadataName(exp); + INamedTypeSymbol symbol = compilation.GetOrCreateTypeByMetadataName(exp); if (symbol == null) { continue; diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/DoNotUseEnumerableMethodsOnIndexableCollectionsInsteadUseTheCollectionDirectly.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/DoNotUseEnumerableMethodsOnIndexableCollectionsInsteadUseTheCollectionDirectly.cs index e0bfa85a63..2f3eb38a44 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/DoNotUseEnumerableMethodsOnIndexableCollectionsInsteadUseTheCollectionDirectly.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/DoNotUseEnumerableMethodsOnIndexableCollectionsInsteadUseTheCollectionDirectly.cs @@ -53,9 +53,9 @@ public override void Initialize(AnalysisContext context) private static void OnCompilationStart(CompilationStartAnalysisContext context) { - var listType = context.Compilation.GetTypeByMetadataName(IListMetadataName); - var readonlyListType = context.Compilation.GetTypeByMetadataName(IReadOnlyListMetadataName); - var enumerableType = context.Compilation.GetTypeByMetadataName(EnumerableMetadataName); + var listType = context.Compilation.GetOrCreateTypeByMetadataName(IListMetadataName); + var readonlyListType = context.Compilation.GetOrCreateTypeByMetadataName(IReadOnlyListMetadataName); + var enumerableType = context.Compilation.GetOrCreateTypeByMetadataName(EnumerableMetadataName); if (readonlyListType == null || enumerableType == null || listType == null) { return; diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/InstantiateArgumentExceptionsCorrectly.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/InstantiateArgumentExceptionsCorrectly.cs index f4dab8d752..d22ccaf064 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/InstantiateArgumentExceptionsCorrectly.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/InstantiateArgumentExceptionsCorrectly.cs @@ -45,7 +45,7 @@ public override void Initialize(AnalysisContext analysisContext) compilationContext => { Compilation compilation = compilationContext.Compilation; - ITypeSymbol argumentExceptionType = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemArgumentException); + ITypeSymbol argumentExceptionType = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemArgumentException); if (argumentExceptionType == null) { diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/MarkAllNonSerializableFields.Fixer.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/MarkAllNonSerializableFields.Fixer.cs index bf0f53eed4..0842ddbbff 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/MarkAllNonSerializableFields.Fixer.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/MarkAllNonSerializableFields.Fixer.cs @@ -9,6 +9,7 @@ using Microsoft.CodeAnalysis.Editing; using Analyzer.Utilities; using Microsoft.CodeAnalysis; +using Analyzer.Utilities.Extensions; namespace Microsoft.NetCore.Analyzers.Runtime { @@ -55,7 +56,7 @@ private static async Task AddNonSerializedAttribute(Document document, { DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); SyntaxNode attr = editor.Generator.Attribute(editor.Generator.TypeExpression( - editor.SemanticModel.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemNonSerializedAttribute))); + editor.SemanticModel.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNonSerializedAttribute))); editor.AddAttribute(fieldNode, attr); return editor.GetChangedDocument(); } @@ -66,7 +67,7 @@ private static async Task AddSerializableAttributeToType(Document docu await editor.EditOneDeclarationAsync(type, (docEditor, declaration) => { SyntaxNode serializableAttr = docEditor.Generator.Attribute(docEditor.Generator.TypeExpression( - docEditor.SemanticModel.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemSerializableAttribute))); + docEditor.SemanticModel.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSerializableAttribute))); docEditor.AddAttribute(declaration, serializableAttr); }, cancellationToken).ConfigureAwait(false); diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/MarkISerializableTypesWithSerializable.Fixer.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/MarkISerializableTypesWithSerializable.Fixer.cs index 10a26b3550..b4ac68e037 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/MarkISerializableTypesWithSerializable.Fixer.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/MarkISerializableTypesWithSerializable.Fixer.cs @@ -9,6 +9,7 @@ using Microsoft.CodeAnalysis.Editing; using Analyzer.Utilities; using Microsoft.CodeAnalysis; +using Analyzer.Utilities.Extensions; namespace Microsoft.NetCore.Analyzers.Runtime { @@ -42,7 +43,7 @@ private static async Task AddSerializableAttribute(Document document, { DocumentEditor editor = await DocumentEditor.CreateAsync(document, cancellationToken).ConfigureAwait(false); SyntaxNode attr = editor.Generator.Attribute(editor.Generator.TypeExpression( - editor.SemanticModel.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemSerializableAttribute))); + editor.SemanticModel.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSerializableAttribute))); editor.AddAttribute(node, attr); return editor.GetChangedDocument(); } diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/NormalizeStringsToUppercase.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/NormalizeStringsToUppercase.cs index 1a313fd9c7..b316b9d29e 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/NormalizeStringsToUppercase.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/NormalizeStringsToUppercase.cs @@ -3,6 +3,7 @@ using System.Collections.Immutable; using System.Linq; using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; @@ -52,7 +53,7 @@ public override void Initialize(AnalysisContext analysisContext) return; } - var cultureInfo = compilationStartContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemGlobalizationCultureInfo); + var cultureInfo = compilationStartContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemGlobalizationCultureInfo); var invariantCulture = cultureInfo?.GetMembers("InvariantCulture").OfType().FirstOrDefault(); // We want to flag calls to "ToLowerInvariant" and "ToLower(CultureInfo.InvariantCulture)". diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/SerializationRulesDiagnosticAnalyzer.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/SerializationRulesDiagnosticAnalyzer.cs index 0077009877..626200ce49 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/SerializationRulesDiagnosticAnalyzer.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/SerializationRulesDiagnosticAnalyzer.cs @@ -97,31 +97,31 @@ public override void Initialize(AnalysisContext analysisContext) analysisContext.RegisterCompilationStartAction( (context) => { - INamedTypeSymbol iserializableTypeSymbol = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationISerializable); + INamedTypeSymbol iserializableTypeSymbol = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationISerializable); if (iserializableTypeSymbol == null) { return; } - INamedTypeSymbol serializationInfoTypeSymbol = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationSerializationInfo); + INamedTypeSymbol serializationInfoTypeSymbol = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationSerializationInfo); if (serializationInfoTypeSymbol == null) { return; } - INamedTypeSymbol streamingContextTypeSymbol = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationStreamingContext); + INamedTypeSymbol streamingContextTypeSymbol = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeSerializationStreamingContext); if (streamingContextTypeSymbol == null) { return; } - INamedTypeSymbol serializableAttributeTypeSymbol = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemSerializableAttribute); + INamedTypeSymbol serializableAttributeTypeSymbol = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSerializableAttribute); if (serializableAttributeTypeSymbol == null) { return; } - INamedTypeSymbol nonSerializedAttributeTypeSymbol = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemNonSerializedAttribute); + INamedTypeSymbol nonSerializedAttributeTypeSymbol = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNonSerializedAttribute); if (nonSerializedAttributeTypeSymbol == null) { return; diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/SpecifyCultureInfo.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/SpecifyCultureInfo.cs index 1102f86e71..5411b3a9bc 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/SpecifyCultureInfo.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/SpecifyCultureInfo.cs @@ -43,9 +43,9 @@ public override void Initialize(AnalysisContext analysisContext) analysisContext.RegisterCompilationStartAction(csaContext => { - var obsoleteAttributeType = csaContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemObsoleteAttribute); + var obsoleteAttributeType = csaContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemObsoleteAttribute); - var cultureInfoType = csaContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemGlobalizationCultureInfo); + var cultureInfoType = csaContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemGlobalizationCultureInfo); if (cultureInfoType != null) { csaContext.RegisterOperationAction(oaContext => diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/SpecifyIFormatProvider.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/SpecifyIFormatProvider.cs index 37cef1fcd7..f2ba863285 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/SpecifyIFormatProvider.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/SpecifyIFormatProvider.cs @@ -75,8 +75,8 @@ public override void Initialize(AnalysisContext analysisContext) analysisContext.RegisterCompilationStartAction(csaContext => { #region "Get All the WellKnown Types and Members" - var iformatProviderType = csaContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemIFormatProvider); - var cultureInfoType = csaContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemGlobalizationCultureInfo); + var iformatProviderType = csaContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemIFormatProvider); + var cultureInfoType = csaContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemGlobalizationCultureInfo); if (iformatProviderType == null || cultureInfoType == null) { return; @@ -111,16 +111,16 @@ public override void Initialize(AnalysisContext analysisContext) var currentUICultureProperty = cultureInfoType?.GetMembers("CurrentUICulture").OfType().FirstOrDefault(); var installedUICultureProperty = cultureInfoType?.GetMembers("InstalledUICulture").OfType().FirstOrDefault(); - var threadType = csaContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemThreadingThread); + var threadType = csaContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingThread); var currentThreadCurrentUICultureProperty = threadType?.GetMembers("CurrentUICulture").OfType().FirstOrDefault(); - var activatorType = csaContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemActivator); - var resourceManagerType = csaContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemResourcesResourceManager); + var activatorType = csaContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemActivator); + var resourceManagerType = csaContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemResourcesResourceManager); - var computerInfoType = csaContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualBasicDevicesComputerInfo); + var computerInfoType = csaContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftVisualBasicDevicesComputerInfo); var installedUICulturePropertyOfComputerInfoType = computerInfoType?.GetMembers("InstalledUICulture").OfType().FirstOrDefault(); - var obsoleteAttributeType = csaContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemObsoleteAttribute); + var obsoleteAttributeType = csaContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemObsoleteAttribute); #endregion csaContext.RegisterOperationAction(oaContext => diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/SpecifyStringComparison.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/SpecifyStringComparison.cs index f74bd68bb1..d61364a644 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/SpecifyStringComparison.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/SpecifyStringComparison.cs @@ -42,7 +42,7 @@ public override void Initialize(AnalysisContext analysisContext) analysisContext.RegisterCompilationStartAction(csaContext => { - var stringComparisonType = csaContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemStringComparison); + var stringComparisonType = csaContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemStringComparison); var stringType = csaContext.Compilation.GetSpecialType(SpecialType.System_String); // Without these symbols the rule cannot run diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/UseOrdinalStringComparison.Fixer.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/UseOrdinalStringComparison.Fixer.cs index 12959d69cd..a2996b043b 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/UseOrdinalStringComparison.Fixer.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/UseOrdinalStringComparison.Fixer.cs @@ -5,6 +5,7 @@ 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; @@ -75,7 +76,7 @@ internal SyntaxNode CreateEqualsExpression(SyntaxGenerator generator, SemanticMo internal static SyntaxNode CreateOrdinalMemberAccess(SyntaxGenerator generator, SemanticModel model) { - INamedTypeSymbol stringComparisonType = model.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemStringComparison); + INamedTypeSymbol stringComparisonType = model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemStringComparison); return generator.MemberAccessExpression( generator.TypeExpressionForStaticMemberAccess(stringComparisonType), generator.IdentifierName(UseOrdinalStringComparisonAnalyzer.OrdinalText)); @@ -83,7 +84,7 @@ internal static SyntaxNode CreateOrdinalMemberAccess(SyntaxGenerator generator, protected static bool CanAddStringComparison(IMethodSymbol methodSymbol, SemanticModel model) { - if (model.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemStringComparison) == null) + if (model.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemStringComparison) == null) { return false; } diff --git a/src/Microsoft.NetCore.Analyzers/Core/Runtime/UseOrdinalStringComparison.cs b/src/Microsoft.NetCore.Analyzers/Core/Runtime/UseOrdinalStringComparison.cs index 60078848e1..8827509e46 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Runtime/UseOrdinalStringComparison.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Runtime/UseOrdinalStringComparison.cs @@ -46,7 +46,7 @@ public override void Initialize(AnalysisContext analysisContext) analysisContext.RegisterCompilationStartAction( (context) => { - INamedTypeSymbol stringComparisonType = context.Compilation.GetTypeByMetadataName(StringComparisonTypeName); + INamedTypeSymbol stringComparisonType = context.Compilation.GetOrCreateTypeByMetadataName(StringComparisonTypeName); if (stringComparisonType != null) { context.RegisterOperationAction(operationContext => diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/ApprovedCipherModeAnalyzer.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/ApprovedCipherModeAnalyzer.cs index f79794944d..7fb7a7515a 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/ApprovedCipherModeAnalyzer.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/ApprovedCipherModeAnalyzer.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Immutable; using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; @@ -56,7 +57,7 @@ public sealed override void Initialize(AnalysisContext context) (CompilationStartAnalysisContext compilationStartAnalysisContext) => { INamedTypeSymbol cipherModeTypeSymbol = - compilationStartAnalysisContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyCipherMode); + compilationStartAnalysisContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyCipherMode); if (cipherModeTypeSymbol == null) { diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotAddSchemaByURL.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotAddSchemaByURL.cs index 7b48ab9c56..87ba90e831 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotAddSchemaByURL.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotAddSchemaByURL.cs @@ -48,7 +48,7 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(compilationStartAnalysisContext => { - var xmlSchemaCollectionTypeSymbol = compilationStartAnalysisContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemXmlSchemaXmlSchemaCollection); + var xmlSchemaCollectionTypeSymbol = compilationStartAnalysisContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemXmlSchemaXmlSchemaCollection); if (xmlSchemaCollectionTypeSymbol == null) { diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotDisableHttpHeaderChecking.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotDisableHttpHeaderChecking.cs index e65ea99258..9154032c5c 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotDisableHttpHeaderChecking.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotDisableHttpHeaderChecking.cs @@ -49,7 +49,7 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(compilationStartAnalysisContext => { var compilation = compilationStartAnalysisContext.Compilation; - var httpRuntimeSectionTypeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemWebConfigurationHttpRuntimeSection); + var httpRuntimeSectionTypeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemWebConfigurationHttpRuntimeSection); if (httpRuntimeSectionTypeSymbol == null) { diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotReferSelfInSerializableClass.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotReferSelfInSerializableClass.cs index 65a8f52e0a..a2b52a7bc1 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotReferSelfInSerializableClass.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotReferSelfInSerializableClass.cs @@ -52,14 +52,14 @@ public sealed override void Initialize(AnalysisContext context) (CompilationStartAnalysisContext compilationStartAnalysisContext) => { var compilation = compilationStartAnalysisContext.Compilation; - var serializableAttributeTypeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemSerializableAttribute); + var serializableAttributeTypeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSerializableAttribute); if (serializableAttributeTypeSymbol == null) { return; } - var nonSerializedAttribute = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemNonSerializedAttribute); + var nonSerializedAttribute = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNonSerializedAttribute); if (nonSerializedAttribute == null) { diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotSerializeTypeWithPointerFields.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotSerializeTypeWithPointerFields.cs index 64d2f984f5..9d8a7f5892 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotSerializeTypeWithPointerFields.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotSerializeTypeWithPointerFields.cs @@ -51,14 +51,14 @@ public sealed override void Initialize(AnalysisContext context) (CompilationStartAnalysisContext compilationStartAnalysisContext) => { var compilation = compilationStartAnalysisContext.Compilation; - var serializableAttributeTypeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemSerializableAttribute); + var serializableAttributeTypeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSerializableAttribute); if (serializableAttributeTypeSymbol == null) { return; } - var nonSerializedAttribute = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemNonSerializedAttribute); + var nonSerializedAttribute = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNonSerializedAttribute); var visitedType = new ConcurrentDictionary(); var pointerFields = new ConcurrentDictionary(); diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotSetSwitch.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotSetSwitch.cs index 11761203d0..b69f0e0c13 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotSetSwitch.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotSetSwitch.cs @@ -63,7 +63,7 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(compilationStartAnalysisContext => { var compilation = compilationStartAnalysisContext.Compilation; - var appContextTypeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemAppContext); + var appContextTypeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemAppContext); if (appContextTypeSymbol == null) { diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotUseInsecureDeserializerMethodsBase.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotUseInsecureDeserializerMethodsBase.cs index 7dd48c5a28..4eb43393b6 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotUseInsecureDeserializerMethodsBase.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotUseInsecureDeserializerMethodsBase.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Immutable; using System.Diagnostics; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; @@ -58,7 +59,7 @@ public sealed override void Initialize(AnalysisContext context) (CompilationStartAnalysisContext compilationStartAnalysisContext) => { INamedTypeSymbol deserializerTypeSymbol = - compilationStartAnalysisContext.Compilation.GetTypeByMetadataName(this.DeserializerTypeMetadataName); + compilationStartAnalysisContext.Compilation.GetOrCreateTypeByMetadataName(this.DeserializerTypeMetadataName); if (deserializerTypeSymbol == null) { return; diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotUseXslTransform.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotUseXslTransform.cs index 761df9c102..a0463b77b5 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotUseXslTransform.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/DoNotUseXslTransform.cs @@ -43,7 +43,7 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(compilationStartAnalysisContext => { - var xslTransformTypeSymbol = compilationStartAnalysisContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemXmlXslXslTransform); + var xslTransformTypeSymbol = compilationStartAnalysisContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemXmlXslXslTransform); if (xslTransformTypeSymbol == null) { diff --git a/src/Microsoft.NetCore.Analyzers/Core/Security/Helpers/CompilationSecurityTypes.cs b/src/Microsoft.NetCore.Analyzers/Core/Security/Helpers/CompilationSecurityTypes.cs index 6d19563373..9e56510b4e 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Security/Helpers/CompilationSecurityTypes.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Security/Helpers/CompilationSecurityTypes.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 Analyzer.Utilities; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; namespace Microsoft.NetCore.Analyzers.Security.Helpers @@ -23,17 +24,17 @@ public class CompilationSecurityTypes public CompilationSecurityTypes(Compilation compilation) { - MD5 = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyMD5); - SHA1 = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographySHA1); - HMACSHA1 = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyHMACSHA1); - DES = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyDES); - DSA = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyDSA); - DSASignatureFormatter = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyDSASignatureFormatter); - HMACMD5 = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyHMACMD5); - RC2 = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyRC2); - TripleDES = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyTripleDES); - RIPEMD160 = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyRIPEMD160); - HMACRIPEMD160 = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyHMACRIPEMD160); + MD5 = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyMD5); + SHA1 = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographySHA1); + HMACSHA1 = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyHMACSHA1); + DES = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyDES); + DSA = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyDSA); + DSASignatureFormatter = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyDSASignatureFormatter); + HMACMD5 = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyHMACMD5); + RC2 = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyRC2); + TripleDES = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyTripleDES); + RIPEMD160 = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyRIPEMD160); + HMACRIPEMD160 = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSecurityCryptographyHMACRIPEMD160); } } } diff --git a/src/Microsoft.NetCore.Analyzers/Core/Tasks/DoNotCreateTasksWithoutPassingATaskScheduler.cs b/src/Microsoft.NetCore.Analyzers/Core/Tasks/DoNotCreateTasksWithoutPassingATaskScheduler.cs index 9c794b5190..ddc8906e3a 100644 --- a/src/Microsoft.NetCore.Analyzers/Core/Tasks/DoNotCreateTasksWithoutPassingATaskScheduler.cs +++ b/src/Microsoft.NetCore.Analyzers/Core/Tasks/DoNotCreateTasksWithoutPassingATaskScheduler.cs @@ -3,6 +3,7 @@ using System.Collections.Immutable; using System.Linq; using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; @@ -42,9 +43,9 @@ public sealed override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(compilationContext => { // Check if TPL is available before actually doing the searches - var taskType = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTask); - var taskFactoryType = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTaskFactory); - var taskSchedulerType = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTaskScheduler); + var taskType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTask); + var taskFactoryType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTaskFactory); + var taskSchedulerType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemThreadingTasksTaskScheduler); if (taskType == null || taskFactoryType == null || taskSchedulerType == null) { return; diff --git a/src/Microsoft.NetFramework.Analyzers/Core/Helpers/CompilationSecurityTypes.cs b/src/Microsoft.NetFramework.Analyzers/Core/Helpers/CompilationSecurityTypes.cs index 949845bff9..5090bca26e 100644 --- a/src/Microsoft.NetFramework.Analyzers/Core/Helpers/CompilationSecurityTypes.cs +++ b/src/Microsoft.NetFramework.Analyzers/Core/Helpers/CompilationSecurityTypes.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 Analyzer.Utilities; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; namespace Microsoft.NetFramework.Analyzers.Helpers @@ -32,26 +33,26 @@ public class CompilationSecurityTypes public CompilationSecurityTypes(Compilation compilation) { HandleProcessCorruptedStateExceptionsAttribute = - compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeExceptionServicesHandleProcessCorruptedStateExceptionsAttribute); + compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeExceptionServicesHandleProcessCorruptedStateExceptionsAttribute); SystemObject = compilation.GetSpecialType(SpecialType.System_Object); - SystemException = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemException); - SystemSystemException = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemSystemException); - XmlDocument = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemXmlXmlDocument); - XPathDocument = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemXmlXPathXPathDocument); - XmlSchema = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemXmlSchemaXmlSchema); - DataSet = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemDataDataSet); - XmlSerializer = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemXmlSerializationXmlSerializer); - DataTable = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemDataDataTable); - XmlNode = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemXmlXmlNode); - DataViewManager = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemDataDataViewManager); - XmlTextReader = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemXmlXmlTextReader); - XmlReader = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemXmlXmlReader); - DtdProcessing = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemXmlDtdProcessing); - XmlReaderSettings = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemXmlXmlReaderSettings); - XslCompiledTransform = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemXmlXslXslCompiledTransform); - XmlResolver = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemXmlXmlResolver); - XmlSecureResolver = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemXmlXmlSecureResolver); - XsltSettings = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemXmlXslXsltSettings); + SystemException = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemException); + SystemSystemException = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemSystemException); + XmlDocument = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemXmlXmlDocument); + XPathDocument = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemXmlXPathXPathDocument); + XmlSchema = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemXmlSchemaXmlSchema); + DataSet = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataDataSet); + XmlSerializer = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemXmlSerializationXmlSerializer); + DataTable = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataDataTable); + XmlNode = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemXmlXmlNode); + DataViewManager = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemDataDataViewManager); + XmlTextReader = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemXmlXmlTextReader); + XmlReader = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemXmlXmlReader); + DtdProcessing = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemXmlDtdProcessing); + XmlReaderSettings = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemXmlXmlReaderSettings); + XslCompiledTransform = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemXmlXslXslCompiledTransform); + XmlResolver = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemXmlXmlResolver); + XmlSecureResolver = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemXmlXmlSecureResolver); + XsltSettings = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemXmlXslXsltSettings); } } } diff --git a/src/Microsoft.NetFramework.Analyzers/Core/Helpers/SecurityDiagnosticHelpers.cs b/src/Microsoft.NetFramework.Analyzers/Core/Helpers/SecurityDiagnosticHelpers.cs index b36fa2d890..84d7fbbf17 100644 --- a/src/Microsoft.NetFramework.Analyzers/Core/Helpers/SecurityDiagnosticHelpers.cs +++ b/src/Microsoft.NetFramework.Analyzers/Core/Helpers/SecurityDiagnosticHelpers.cs @@ -226,7 +226,7 @@ private static int GetSpecifiedParameterIndex(IMethodSymbol method, CompilationS { return null; } - INamedTypeSymbol typeSymbol = compilation.GetTypeByMetadataName(typeName); + INamedTypeSymbol typeSymbol = compilation.GetOrCreateTypeByMetadataName(typeName); return typeSymbol?.ContainingAssembly.Identity.Name.Equals(assemblyName, StringComparison.Ordinal); } diff --git a/src/Microsoft.NetFramework.Analyzers/Core/MarkVerbHandlersWithValidateAntiforgeryTokenAnalyzer.MvcAttributeSymbols.cs b/src/Microsoft.NetFramework.Analyzers/Core/MarkVerbHandlersWithValidateAntiforgeryTokenAnalyzer.MvcAttributeSymbols.cs index 303adbeb0b..0811f1631d 100644 --- a/src/Microsoft.NetFramework.Analyzers/Core/MarkVerbHandlersWithValidateAntiforgeryTokenAnalyzer.MvcAttributeSymbols.cs +++ b/src/Microsoft.NetFramework.Analyzers/Core/MarkVerbHandlersWithValidateAntiforgeryTokenAnalyzer.MvcAttributeSymbols.cs @@ -3,6 +3,7 @@ using System; using System.Collections.Immutable; using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; namespace Microsoft.NetFramework.Analyzers @@ -27,16 +28,16 @@ private sealed class MvcAttributeSymbols public MvcAttributeSymbols(Compilation compilation) { - this.ValidateAntiforgeryTokenAttributeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemWebMvcValidateAntiForgeryTokenAttribute); - this.HttpGetAttributeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemWebMvcHttpGetAttribute); - this.HttpPostAttributeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemWebMvcHttpPostAttribute); - this.HttpPutAttributeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemWebMvcHttpPutAttribute); - this.HttpDeleteAttributeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemWebMvcHttpDeleteAttribute); - this.HttpPatchAttributeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemWebMvcHttpPatchAttribute); - this.AcceptVerbsAttributeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemWebMvcAcceptVerbsAttribute); - this.NonActionAttributeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemWebMvcNonActionAttribute); - this.ChildActionOnlyAttributeSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemWebMvcChildActionOnlyAttribute); - this.HttpVerbsSymbol = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemWebMvcHttpVerbs); + this.ValidateAntiforgeryTokenAttributeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemWebMvcValidateAntiForgeryTokenAttribute); + this.HttpGetAttributeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemWebMvcHttpGetAttribute); + this.HttpPostAttributeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemWebMvcHttpPostAttribute); + this.HttpPutAttributeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemWebMvcHttpPutAttribute); + this.HttpDeleteAttributeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemWebMvcHttpDeleteAttribute); + this.HttpPatchAttributeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemWebMvcHttpPatchAttribute); + this.AcceptVerbsAttributeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemWebMvcAcceptVerbsAttribute); + this.NonActionAttributeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemWebMvcNonActionAttribute); + this.ChildActionOnlyAttributeSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemWebMvcChildActionOnlyAttribute); + this.HttpVerbsSymbol = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemWebMvcHttpVerbs); } /// diff --git a/src/Microsoft.NetFramework.Analyzers/Core/TypesShouldNotExtendCertainBaseTypes.cs b/src/Microsoft.NetFramework.Analyzers/Core/TypesShouldNotExtendCertainBaseTypes.cs index d801926a0d..cae292221e 100644 --- a/src/Microsoft.NetFramework.Analyzers/Core/TypesShouldNotExtendCertainBaseTypes.cs +++ b/src/Microsoft.NetFramework.Analyzers/Core/TypesShouldNotExtendCertainBaseTypes.cs @@ -57,7 +57,7 @@ public override void Initialize(AnalysisContext analysisContext) private static void AnalyzeCompilationStart(CompilationStartAnalysisContext context) { ImmutableHashSet badBaseTypes = s_badBaseTypesToMessage.Keys - .Select(bt => context.Compilation.GetTypeByMetadataName(bt)) + .Select(bt => context.Compilation.GetOrCreateTypeByMetadataName(bt)) .Where(bt => bt != null) .ToImmutableHashSet(); diff --git a/src/PerformanceSensitiveAnalyzers/Core/AbstractAllocationAnalyzer.cs b/src/PerformanceSensitiveAnalyzers/Core/AbstractAllocationAnalyzer.cs index c4eed3649d..cfaccc789c 100644 --- a/src/PerformanceSensitiveAnalyzers/Core/AbstractAllocationAnalyzer.cs +++ b/src/PerformanceSensitiveAnalyzers/Core/AbstractAllocationAnalyzer.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 Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers @@ -26,7 +27,7 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(compilationStartContext => { var compilation = compilationStartContext.Compilation; - var attributeSymbol = compilation.GetTypeByMetadataName(AllocationRules.PerformanceSensitiveAttributeName); + var attributeSymbol = compilation.GetOrCreateTypeByMetadataName(AllocationRules.PerformanceSensitiveAttributeName); // Bail if PerformanceSensitiveAttribute is not delcared in the compilation. if (attributeSymbol == null) diff --git a/src/PerformanceSensitiveAnalyzers/Core/AbstractAllocationAnalyzer`1.cs b/src/PerformanceSensitiveAnalyzers/Core/AbstractAllocationAnalyzer`1.cs index bad0046a8f..43ca59526f 100644 --- a/src/PerformanceSensitiveAnalyzers/Core/AbstractAllocationAnalyzer`1.cs +++ b/src/PerformanceSensitiveAnalyzers/Core/AbstractAllocationAnalyzer`1.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 Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis.Diagnostics; namespace Microsoft.CodeAnalysis.PerformanceSensitiveAnalyzers @@ -27,7 +28,7 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(compilationStartContext => { var compilation = compilationStartContext.Compilation; - var attributeSymbol = compilation.GetTypeByMetadataName(AllocationRules.PerformanceSensitiveAttributeName); + var attributeSymbol = compilation.GetOrCreateTypeByMetadataName(AllocationRules.PerformanceSensitiveAttributeName); // Bail if PerformanceSensitiveAttribute is not delcared in the compilation. if (attributeSymbol == null) diff --git a/src/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.Impl.cs b/src/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.Impl.cs index 8ca7a90150..c6f50f7da5 100644 --- a/src/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.Impl.cs +++ b/src/PublicApiAnalyzers/Core/Analyzers/DeclarePublicApiAnalyzer.Impl.cs @@ -493,7 +493,7 @@ internal void OnCompilationEnd(CompilationAnalysisContext context) private void ProcessTypeForwardedAttributes(Compilation compilation, Action reportDiagnostic, CancellationToken cancellationToken) { - var typeForwardedToAttribute = compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemRuntimeCompilerServicesTypeForwardedToAttribute); + var typeForwardedToAttribute = compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemRuntimeCompilerServicesTypeForwardedToAttribute); if (typeForwardedToAttribute != null) { diff --git a/src/Roslyn.Diagnostics.Analyzers/CSharp/CSharpSymbolDeclaredEventMustBeGeneratedForSourceSymbols.cs b/src/Roslyn.Diagnostics.Analyzers/CSharp/CSharpSymbolDeclaredEventMustBeGeneratedForSourceSymbols.cs index 95a381a868..325474f17c 100644 --- a/src/Roslyn.Diagnostics.Analyzers/CSharp/CSharpSymbolDeclaredEventMustBeGeneratedForSourceSymbols.cs +++ b/src/Roslyn.Diagnostics.Analyzers/CSharp/CSharpSymbolDeclaredEventMustBeGeneratedForSourceSymbols.cs @@ -2,6 +2,7 @@ using System.Collections.Immutable; using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; @@ -23,7 +24,7 @@ public class CSharpSymbolDeclaredEventAnalyzer : SymbolDeclaredEventAnalyzer { - var mefV1ExportAttribute = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionExportAttribute); - var mefV2ExportAttribute = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCompositionExportAttribute); + var mefV1ExportAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionExportAttribute); + var mefV2ExportAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCompositionExportAttribute); if (mefV1ExportAttribute == null || mefV2ExportAttribute == null) { // We don't need to check assemblies unless they're referencing both versions of MEF, so we're done return; }; - var attributeUsageAttribute = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemAttributeUsageAttribute); + var attributeUsageAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemAttributeUsageAttribute); var exportAttributes = new List() { mefV1ExportAttribute, mefV2ExportAttribute }; compilationContext.RegisterSymbolAction(c => AnalyzeSymbol(c, exportAttributes, attributeUsageAttribute), SymbolKind.NamedType); diff --git a/src/Roslyn.Diagnostics.Analyzers/Core/DoNotUseGenericCodeActionCreateToCreateCodeAction.cs b/src/Roslyn.Diagnostics.Analyzers/Core/DoNotUseGenericCodeActionCreateToCreateCodeAction.cs index 12b86e5e99..87f8a476b4 100644 --- a/src/Roslyn.Diagnostics.Analyzers/Core/DoNotUseGenericCodeActionCreateToCreateCodeAction.cs +++ b/src/Roslyn.Diagnostics.Analyzers/Core/DoNotUseGenericCodeActionCreateToCreateCodeAction.cs @@ -5,6 +5,7 @@ using System.Linq; using System.Threading; using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; @@ -41,7 +42,7 @@ private void OnCompilationStart(CompilationStartAnalysisContext context) { context.CancellationToken.ThrowIfCancellationRequested(); - var codeActionSymbol = context.Compilation.GetTypeByMetadataName(CodeActionMetadataName); + var codeActionSymbol = context.Compilation.GetOrCreateTypeByMetadataName(CodeActionMetadataName); if (codeActionSymbol == null) { return; diff --git a/src/Roslyn.Diagnostics.Analyzers/Core/ExportedPartsShouldHaveImportingConstructor.cs b/src/Roslyn.Diagnostics.Analyzers/Core/ExportedPartsShouldHaveImportingConstructor.cs index ce4bc604be..8f1d6bb388 100644 --- a/src/Roslyn.Diagnostics.Analyzers/Core/ExportedPartsShouldHaveImportingConstructor.cs +++ b/src/Roslyn.Diagnostics.Analyzers/Core/ExportedPartsShouldHaveImportingConstructor.cs @@ -43,11 +43,11 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(compilationContext => { - var exportAttributeV1 = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionExportAttribute); - var importingConstructorAttributeV1 = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionImportingConstructorAttribute); - var exportAttributeV2 = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCompositionExportAttribute); - var inheritedExportAttribute = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionInheritedExportAttribute); - var importingConstructorAttributeV2 = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCompositionImportingConstructorAttribute); + var exportAttributeV1 = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionExportAttribute); + var importingConstructorAttributeV1 = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionImportingConstructorAttribute); + var exportAttributeV2 = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCompositionExportAttribute); + var inheritedExportAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionInheritedExportAttribute); + var importingConstructorAttributeV2 = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCompositionImportingConstructorAttribute); if (exportAttributeV1 is null && exportAttributeV2 is null) { diff --git a/src/Roslyn.Diagnostics.Analyzers/Core/ImportingConstructorShouldBeObsolete.cs b/src/Roslyn.Diagnostics.Analyzers/Core/ImportingConstructorShouldBeObsolete.cs index d6827bfb9a..3b770c8605 100644 --- a/src/Roslyn.Diagnostics.Analyzers/Core/ImportingConstructorShouldBeObsolete.cs +++ b/src/Roslyn.Diagnostics.Analyzers/Core/ImportingConstructorShouldBeObsolete.cs @@ -45,12 +45,12 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(compilationContext => { - var obsoleteAttribute = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemObsoleteAttribute); - var exportAttributeV1 = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionExportAttribute); - var importingConstructorAttributeV1 = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionImportingConstructorAttribute); - var exportAttributeV2 = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCompositionExportAttribute); - var inheritedExportAttribute = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionInheritedExportAttribute); - var importingConstructorAttributeV2 = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCompositionImportingConstructorAttribute); + var obsoleteAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemObsoleteAttribute); + var exportAttributeV1 = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionExportAttribute); + var importingConstructorAttributeV1 = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionImportingConstructorAttribute); + var exportAttributeV2 = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCompositionExportAttribute); + var inheritedExportAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionInheritedExportAttribute); + var importingConstructorAttributeV2 = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCompositionImportingConstructorAttribute); if (exportAttributeV1 is null && exportAttributeV2 is null) { diff --git a/src/Roslyn.Diagnostics.Analyzers/Core/ImportingConstructorShouldBeObsoleteCodeFixProvider.cs b/src/Roslyn.Diagnostics.Analyzers/Core/ImportingConstructorShouldBeObsoleteCodeFixProvider.cs index 3db3454d23..327edb6436 100644 --- a/src/Roslyn.Diagnostics.Analyzers/Core/ImportingConstructorShouldBeObsoleteCodeFixProvider.cs +++ b/src/Roslyn.Diagnostics.Analyzers/Core/ImportingConstructorShouldBeObsoleteCodeFixProvider.cs @@ -7,6 +7,7 @@ using System.Threading; using System.Threading.Tasks; using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CodeActions; using Microsoft.CodeAnalysis.CodeFixes; @@ -81,7 +82,7 @@ private async Task AddObsoleteAttributeAsync(Document document, TextSp { var root = await document.GetSyntaxRootAsync(cancellationToken).ConfigureAwait(false); var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false); - var obsoleteAttributeSymbol = semanticModel.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemObsoleteAttribute); + var obsoleteAttributeSymbol = semanticModel.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemObsoleteAttribute); if (obsoleteAttributeSymbol is null) { return document; @@ -235,7 +236,7 @@ private async Task SetErrorToTrueAsync(Document document, TextSpan sou private static SyntaxNode GenerateDescriptionArgument(SyntaxGenerator generator, SemanticModel semanticModel) { - var mefConstructionType = semanticModel.Compilation.GetTypeByMetadataName(WellKnownTypeNames.MicrosoftCodeAnalysisHostMefMefConstruction); + var mefConstructionType = semanticModel.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftCodeAnalysisHostMefMefConstruction); var knownConstant = mefConstructionType?.GetMembers("ImportingConstructorMessage").OfType().Any(); SyntaxNode attributeArgument; diff --git a/src/Roslyn.Diagnostics.Analyzers/Core/PartsExportedWithMEFv2MustBeMarkedAsShared.cs b/src/Roslyn.Diagnostics.Analyzers/Core/PartsExportedWithMEFv2MustBeMarkedAsShared.cs index 9cdea6c14c..a9f479aabd 100644 --- a/src/Roslyn.Diagnostics.Analyzers/Core/PartsExportedWithMEFv2MustBeMarkedAsShared.cs +++ b/src/Roslyn.Diagnostics.Analyzers/Core/PartsExportedWithMEFv2MustBeMarkedAsShared.cs @@ -39,8 +39,8 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(compilationContext => { - var exportAttribute = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCompositionExportAttribute); - var attributeUsageAttribute = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemAttributeUsageAttribute); + var exportAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCompositionExportAttribute); + var attributeUsageAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemAttributeUsageAttribute); if (exportAttribute == null) { diff --git a/src/Roslyn.Diagnostics.Analyzers/Core/SpecializedEnumerableCreationAnalyzer.cs b/src/Roslyn.Diagnostics.Analyzers/Core/SpecializedEnumerableCreationAnalyzer.cs index 01b6bbd4db..579f116364 100644 --- a/src/Roslyn.Diagnostics.Analyzers/Core/SpecializedEnumerableCreationAnalyzer.cs +++ b/src/Roslyn.Diagnostics.Analyzers/Core/SpecializedEnumerableCreationAnalyzer.cs @@ -4,6 +4,7 @@ using System.Collections.Immutable; using System.Linq; using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Diagnostics; @@ -53,7 +54,7 @@ public override void Initialize(AnalysisContext analysisContext) analysisContext.RegisterCompilationStartAction( (context) => { - INamedTypeSymbol specializedCollectionsSymbol = context.Compilation.GetTypeByMetadataName(SpecializedCollectionsMetadataName); + INamedTypeSymbol specializedCollectionsSymbol = context.Compilation.GetOrCreateTypeByMetadataName(SpecializedCollectionsMetadataName); if (specializedCollectionsSymbol == null) { // TODO: In the future, we may want to run this analyzer even if the SpecializedCollections @@ -63,13 +64,13 @@ public override void Initialize(AnalysisContext analysisContext) return; } - INamedTypeSymbol genericEnumerableSymbol = context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericIEnumerable1); + INamedTypeSymbol genericEnumerableSymbol = context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCollectionsGenericIEnumerable1); if (genericEnumerableSymbol == null) { return; } - INamedTypeSymbol linqEnumerableSymbol = context.Compilation.GetTypeByMetadataName(LinqEnumerableMetadataName); + INamedTypeSymbol linqEnumerableSymbol = context.Compilation.GetOrCreateTypeByMetadataName(LinqEnumerableMetadataName); if (linqEnumerableSymbol == null) { return; diff --git a/src/Roslyn.Diagnostics.Analyzers/Core/SymbolDeclaredEventMustBeGeneratedForSourceSymbols.cs b/src/Roslyn.Diagnostics.Analyzers/Core/SymbolDeclaredEventMustBeGeneratedForSourceSymbols.cs index 4aa432b83b..0266dffc9e 100644 --- a/src/Roslyn.Diagnostics.Analyzers/Core/SymbolDeclaredEventMustBeGeneratedForSourceSymbols.cs +++ b/src/Roslyn.Diagnostics.Analyzers/Core/SymbolDeclaredEventMustBeGeneratedForSourceSymbols.cs @@ -41,7 +41,7 @@ public sealed override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(compilationContext => { - INamedTypeSymbol symbolType = compilationContext.Compilation.GetTypeByMetadataName(s_fullNameOfSymbol); + INamedTypeSymbol symbolType = compilationContext.Compilation.GetOrCreateTypeByMetadataName(s_fullNameOfSymbol); if (symbolType != null) { CompilationAnalyzer compilationAnalyzer = GetCompilationAnalyzer(compilationContext.Compilation, symbolType); diff --git a/src/Roslyn.Diagnostics.Analyzers/Core/TestExportsShouldNotBeDiscoverable.cs b/src/Roslyn.Diagnostics.Analyzers/Core/TestExportsShouldNotBeDiscoverable.cs index ee4762a4bf..3d58911aeb 100644 --- a/src/Roslyn.Diagnostics.Analyzers/Core/TestExportsShouldNotBeDiscoverable.cs +++ b/src/Roslyn.Diagnostics.Analyzers/Core/TestExportsShouldNotBeDiscoverable.cs @@ -44,10 +44,10 @@ public override void Initialize(AnalysisContext context) context.RegisterCompilationStartAction(compilationContext => { - var exportAttributeV1 = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionExportAttribute); - var exportAttributeV2 = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemCompositionExportAttribute); - var inheritedExportAttribute = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionInheritedExportAttribute); - var attributeUsageAttribute = compilationContext.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemAttributeUsageAttribute); + var exportAttributeV1 = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionExportAttribute); + var exportAttributeV2 = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemCompositionExportAttribute); + var inheritedExportAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemComponentModelCompositionInheritedExportAttribute); + var attributeUsageAttribute = compilationContext.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemAttributeUsageAttribute); if (exportAttributeV1 is null && exportAttributeV2 is null) { diff --git a/src/Roslyn.Diagnostics.Analyzers/VisualBasic/BasicSymbolDeclaredEventMustBeGeneratedForSourceSymbols.vb b/src/Roslyn.Diagnostics.Analyzers/VisualBasic/BasicSymbolDeclaredEventMustBeGeneratedForSourceSymbols.vb index 6527b23fcf..52a1878b7a 100644 --- a/src/Roslyn.Diagnostics.Analyzers/VisualBasic/BasicSymbolDeclaredEventMustBeGeneratedForSourceSymbols.vb +++ b/src/Roslyn.Diagnostics.Analyzers/VisualBasic/BasicSymbolDeclaredEventMustBeGeneratedForSourceSymbols.vb @@ -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. Imports System.Collections.Immutable +Imports Analyzer.Utilities.Extensions Imports Microsoft.CodeAnalysis Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic @@ -15,12 +16,12 @@ Namespace Roslyn.Diagnostics.VisualBasic.Analyzers Private Const SourceModuleTypeFullName As String = "Microsoft.CodeAnalysis.VisualBasic.Symbols.SourceModuleSymbol" Protected Overrides Function GetCompilationAnalyzer(compilation As Compilation, symbolType As INamedTypeSymbol) As CompilationAnalyzer - Dim compilationType = compilation.GetTypeByMetadataName(GetType(VisualBasicCompilation).FullName) + Dim compilationType = compilation.GetOrCreateTypeByMetadataName(GetType(VisualBasicCompilation).FullName) If compilationType Is Nothing Then Return Nothing End If - Dim sourceModuleType = compilation.GetTypeByMetadataName(SourceModuleTypeFullName) + Dim sourceModuleType = compilation.GetOrCreateTypeByMetadataName(SourceModuleTypeFullName) If sourceModuleType Is Nothing Then Return Nothing End If diff --git a/src/Utilities/Compiler/DoNotCatchGeneralUnlessRethrown.cs b/src/Utilities/Compiler/DoNotCatchGeneralUnlessRethrown.cs index c1c905ca59..4aef2b2789 100644 --- a/src/Utilities/Compiler/DoNotCatchGeneralUnlessRethrown.cs +++ b/src/Utilities/Compiler/DoNotCatchGeneralUnlessRethrown.cs @@ -82,7 +82,7 @@ public override void Initialize(AnalysisContext analysisContext) private INamedTypeSymbol GetRequiredAttributeType(Compilation compilation) { - return compilation.GetTypeByMetadataName(_enablingMethodAttributeFullyQualifiedName); + return compilation.GetOrCreateTypeByMetadataName(_enablingMethodAttributeFullyQualifiedName); } private bool MethodHasAttribute(IMethodSymbol method, INamedTypeSymbol attributeType) diff --git a/src/Utilities/Compiler/Extensions/CompilationExtensions.cs b/src/Utilities/Compiler/Extensions/CompilationExtensions.cs index 259549a5ca..1072ef120a 100644 --- a/src/Utilities/Compiler/Extensions/CompilationExtensions.cs +++ b/src/Utilities/Compiler/Extensions/CompilationExtensions.cs @@ -8,61 +8,6 @@ namespace Analyzer.Utilities.Extensions /// internal static class CompilationExtensions { - /// - /// Gets the type within the compilation's assembly using its canonical CLR metadata name. If not found, gets the first public type from all referenced assemblies. If not found, gets the first type from all referenced assemblies. - /// - /// The compilation. - /// The fully qualified metadata name. - /// A if found; otherwise. - internal static INamedTypeSymbol GetVisibleTypeByMetadataName(this Compilation compilation, string fullyQualifiedMetadataName) - { - var typeSymbol = compilation.GetTypeByMetadataName(fullyQualifiedMetadataName); - if (typeSymbol is object) - { - return typeSymbol; - } - - var segments = fullyQualifiedMetadataName.Split('.'); - - var @namespace = compilation.GlobalNamespace; - - for (var s = 0; s < segments.Length - 1; s++) - { - @namespace = @namespace.GetMembers(segments[s]).OfType().SingleOrDefault(); - - if (@namespace is null) - { - return null; - } - } - - var metadataName = segments[segments.Length - 1]; - INamedTypeSymbol publicType = null; - INamedTypeSymbol anyType = null; - - foreach (var member in @namespace.GetMembers()) - { - if (member is INamedTypeSymbol type && type.MetadataName == metadataName) - { - if (type.ContainingAssembly.Equals(compilation.Assembly)) - { - return type; - } - else if (publicType is null && type.DeclaredAccessibility == Accessibility.Public) - { - publicType = type; - break; - } - else if (anyType is null) - { - anyType = type; - } - } - } - - return publicType ?? anyType; - } - /// /// Gets a type by its full type name and cache it at the compilation level. /// diff --git a/src/Utilities/Compiler/Extensions/OperationBlockAnalysisContextExtension.cs b/src/Utilities/Compiler/Extensions/OperationBlockAnalysisContextExtension.cs index a4508a7313..0908c41ba7 100644 --- a/src/Utilities/Compiler/Extensions/OperationBlockAnalysisContextExtension.cs +++ b/src/Utilities/Compiler/Extensions/OperationBlockAnalysisContextExtension.cs @@ -62,8 +62,8 @@ static bool IsSingleStatementBody(IBlockOperation body) innerOperation is IThrowOperation throwOperation && throwOperation.GetThrownExceptionType() is ITypeSymbol createdExceptionType) { - if (Equals(context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemNotImplementedException), createdExceptionType.OriginalDefinition) - || Equals(context.Compilation.GetTypeByMetadataName(WellKnownTypeNames.SystemNotSupportedException), createdExceptionType.OriginalDefinition)) + if (Equals(context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNotImplementedException), createdExceptionType.OriginalDefinition) + || Equals(context.Compilation.GetOrCreateTypeByMetadataName(WellKnownTypeNames.SystemNotSupportedException), createdExceptionType.OriginalDefinition)) { return true; } diff --git a/src/Utilities/Compiler/WellKnownTypeProvider.cs b/src/Utilities/Compiler/WellKnownTypeProvider.cs index 2e5f94c6a9..aee76962ed 100644 --- a/src/Utilities/Compiler/WellKnownTypeProvider.cs +++ b/src/Utilities/Compiler/WellKnownTypeProvider.cs @@ -2,6 +2,8 @@ using System; using System.Collections.Concurrent; +using System.Linq; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; namespace Analyzer.Utilities @@ -46,7 +48,53 @@ public bool TryGetOrCreateTypeByMetadataName(string fullTypeName, out INamedType { namedTypeSymbol = _fullNameToTypeMap.GetOrAdd( fullTypeName, - (string s) => Compilation.GetTypeByMetadataName(s)); // Caching null results in our cache is intended. + fullyQualifiedMetadataName => + { + // Caching null results in our cache is intended. + +#pragma warning disable RS0030 // Do not used banned APIs + // Use of Compilation.GetTypeByMetadataName is allowed here (this is our wrapper for it which + // includes fallback handling for cases where GetTypeByMetadataName returns null). + var type = Compilation.GetTypeByMetadataName(fullyQualifiedMetadataName); +#pragma warning restore RS0030 // Do not used banned APIs + + type ??= Compilation.Assembly.GetTypeByMetadataName(fullyQualifiedMetadataName); + if (type is null) + { + foreach (var module in Compilation.Assembly.Modules) + { + foreach (var referencedAssembly in module.ReferencedAssemblySymbols) + { + var currentType = referencedAssembly.GetTypeByMetadataName(fullyQualifiedMetadataName); + if (currentType is null) + { + continue; + } + + switch (currentType.GetResultantVisibility()) + { + case SymbolVisibility.Public: + case SymbolVisibility.Internal when referencedAssembly.GivesAccessTo(Compilation.Assembly): + break; + + default: + continue; + } + + if (type is object) + { + // Multiple visible types with the same metadata name are present. + return null; + } + + type = currentType; + } + } + } + + return type; + }); + return namedTypeSymbol != null; } diff --git a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysisHelper.cs b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysisHelper.cs index 61cf1da419..87ec6d669e 100644 --- a/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysisHelper.cs +++ b/src/Utilities/FlowAnalysis/FlowAnalysis/Analysis/DisposeAnalysis/DisposeAnalysisHelper.cs @@ -60,7 +60,7 @@ private static ImmutableHashSet GetDisposeOwnershipTransferLik var builder = PooledHashSet.GetInstance(); foreach (var typeName in s_disposeOwnershipTransferLikelyTypes) { - INamedTypeSymbol typeSymbol = compilation.GetTypeByMetadataName(typeName); + INamedTypeSymbol typeSymbol = compilation.GetOrCreateTypeByMetadataName(typeName); if (typeSymbol != null) { builder.Add(typeSymbol); diff --git a/src/Utilities/Workspaces/SyntaxGeneratorExtensions.cs b/src/Utilities/Workspaces/SyntaxGeneratorExtensions.cs index 9676803acc..90beb1ecbb 100644 --- a/src/Utilities/Workspaces/SyntaxGeneratorExtensions.cs +++ b/src/Utilities/Workspaces/SyntaxGeneratorExtensions.cs @@ -2,6 +2,7 @@ using System.Collections.Generic; using System.Linq; +using Analyzer.Utilities.Extensions; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Editing; @@ -430,7 +431,7 @@ public static SyntaxNode DefaultMethodStatement(this SyntaxGenerator generator, { return generator.ThrowStatement(generator.ObjectCreationExpression( generator.TypeExpression( - compilation.GetTypeByMetadataName(SystemNotImplementedExceptionTypeName)))); + compilation.GetOrCreateTypeByMetadataName(SystemNotImplementedExceptionTypeName)))); } } } \ No newline at end of file