From d461a8d25fa05c82fdd403894796a8989ca2a46c Mon Sep 17 00:00:00 2001 From: Sam Harwell Date: Wed, 21 Jun 2023 16:27:29 -0500 Subject: [PATCH 1/5] Implement RS1038 (Strict compiler reference analysis) --- .../Core/AnalyzerReleases.Unshipped.md | 6 + .../CodeAnalysisDiagnosticsResources.resx | 15 + .../Core/DiagnosticIds.cs | 1 + .../CompilerExtensionStrictApiAnalyzer.cs | 184 +++++++++++ .../CodeAnalysisDiagnosticsResources.cs.xlf | 25 ++ .../CodeAnalysisDiagnosticsResources.de.xlf | 25 ++ .../CodeAnalysisDiagnosticsResources.es.xlf | 25 ++ .../CodeAnalysisDiagnosticsResources.fr.xlf | 25 ++ .../CodeAnalysisDiagnosticsResources.it.xlf | 25 ++ .../CodeAnalysisDiagnosticsResources.ja.xlf | 25 ++ .../CodeAnalysisDiagnosticsResources.ko.xlf | 25 ++ .../CodeAnalysisDiagnosticsResources.pl.xlf | 25 ++ ...CodeAnalysisDiagnosticsResources.pt-BR.xlf | 25 ++ .../CodeAnalysisDiagnosticsResources.ru.xlf | 25 ++ .../CodeAnalysisDiagnosticsResources.tr.xlf | 25 ++ ...deAnalysisDiagnosticsResources.zh-Hans.xlf | 25 ++ ...deAnalysisDiagnosticsResources.zh-Hant.xlf | 25 ++ .../Microsoft.CodeAnalysis.Analyzers.md | 12 + .../Microsoft.CodeAnalysis.Analyzers.sarif | 18 ++ .../RulesMissingDocumentation.md | 1 + ...CompilerExtensionStrictApiAnalyzerTests.cs | 306 ++++++++++++++++++ ...DiagnosticAnalyzerApiUsageAnalyzerTests.cs | 116 ++++--- src/Utilities/Compiler/WellKnownTypeNames.cs | 2 + 23 files changed, 924 insertions(+), 62 deletions(-) create mode 100644 src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/CompilerExtensionStrictApiAnalyzer.cs create mode 100644 src/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/CompilerExtensionStrictApiAnalyzerTests.cs diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/AnalyzerReleases.Unshipped.md b/src/Microsoft.CodeAnalysis.Analyzers/Core/AnalyzerReleases.Unshipped.md index cdf4f1397e..0b96acefcc 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/AnalyzerReleases.Unshipped.md +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/AnalyzerReleases.Unshipped.md @@ -1 +1,7 @@ ; Please do not edit this file manually, it should only be updated through code fix application. + +### New Rules + +Rule ID | Category | Severity | Notes +--------|----------|----------|------- +RS1038 | MicrosoftCodeAnalysisCorrectness | Warning | CompilerExtensionStrictApiAnalyzer diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/CodeAnalysisDiagnosticsResources.resx b/src/Microsoft.CodeAnalysis.Analyzers/Core/CodeAnalysisDiagnosticsResources.resx index c69e20297c..d7b9aa587c 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/CodeAnalysisDiagnosticsResources.resx +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/CodeAnalysisDiagnosticsResources.resx @@ -556,4 +556,19 @@ Specify analyzer banned API enforcement setting + + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + + + Compiler extensions should be implemented in assemblies with compiler-provided references + \ No newline at end of file diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/DiagnosticIds.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/DiagnosticIds.cs index 24dd25557a..41700c3cba 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/DiagnosticIds.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/DiagnosticIds.cs @@ -41,6 +41,7 @@ internal static class DiagnosticIds public const string SymbolIsBannedInAnalyzersRuleId = "RS1035"; public const string NoSettingSpecifiedSymbolIsBannedInAnalyzersRuleId = "RS1036"; public const string AddCompilationEndCustomTagRuleId = "RS1037"; + public const string DoNotRegisterCompilerTypesWithBadAssemblyReferenceRuleId = "RS1038"; // Release tracking analyzer IDs public const string DeclareDiagnosticIdInAnalyzerReleaseRuleId = "RS2000"; diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/CompilerExtensionStrictApiAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/CompilerExtensionStrictApiAnalyzer.cs new file mode 100644 index 0000000000..852de7eadd --- /dev/null +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/CompilerExtensionStrictApiAnalyzer.cs @@ -0,0 +1,184 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. + +using System.Collections.Immutable; +using System.Diagnostics.CodeAnalysis; +using Analyzer.Utilities; +using Analyzer.Utilities.Extensions; +using Microsoft.CodeAnalysis.Diagnostics; + +namespace Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers +{ + using static CodeAnalysisDiagnosticsResources; + + [DiagnosticAnalyzer(LanguageNames.CSharp, LanguageNames.VisualBasic)] + internal sealed class CompilerExtensionStrictApiAnalyzer : DiagnosticAnalyzer + { + private static readonly LocalizableString s_localizableTitle = CreateLocalizableResourceString(nameof(DoNotRegisterCompilerTypesWithBadAssemblyReferenceRuleTitle)); + private static readonly LocalizableString s_localizableDescription = CreateLocalizableResourceString(nameof(DoNotRegisterCompilerTypesWithBadAssemblyReferenceRuleDescription)); + + public static readonly DiagnosticDescriptor DoNotDeclareCompilerFeatureInAssemblyWithWorkspacesReferenceStrictRule = new( + DiagnosticIds.DoNotRegisterCompilerTypesWithBadAssemblyReferenceRuleId, + s_localizableTitle, + CreateLocalizableResourceString(nameof(DoNotDeclareCompilerFeatureInAssemblyWithWorkspacesReferenceMessage)), + DiagnosticCategory.MicrosoftCodeAnalysisCorrectness, + DiagnosticSeverity.Warning, + isEnabledByDefault: true, + description: s_localizableDescription, + customTags: WellKnownDiagnosticTagsExtensions.Telemetry); + + public static readonly DiagnosticDescriptor DoNotDeclareCSharpCompilerFeatureInAssemblyWithVisualBasicReferenceStrictRule = new( + DiagnosticIds.DoNotRegisterCompilerTypesWithBadAssemblyReferenceRuleId, + s_localizableTitle, + CreateLocalizableResourceString(nameof(DoNotDeclareCSharpCompilerFeatureInAssemblyWithVisualBasicReferenceMessage)), + DiagnosticCategory.MicrosoftCodeAnalysisCorrectness, + DiagnosticSeverity.Warning, + isEnabledByDefault: true, + description: s_localizableDescription, + customTags: WellKnownDiagnosticTagsExtensions.Telemetry); + + public static readonly DiagnosticDescriptor DoNotDeclareVisualBasicCompilerFeatureInAssemblyWithCSharpReferenceStrictRule = new( + DiagnosticIds.DoNotRegisterCompilerTypesWithBadAssemblyReferenceRuleId, + s_localizableTitle, + CreateLocalizableResourceString(nameof(DoNotDeclareVisualBasicCompilerFeatureInAssemblyWithCSharpReferenceMessage)), + DiagnosticCategory.MicrosoftCodeAnalysisCorrectness, + DiagnosticSeverity.Warning, + isEnabledByDefault: true, + description: s_localizableDescription, + customTags: WellKnownDiagnosticTagsExtensions.Telemetry); + + public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create( + DoNotDeclareCompilerFeatureInAssemblyWithWorkspacesReferenceStrictRule, + DoNotDeclareCSharpCompilerFeatureInAssemblyWithVisualBasicReferenceStrictRule, + DoNotDeclareVisualBasicCompilerFeatureInAssemblyWithCSharpReferenceStrictRule); + + public override void Initialize(AnalysisContext context) + { + context.EnableConcurrentExecution(); + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + + context.RegisterCompilationStartAction(context => + { + var typeProvider = WellKnownTypeProvider.GetOrCreate(context.Compilation); + var diagnosticAnalyzer = typeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftCodeAnalysisDiagnosticsDiagnosticAnalyzer); + if (diagnosticAnalyzer is null) + return; + + var referencesWorkspaces = false; + var referencesCSharp = false; + var referencesVisualBasic = false; + foreach (var assemblyName in context.Compilation.ReferencedAssemblyNames) + { + if (assemblyName.Name == "Microsoft.CodeAnalysis.Workspaces") + { + referencesWorkspaces = true; + } + else if (assemblyName.Name == "Microsoft.CodeAnalysis.CSharp") + { + referencesCSharp = true; + } + else if (assemblyName.Name == "Microsoft.CodeAnalysis.VisualBasic") + { + referencesVisualBasic = true; + } + } + + if (!referencesWorkspaces && !referencesCSharp && !referencesVisualBasic) + { + // This compilation doesn't reference any assemblies that would produce warnings by this analyzer + return; + } + + var diagnosticAnalyzerAttribute = typeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftCodeAnalysisDiagnosticsDiagnosticAnalyzerAttribute); + var sourceGeneratorInterface = typeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftCodeAnalysisISourceGenerator); + var incrementalGeneratorInterface = typeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftCodeAnalysisIIncrementalGenerator); + var generatorAttribute = typeProvider.GetOrCreateTypeByMetadataName(WellKnownTypeNames.MicrosoftCodeAnalysisGeneratorAttribute); + + context.RegisterSymbolAction( + context => + { + var namedType = (INamedTypeSymbol)context.Symbol; + if (!IsRegisteredExtension(namedType, diagnosticAnalyzer, diagnosticAnalyzerAttribute, out var applicationSyntaxReference, out var supportsCSharp, out var supportsVisualBasic) + && !IsRegisteredExtension(namedType, sourceGeneratorInterface, generatorAttribute, out applicationSyntaxReference, out supportsCSharp, out supportsVisualBasic) + && !IsRegisteredExtension(namedType, incrementalGeneratorInterface, generatorAttribute, out applicationSyntaxReference, out supportsCSharp, out supportsVisualBasic)) + { + // This is not a compiler extension + return; + } + + DiagnosticDescriptor descriptor; + if (referencesWorkspaces) + { + descriptor = DoNotDeclareCompilerFeatureInAssemblyWithWorkspacesReferenceStrictRule; + } + else if (supportsCSharp && referencesVisualBasic) + { + descriptor = DoNotDeclareCSharpCompilerFeatureInAssemblyWithVisualBasicReferenceStrictRule; + } + else if (supportsVisualBasic && referencesCSharp) + { + descriptor = DoNotDeclareVisualBasicCompilerFeatureInAssemblyWithCSharpReferenceStrictRule; + } + else + { + return; + } + + context.ReportDiagnostic(Diagnostic.Create(descriptor, Location.Create(applicationSyntaxReference.SyntaxTree, applicationSyntaxReference.Span))); + }, + SymbolKind.NamedType); + }); + } + + private static bool IsRegisteredExtension(INamedTypeSymbol extension, [NotNullWhen(true)] INamedTypeSymbol? extensionClassOrInterface, [NotNullWhen(true)] INamedTypeSymbol? registrationAttributeType, [NotNullWhen(true)] out SyntaxReference? node, out bool supportsCSharp, out bool supportsVisualBasic) + { + supportsCSharp = false; + supportsVisualBasic = false; + + if (!extension.Inherits(extensionClassOrInterface)) + { + node = null; + return false; + } + + foreach (var attribute in extension.GetAttributes()) + { + if (!attribute.AttributeClass.Inherits(registrationAttributeType)) + continue; + + foreach (var arg in attribute.ConstructorArguments) + { + CheckLanguage(arg, ref supportsCSharp, ref supportsVisualBasic); + if (arg.Kind == TypedConstantKind.Array) + { + foreach (var element in arg.Values) + { + CheckLanguage(element, ref supportsCSharp, ref supportsVisualBasic); + } + } + } + + node = attribute.ApplicationSyntaxReference; + return true; + } + + node = null; + return false; + } + + private static void CheckLanguage(TypedConstant argument, ref bool supportsCSharp, ref bool supportsVisualBasic) + { + if (argument is { Kind: TypedConstantKind.Primitive, Type.SpecialType: SpecialType.System_String }) + { + string supportedLanguage = (string)argument.Value; + if (supportedLanguage == LanguageNames.CSharp) + { + supportsCSharp = true; + } + else if (supportedLanguage == LanguageNames.VisualBasic) + { + supportsVisualBasic = true; + } + } + } + } +} diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.cs.xlf b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.cs.xlf index a0852b3978..42d8592954 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.cs.xlf +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.cs.xlf @@ -117,6 +117,31 @@ Definujte správně nadpis diagnostiky + + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + + + + Compiler extensions should be implemented in assemblies with compiler-provided references + Compiler extensions should be implemented in assemblies with compiler-provided references + + 'GetSemanticModel' is an expensive method to invoke within a diagnostic analyzer because it creates a completely new semantic model, which does not share compilation data with the compiler or other analyzers. This incurs an additional performance cost during semantic analysis. Instead, consider registering a different analyzer action which allows used of a shared 'SemanticModel', such as 'RegisterOperationAction', 'RegisterSyntaxNodeAction', or 'RegisterSemanticModelAction'. GetSemanticModel je náročná metoda na to, aby se volala v diagnostickém analyzátoru, protože vytváří zcela nový sémantický model, který nesdílí data kompilace s kompilátorem nebo jinými analyzátory. To dále snižuje výkon během analýzy sémantiky. Zvažte místo toho možnost zaregistrovat jinou akci analyzátoru, která umožňuje používat sdílený SemanticModel, třeba RegisterOperationAction, RegisterSyntaxNodeAction nebo RegisterSemanticModelAction. diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.de.xlf b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.de.xlf index 6ab4b31ec5..b01365c239 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.de.xlf +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.de.xlf @@ -117,6 +117,31 @@ Titel der Diagnosemeldung ordnungsgemäß definieren + + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + + + + Compiler extensions should be implemented in assemblies with compiler-provided references + Compiler extensions should be implemented in assemblies with compiler-provided references + + 'GetSemanticModel' is an expensive method to invoke within a diagnostic analyzer because it creates a completely new semantic model, which does not share compilation data with the compiler or other analyzers. This incurs an additional performance cost during semantic analysis. Instead, consider registering a different analyzer action which allows used of a shared 'SemanticModel', such as 'RegisterOperationAction', 'RegisterSyntaxNodeAction', or 'RegisterSemanticModelAction'. "GetSemanticModel" ist eine kostspielige Methode zum Aufruf in einem Diagnoseanalysetool, weil damit ein vollständig neues Semantikmodell erstellt wird, das keine Kompilierungsdaten mit dem Compiler oder anderen Analysetools teilt. Dies führt zu zusätzlichen Leistungseinbußen bei der Semantikanalyse. Erwägen Sie stattdessen die Registrierung einer anderen Analysetoolaktion, die die Verwendung eines freigegebenen "SemanticModel" wie z. B. "RegisterOperationAction", "RegisterSyntaxNodeAction" oder "RegisterSemanticModelAction" ermöglicht. diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.es.xlf b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.es.xlf index 22be164f26..7c1c4c9c67 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.es.xlf +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.es.xlf @@ -117,6 +117,31 @@ Definir el título del diagnóstico correctamente + + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + + + + Compiler extensions should be implemented in assemblies with compiler-provided references + Compiler extensions should be implemented in assemblies with compiler-provided references + + 'GetSemanticModel' is an expensive method to invoke within a diagnostic analyzer because it creates a completely new semantic model, which does not share compilation data with the compiler or other analyzers. This incurs an additional performance cost during semantic analysis. Instead, consider registering a different analyzer action which allows used of a shared 'SemanticModel', such as 'RegisterOperationAction', 'RegisterSyntaxNodeAction', or 'RegisterSemanticModelAction'. "GetSemanticModel" es un método caro para invocar dentro de un analizador de diagnóstico porque crea un modelo semántico completamente nuevo que no comparte datos de compilación con el compilador u otros analizadores. Como consecuencia, se generan costos de rendimiento adicionales durante el análisis semántico. En su lugar, podría registrar una acción del analizador diferente que permita usar un elemento "SemanticModel" compartido, como "RegisterOperationAction", "RegisterSyntaxNodeAction" o "RegisterSemanticModelAction". diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.fr.xlf b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.fr.xlf index 56632bc6d9..701bfc7fbf 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.fr.xlf +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.fr.xlf @@ -117,6 +117,31 @@ Définir correctement le titre de diagnostic + + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + + + + Compiler extensions should be implemented in assemblies with compiler-provided references + Compiler extensions should be implemented in assemblies with compiler-provided references + + 'GetSemanticModel' is an expensive method to invoke within a diagnostic analyzer because it creates a completely new semantic model, which does not share compilation data with the compiler or other analyzers. This incurs an additional performance cost during semantic analysis. Instead, consider registering a different analyzer action which allows used of a shared 'SemanticModel', such as 'RegisterOperationAction', 'RegisterSyntaxNodeAction', or 'RegisterSemanticModelAction'. 'GetSemanticModel' est une méthode coûteuse à appeler dans un analyseur de diagnostic, car elle crée un modèle sémantique complètement nouveau, qui ne partage pas les données de compilation avec le compilateur ou d'autres analyseurs. Cela entraîne un coût supplémentaire au niveau des performances au moment de l'analyse sémantique. À la place, inscrivez une autre action d'analyseur qui permet d'utiliser un 'SemanticModel' partagé, par exemple 'RegisterOperationAction', 'RegisterSyntaxNodeAction' ou 'RegisterSemanticModelAction'. diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.it.xlf b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.it.xlf index 99718fe985..c09149611a 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.it.xlf +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.it.xlf @@ -117,6 +117,31 @@ Definisci correttamente il titolo della diagnostica + + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + + + + Compiler extensions should be implemented in assemblies with compiler-provided references + Compiler extensions should be implemented in assemblies with compiler-provided references + + 'GetSemanticModel' is an expensive method to invoke within a diagnostic analyzer because it creates a completely new semantic model, which does not share compilation data with the compiler or other analyzers. This incurs an additional performance cost during semantic analysis. Instead, consider registering a different analyzer action which allows used of a shared 'SemanticModel', such as 'RegisterOperationAction', 'RegisterSyntaxNodeAction', or 'RegisterSemanticModelAction'. 'GetSemanticModel' è un metodo dispendioso da richiamare in un analizzatore diagnostico perché crea un modello semantico completamente nuovo, che non condivide i dati di compilazione con il compilatore o con altri analizzatori, comportando un ulteriore costo in termini di prestazioni durante l'analisi semantica. Provare invece a registrare un'azione diversa dell'analizzatore che consenta l'uso di un elemento 'SemanticModel' condiviso, come 'RegisterOperationAction', 'RegisterSyntaxNodeAction' o 'RegisterSemanticModelAction'. diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.ja.xlf b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.ja.xlf index b727619c3d..2f1e534b2c 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.ja.xlf +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.ja.xlf @@ -117,6 +117,31 @@ 診断タイトルを正しく定義する + + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + + + + Compiler extensions should be implemented in assemblies with compiler-provided references + Compiler extensions should be implemented in assemblies with compiler-provided references + + 'GetSemanticModel' is an expensive method to invoke within a diagnostic analyzer because it creates a completely new semantic model, which does not share compilation data with the compiler or other analyzers. This incurs an additional performance cost during semantic analysis. Instead, consider registering a different analyzer action which allows used of a shared 'SemanticModel', such as 'RegisterOperationAction', 'RegisterSyntaxNodeAction', or 'RegisterSemanticModelAction'. 'GetSemanticModel' は、コンパイラやその他のアナライザーとコンパイル データを共有しないまったく新しいセマンティック モデルを作成するため、診断アナライザー内で呼び出すのにコストの高い方法です。セマンティック分析中に追加のパフォーマンス コストが発生します。代わりに、'RegisterOperationAction'、'RegisterSyntaxNodeAction'、'RegisterSemanticModelAction' など、共有されている 'SemanticModel' を使用できる別のアナライザー操作を登録することをご検討ください。 diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.ko.xlf b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.ko.xlf index 8bcf46423e..7e898bf104 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.ko.xlf +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.ko.xlf @@ -117,6 +117,31 @@ 진단 제목을 올바르게 정의 + + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + + + + Compiler extensions should be implemented in assemblies with compiler-provided references + Compiler extensions should be implemented in assemblies with compiler-provided references + + 'GetSemanticModel' is an expensive method to invoke within a diagnostic analyzer because it creates a completely new semantic model, which does not share compilation data with the compiler or other analyzers. This incurs an additional performance cost during semantic analysis. Instead, consider registering a different analyzer action which allows used of a shared 'SemanticModel', such as 'RegisterOperationAction', 'RegisterSyntaxNodeAction', or 'RegisterSemanticModelAction'. 'GetSemanticModel'은 컴파일러나 다른 분석기와 컴파일 데이터를 공유하지 않는 완전히 새로운 의미 체계 모델을 만들므로 진단 분석기 내에서 호출하는 데 부담이 큰 메서드입니다. 이 메서드를 사용하면 의미 체계 분석 중 추가 성능 비용이 발생합니다. 대신 공유 'SemanticModel'을 사용할 수 있는 'RegisterOperationAction', 'RegisterSyntaxNodeAction', 'RegisterSemanticModelAction' 등과 같은 다른 분석기 작업을 등록하세요. diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.pl.xlf b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.pl.xlf index cd479bb4ff..b2b0c4c6ef 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.pl.xlf +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.pl.xlf @@ -117,6 +117,31 @@ Poprawnie zdefiniuj tytuł diagnostyki + + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + + + + Compiler extensions should be implemented in assemblies with compiler-provided references + Compiler extensions should be implemented in assemblies with compiler-provided references + + 'GetSemanticModel' is an expensive method to invoke within a diagnostic analyzer because it creates a completely new semantic model, which does not share compilation data with the compiler or other analyzers. This incurs an additional performance cost during semantic analysis. Instead, consider registering a different analyzer action which allows used of a shared 'SemanticModel', such as 'RegisterOperationAction', 'RegisterSyntaxNodeAction', or 'RegisterSemanticModelAction'. Wywołanie metody „GetSemanticModel” w analizatorze diagnostycznym jest kosztowne, ponieważ powoduje utworzenie całkowicie nowego modelu semantycznego, który nie współdzieli danych kompilacji z kompilatorem ani innymi analizatorami. Wiąże się to z dodatkowym kosztem wydajności podczas analizy semantycznej. Zamiast tego rozważ zarejestrowanie innej akcji analizatora, która umożliwia użycie współdzielonego modelu „SemanticModel”, takiego jak „RegisterOperationAction”, „RegisterSyntaxNodeAction” lub „RegisterSemanticModelAction”. diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.pt-BR.xlf b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.pt-BR.xlf index 8e3d9a10db..9267d2dc81 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.pt-BR.xlf +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.pt-BR.xlf @@ -117,6 +117,31 @@ Definir o título de diagnóstico corretamente + + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + + + + Compiler extensions should be implemented in assemblies with compiler-provided references + Compiler extensions should be implemented in assemblies with compiler-provided references + + 'GetSemanticModel' is an expensive method to invoke within a diagnostic analyzer because it creates a completely new semantic model, which does not share compilation data with the compiler or other analyzers. This incurs an additional performance cost during semantic analysis. Instead, consider registering a different analyzer action which allows used of a shared 'SemanticModel', such as 'RegisterOperationAction', 'RegisterSyntaxNodeAction', or 'RegisterSemanticModelAction'. 'GetSemanticModel' é um método caro para ser invocado em um analisador de diagnóstico porque ele cria um modelo semântico completamente novo, que não compartilha dados de compilação com o compilador ou com outros analisadores. Isso gera um custo de desempenho adicional durante a análise semântica. Nesse caso, considere o registro de uma ação do analisador diferente que permita o uso de um 'SemanticModel' compartilhado, como 'RegisterOperationAction', 'RegisterSyntaxNodeAction' ou 'RegisterSemanticModelAction'. diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.ru.xlf b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.ru.xlf index baeeb5ead3..c27c845bdf 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.ru.xlf +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.ru.xlf @@ -117,6 +117,31 @@ Укажите название диагностики правильно + + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + + + + Compiler extensions should be implemented in assemblies with compiler-provided references + Compiler extensions should be implemented in assemblies with compiler-provided references + + 'GetSemanticModel' is an expensive method to invoke within a diagnostic analyzer because it creates a completely new semantic model, which does not share compilation data with the compiler or other analyzers. This incurs an additional performance cost during semantic analysis. Instead, consider registering a different analyzer action which allows used of a shared 'SemanticModel', such as 'RegisterOperationAction', 'RegisterSyntaxNodeAction', or 'RegisterSemanticModelAction'. "GetSemanticModel" является затратным методом для вызова в диагностическом анализаторе, так как при этом создается совершенно новая семантическая модель, которая не использует данные компиляции совместно с компилятором или другими анализаторами. Это приводит к снижению производительности во время семантического анализа. Вместо этого попробуйте зарегистрировать другое действие анализатора, которое позволит использовать общую модель "SemanticModel", например "RegisterOperationAction", "RegisterSyntaxNodeAction" или "RegisterSemanticModelAction". diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.tr.xlf b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.tr.xlf index 4863753cb9..f35ebd0746 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.tr.xlf +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.tr.xlf @@ -117,6 +117,31 @@ Tanılama başlığını doğru tanımlayın + + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + + + + Compiler extensions should be implemented in assemblies with compiler-provided references + Compiler extensions should be implemented in assemblies with compiler-provided references + + 'GetSemanticModel' is an expensive method to invoke within a diagnostic analyzer because it creates a completely new semantic model, which does not share compilation data with the compiler or other analyzers. This incurs an additional performance cost during semantic analysis. Instead, consider registering a different analyzer action which allows used of a shared 'SemanticModel', such as 'RegisterOperationAction', 'RegisterSyntaxNodeAction', or 'RegisterSemanticModelAction'. 'GetSemanticModel', derleme verilerini derleyici veya diğer çözümleyiciler ile paylaşmayan tamamen yeni bir anlam modeli oluşturduğundan bir tanılama çözümleyicisi içinde çağırmak için pahalı bir yöntemdir. Bu işlem, anlamsal analiz sırasında ek bir performans maliyetine neden olur. Bunun yerine, 'RegisterOperationAction', 'RegisterSyntaxNodeAction' veya 'RegisterSemanticModelAction' gibi paylaşılan bir 'SemanticModel' kullanılmasına izin veren farklı bir çözümleyici eylemini kaydetmeyi deneyin. diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.zh-Hans.xlf b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.zh-Hans.xlf index 52398b5b69..0b219c67d1 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.zh-Hans.xlf +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.zh-Hans.xlf @@ -117,6 +117,31 @@ 正确定义诊断标题 + + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + + + + Compiler extensions should be implemented in assemblies with compiler-provided references + Compiler extensions should be implemented in assemblies with compiler-provided references + + 'GetSemanticModel' is an expensive method to invoke within a diagnostic analyzer because it creates a completely new semantic model, which does not share compilation data with the compiler or other analyzers. This incurs an additional performance cost during semantic analysis. Instead, consider registering a different analyzer action which allows used of a shared 'SemanticModel', such as 'RegisterOperationAction', 'RegisterSyntaxNodeAction', or 'RegisterSemanticModelAction'. "GetSemanticModel" 是在诊断分析器中调用的昂贵方法,因为它创建了一个全新的语义模型,该语义模型不与编译器或其他分析器共享编译数据。这会在语义分析期间产生额外的性能开销。请考虑改为注册允许使用共享 "SemanticModel" (如 "RegisterOperationAction"、"RegisterSyntaxNodeAction" 或 "RegisterSemanticModelAction")的其他分析器操作。 diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.zh-Hant.xlf b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.zh-Hant.xlf index 9f05a1e845..70e4261ce7 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.zh-Hant.xlf +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/xlf/CodeAnalysisDiagnosticsResources.zh-Hant.xlf @@ -117,6 +117,31 @@ 正確定義診斷標題 + + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This C# compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.VisualBasic. The Microsoft.CodeAnalysis.VisualBasic assembly is not always provided during C# compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.Workspaces. The Microsoft.CodeAnalysis.Workspaces assembly is not provided during command line compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + This Visual Basic compiler extension should not be implemented in an assembly containing a reference to Microsoft.CodeAnalysis.CSharp. The Microsoft.CodeAnalysis.CSharp assembly is not always provided during Visual Basic compilation scenarios, so references to it could cause the compiler extension to behave unpredictably. + + + + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + + + + Compiler extensions should be implemented in assemblies with compiler-provided references + Compiler extensions should be implemented in assemblies with compiler-provided references + + 'GetSemanticModel' is an expensive method to invoke within a diagnostic analyzer because it creates a completely new semantic model, which does not share compilation data with the compiler or other analyzers. This incurs an additional performance cost during semantic analysis. Instead, consider registering a different analyzer action which allows used of a shared 'SemanticModel', such as 'RegisterOperationAction', 'RegisterSyntaxNodeAction', or 'RegisterSemanticModelAction'. 在診斷分析器內叫用方法時,'GetSemanticModel' 是成本較高的方法,原因是其會建立全新的語意模型,而不會與編譯器或其他分析器共用編譯資料,此舉會在分析語意期間產生額外的效能成本。請改為考慮註冊不同的分析器動作,以允許使用共用的 'SemanticModel',例如 'RegisterOperationAction'、'RegisterSyntaxNodeAction' 或 'RegisterSemanticModelAction'。 diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.md b/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.md index 8206571925..e41738d3d4 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.md +++ b/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.md @@ -460,6 +460,18 @@ A project containing analyzers or source generators should specify the property |CodeFix|False| --- +## RS1038: Compiler extensions should be implemented in assemblies with compiler-provided references + +Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisCorrectness| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| +--- + ## [RS2000](https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md): Add analyzer diagnostic IDs to analyzer release All supported analyzer diagnostic IDs should be part of an analyzer release. diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.sarif b/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.sarif index fb87180237..79f9790be3 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.sarif +++ b/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.sarif @@ -475,6 +475,24 @@ ] } }, + "RS1038": { + "id": "RS1038", + "shortDescription": "Compiler extensions should be implemented in assemblies with compiler-provided references", + "fullDescription": "Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably.", + "defaultLevel": "warning", + "properties": { + "category": "MicrosoftCodeAnalysisCorrectness", + "isEnabledByDefault": true, + "typeName": "CompilerExtensionStrictApiAnalyzer", + "languages": [ + "C#", + "Visual Basic" + ], + "tags": [ + "Telemetry" + ] + } + }, "RS2000": { "id": "RS2000", "shortDescription": "Add analyzer diagnostic IDs to analyzer release", diff --git a/src/Microsoft.CodeAnalysis.Analyzers/RulesMissingDocumentation.md b/src/Microsoft.CodeAnalysis.Analyzers/RulesMissingDocumentation.md index 1bb4f4c8d7..54222676dc 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/RulesMissingDocumentation.md +++ b/src/Microsoft.CodeAnalysis.Analyzers/RulesMissingDocumentation.md @@ -38,3 +38,4 @@ RS1034 | | Prefer 'IsKind' for checking syntax kinds | RS1035 | | Do not use APIs banned for analyzers | RS1036 | | Specify analyzer banned API enforcement setting | RS1037 | | Add "CompilationEnd" custom tag to compilation end diagnostic descriptor | +RS1038 | | Compiler extensions should be implemented in assemblies with compiler-provided references | diff --git a/src/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/CompilerExtensionStrictApiAnalyzerTests.cs b/src/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/CompilerExtensionStrictApiAnalyzerTests.cs new file mode 100644 index 0000000000..4154ea04f3 --- /dev/null +++ b/src/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/CompilerExtensionStrictApiAnalyzerTests.cs @@ -0,0 +1,306 @@ +// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information. + +using System; +using System.Collections.Immutable; +using System.Threading.Tasks; +using Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers; +using Microsoft.CodeAnalysis.Testing; +using Xunit; +using VerifyCS = Test.Utilities.CSharpCodeFixVerifier< + Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers.CompilerExtensionStrictApiAnalyzer, + Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; +using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier< + Microsoft.CodeAnalysis.Analyzers.MetaAnalyzers.CompilerExtensionStrictApiAnalyzer, + Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>; + +namespace Microsoft.CodeAnalysis.Analyzers.UnitTests.MetaAnalyzers +{ + public class CompilerExtensionStrictApiAnalyzerTests + { + private const string CompilerReferenceVersion = "4.6.0"; + + public enum ImplementationLanguage + { + CSharp, + VisualBasic, + } + + public enum SupportedLanguage + { + CSharp, + VisualBasic, + CSharpAndVisualBasic, + } + + public enum CompilerFeature + { + DiagnosticAnalyzer, + DiagnosticSuppressor, + ISourceGenerator, + IIncrementalGenerator, + } + + [Theory] + [CombinatorialData] + public async Task CSharpFeatureDefinedWithCommonReference(CompilerFeature feature, SupportedLanguage supportedLanguage) + { + await new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard20.AddPackages(ImmutableArray.Create( + new PackageIdentity("Microsoft.CodeAnalysis.Common", CompilerReferenceVersion))), + TestCode = DefineFeature(ImplementationLanguage.CSharp, feature, supportedLanguage), + }.RunAsync(); + } + + [Theory] + [CombinatorialData] + public async Task CSharpFeatureDefinedWithMatchingLanguageReference(CompilerFeature feature, [CombinatorialValues(SupportedLanguage.CSharp, SupportedLanguage.VisualBasic)] SupportedLanguage supportedLanguage) + { + var matchingPackage = supportedLanguage switch + { + SupportedLanguage.CSharp => "Microsoft.CodeAnalysis.CSharp", + SupportedLanguage.VisualBasic => "Microsoft.CodeAnalysis.VisualBasic", + _ => throw new NotImplementedException(), + }; + + await new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard20.AddPackages(ImmutableArray.Create( + new PackageIdentity(matchingPackage, CompilerReferenceVersion))), + TestCode = DefineFeature(ImplementationLanguage.CSharp, feature, supportedLanguage), + }.RunAsync(); + } + + [Theory] + [CombinatorialData] + public async Task CSharpFeatureDefinedWithWorkspaceReference(CompilerFeature feature, SupportedLanguage supportedLanguage) + { + await new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard20.AddPackages(ImmutableArray.Create( + new PackageIdentity("Microsoft.CodeAnalysis.Workspaces.Common", CompilerReferenceVersion))), + TestCode = DefineFeature(ImplementationLanguage.CSharp, feature, supportedLanguage), + ExpectedDiagnostics = + { + VerifyCS.Diagnostic(CompilerExtensionStrictApiAnalyzer.DoNotDeclareCompilerFeatureInAssemblyWithWorkspacesReferenceStrictRule).WithLocation(0), + }, + }.RunAsync(); + } + + [Theory] + [CombinatorialData] + public async Task CSharpFeatureDefinedWithMismatchedLanguageReference(CompilerFeature feature, SupportedLanguage supportedLanguage) + { + var (mismatchedPackage, descriptor) = supportedLanguage switch + { + SupportedLanguage.CSharp => ("Microsoft.CodeAnalysis.VisualBasic", CompilerExtensionStrictApiAnalyzer.DoNotDeclareCSharpCompilerFeatureInAssemblyWithVisualBasicReferenceStrictRule), + SupportedLanguage.VisualBasic => ("Microsoft.CodeAnalysis.CSharp", CompilerExtensionStrictApiAnalyzer.DoNotDeclareVisualBasicCompilerFeatureInAssemblyWithCSharpReferenceStrictRule), + SupportedLanguage.CSharpAndVisualBasic => ("Microsoft.CodeAnalysis.VisualBasic", CompilerExtensionStrictApiAnalyzer.DoNotDeclareCSharpCompilerFeatureInAssemblyWithVisualBasicReferenceStrictRule), + _ => throw new NotImplementedException(), + }; + + await new VerifyCS.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard20.AddPackages(ImmutableArray.Create( + new PackageIdentity(mismatchedPackage, CompilerReferenceVersion))), + TestCode = DefineFeature(ImplementationLanguage.CSharp, feature, supportedLanguage), + ExpectedDiagnostics = + { + VerifyCS.Diagnostic(descriptor).WithLocation(0), + }, + }.RunAsync(); + } + + [Theory] + [CombinatorialData] + public async Task VisualBasicFeatureDefinedWithCommonReference(CompilerFeature feature, SupportedLanguage supportedLanguage) + { + await new VerifyVB.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard20.AddPackages(ImmutableArray.Create( + new PackageIdentity("Microsoft.CodeAnalysis.Common", CompilerReferenceVersion))), + TestCode = DefineFeature(ImplementationLanguage.VisualBasic, feature, supportedLanguage), + }.RunAsync(); + } + + [Theory] + [CombinatorialData] + public async Task VisualBasicFeatureDefinedWithMatchingLanguageReference(CompilerFeature feature, [CombinatorialValues(SupportedLanguage.CSharp, SupportedLanguage.VisualBasic)] SupportedLanguage supportedLanguage) + { + var matchingPackage = supportedLanguage switch + { + SupportedLanguage.CSharp => "Microsoft.CodeAnalysis.CSharp", + SupportedLanguage.VisualBasic => "Microsoft.CodeAnalysis.VisualBasic", + _ => throw new NotImplementedException(), + }; + + await new VerifyVB.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard20.AddPackages(ImmutableArray.Create( + new PackageIdentity(matchingPackage, CompilerReferenceVersion))), + TestCode = DefineFeature(ImplementationLanguage.VisualBasic, feature, supportedLanguage), + }.RunAsync(); + } + + [Theory] + [CombinatorialData] + public async Task VisualBasicFeatureDefinedWithWorkspaceReference(CompilerFeature feature, SupportedLanguage supportedLanguage) + { + await new VerifyVB.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard20.AddPackages(ImmutableArray.Create( + new PackageIdentity("Microsoft.CodeAnalysis.Workspaces.Common", CompilerReferenceVersion))), + TestCode = DefineFeature(ImplementationLanguage.VisualBasic, feature, supportedLanguage), + ExpectedDiagnostics = + { + VerifyVB.Diagnostic(CompilerExtensionStrictApiAnalyzer.DoNotDeclareCompilerFeatureInAssemblyWithWorkspacesReferenceStrictRule).WithLocation(0), + }, + }.RunAsync(); + } + + [Theory] + [CombinatorialData] + public async Task VisualBasicFeatureDefinedWithMismatchedLanguageReference(CompilerFeature feature, SupportedLanguage supportedLanguage) + { + var (mismatchedPackage, descriptor) = supportedLanguage switch + { + SupportedLanguage.CSharp => ("Microsoft.CodeAnalysis.VisualBasic", CompilerExtensionStrictApiAnalyzer.DoNotDeclareCSharpCompilerFeatureInAssemblyWithVisualBasicReferenceStrictRule), + SupportedLanguage.VisualBasic => ("Microsoft.CodeAnalysis.CSharp", CompilerExtensionStrictApiAnalyzer.DoNotDeclareVisualBasicCompilerFeatureInAssemblyWithCSharpReferenceStrictRule), + SupportedLanguage.CSharpAndVisualBasic => ("Microsoft.CodeAnalysis.CSharp", CompilerExtensionStrictApiAnalyzer.DoNotDeclareVisualBasicCompilerFeatureInAssemblyWithCSharpReferenceStrictRule), + _ => throw new NotImplementedException(), + }; + + await new VerifyVB.Test + { + ReferenceAssemblies = ReferenceAssemblies.NetStandard.NetStandard20.AddPackages(ImmutableArray.Create( + new PackageIdentity(mismatchedPackage, CompilerReferenceVersion))), + TestCode = DefineFeature(ImplementationLanguage.VisualBasic, feature, supportedLanguage), + ExpectedDiagnostics = + { + VerifyVB.Diagnostic(descriptor).WithLocation(0), + }, + }.RunAsync(); + } + + private static string DefineFeature(ImplementationLanguage languageName, CompilerFeature feature, SupportedLanguage supportedLanguage) + { + var languageApplication = (languageName, supportedLanguage) switch + { + (_, SupportedLanguage.CSharp) => "LanguageNames.CSharp", + (_, SupportedLanguage.VisualBasic) => "LanguageNames.VisualBasic", + (ImplementationLanguage.CSharp, SupportedLanguage.CSharpAndVisualBasic) => "LanguageNames.CSharp, LanguageNames.VisualBasic", + (ImplementationLanguage.VisualBasic, SupportedLanguage.CSharpAndVisualBasic) => "LanguageNames.VisualBasic, LanguageNames.CSharp", + _ => throw new NotImplementedException(), + }; + + return (languageName, feature) switch + { + (ImplementationLanguage.CSharp, CompilerFeature.DiagnosticAnalyzer) => + $$""" + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [{|#0:DiagnosticAnalyzer({{languageApplication}})|}] + public class MyAnalyzer : DiagnosticAnalyzer + { + public override ImmutableArray SupportedDiagnostics { get; } + public override void Initialize(AnalysisContext context) { } + } + """, + (ImplementationLanguage.CSharp, CompilerFeature.DiagnosticSuppressor) => + $$""" + using System.Collections.Immutable; + using Microsoft.CodeAnalysis; + using Microsoft.CodeAnalysis.Diagnostics; + + [{|#0:DiagnosticAnalyzer({{languageApplication}})|}] + public class MySuppressor : DiagnosticSuppressor + { + public override ImmutableArray SupportedSuppressions { get; } + public override void ReportSuppressions(SuppressionAnalysisContext context) { } + } + """, + (ImplementationLanguage.CSharp, CompilerFeature.ISourceGenerator) => + $$""" + using Microsoft.CodeAnalysis; + + [{|#0:Generator({{languageApplication}})|}] + public class MyGenerator : ISourceGenerator + { + public void Initialize(GeneratorInitializationContext context) { } + public void Execute(GeneratorExecutionContext context) { } + } + """, + (ImplementationLanguage.CSharp, CompilerFeature.IIncrementalGenerator) => + $$""" + using Microsoft.CodeAnalysis; + + [{|#0:Generator({{languageApplication}})|}] + public class MyGenerator : IIncrementalGenerator + { + public void Initialize(IncrementalGeneratorInitializationContext context) { } + } + """, + (ImplementationLanguage.VisualBasic, CompilerFeature.DiagnosticAnalyzer) => + $$""" + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + <{|#0:DiagnosticAnalyzer({{languageApplication}})|}> + Public Class MyAnalyzer + Inherits DiagnosticAnalyzer + + Public Overrides ReadOnly Property SupportedDiagnostics As ImmutableArray(Of DiagnosticDescriptor) + Public Overrides Sub Initialize(context As AnalysisContext) + End Sub + End Class + """, + (ImplementationLanguage.VisualBasic, CompilerFeature.DiagnosticSuppressor) => + $$""" + Imports System.Collections.Immutable + Imports Microsoft.CodeAnalysis + Imports Microsoft.CodeAnalysis.Diagnostics + + <{|#0:DiagnosticAnalyzer({{languageApplication}})|}> + Public Class MySuppressor + Inherits DiagnosticSuppressor + + Public Overrides ReadOnly Property SupportedSuppressions As ImmutableArray(Of SuppressionDescriptor) + Public Overrides Sub ReportSuppressions(context As SuppressionAnalysisContext) + End Sub + End Class + """, + (ImplementationLanguage.VisualBasic, CompilerFeature.ISourceGenerator) => + $$""" + Imports Microsoft.CodeAnalysis + + <{|#0:Generator({{languageApplication}})|}> + Public Class MyGenerator + Implements ISourceGenerator + + Public Sub Initialize(context As GeneratorInitializationContext) Implements ISourceGenerator.Initialize + End Sub + + Public Sub Execute(context As GeneratorExecutionContext) Implements ISourceGenerator.Execute + End Sub + End Class + """, + (ImplementationLanguage.VisualBasic, CompilerFeature.IIncrementalGenerator) => + $$""" + Imports Microsoft.CodeAnalysis + + <{|#0:Generator({{languageApplication}})|}> + Public Class MyGenerator + Implements IIncrementalGenerator + + Public Sub Initialize(context As IncrementalGeneratorInitializationContext) Implements IIncrementalGenerator.Initialize + End Sub + End Class + """, + _ => throw new NotImplementedException(), + }; + } + } +} diff --git a/src/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DiagnosticAnalyzerApiUsageAnalyzerTests.cs b/src/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DiagnosticAnalyzerApiUsageAnalyzerTests.cs index 18d403ffc3..992867cb46 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DiagnosticAnalyzerApiUsageAnalyzerTests.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/UnitTests/MetaAnalyzers/DiagnosticAnalyzerApiUsageAnalyzerTests.cs @@ -124,7 +124,7 @@ await VerifyCS.VerifyAnalyzerAsync(@" interface I { } -class MyAnalyzer : DiagnosticAnalyzer, I +class {|#0:MyAnalyzer|} : DiagnosticAnalyzer, I { public override ImmutableArray SupportedDiagnostics => throw new NotImplementedException(); @@ -133,7 +133,7 @@ public override void Initialize(AnalysisContext context) } }", // Test0.cs(11,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider'. - GetCSharpExpectedDiagnostic(11, 7, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); + GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System @@ -146,7 +146,7 @@ Imports Microsoft.CodeAnalysis.VisualBasic Interface I(Of T) End Interface -Class MyAnalyzer +Class {|#0:MyAnalyzer|} Inherits DiagnosticAnalyzer Implements I(Of Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider) @@ -161,7 +161,7 @@ End Sub End Class ", // Test0.vb(12,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider'. - GetBasicExpectedDiagnostic(12, 7, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); + GetBasicExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); } [Fact] @@ -176,7 +176,7 @@ await VerifyCS.VerifyAnalyzerAsync(@" using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; -class MyAnalyzer : DiagnosticAnalyzer +class {|#0:MyAnalyzer|} : DiagnosticAnalyzer { private readonly CodeFixProvider field; FixAllContext Method(FixAllProvider param) @@ -191,7 +191,7 @@ public override void Initialize(AnalysisContext context) } }", // Test0.cs(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllContext, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider'. - GetCSharpExpectedDiagnostic(10, 7, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllContext, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); + GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllContext, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System @@ -202,7 +202,7 @@ Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic -Class MyAnalyzer +Class {|#0:MyAnalyzer|} Inherits DiagnosticAnalyzer Dim field As CodeFixProvider @@ -222,7 +222,7 @@ End Class ", // Test0.vb(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllContext, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider'. - GetBasicExpectedDiagnostic(10, 7, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllContext, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); + GetBasicExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllContext, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); } [Fact] @@ -237,7 +237,7 @@ await VerifyCS.VerifyAnalyzerAsync(@" using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; -class MyAnalyzer : DiagnosticAnalyzer +class {|#0:MyAnalyzer|} : DiagnosticAnalyzer { void Method() { @@ -251,7 +251,7 @@ public override void Initialize(AnalysisContext context) } }", // Test0.cs(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider'. - GetCSharpExpectedDiagnostic(10, 7, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); + GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System @@ -262,7 +262,7 @@ Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic -Class MyAnalyzer +Class {|#0:MyAnalyzer|} Inherits DiagnosticAnalyzer Sub Method() @@ -281,7 +281,7 @@ End Class ", // Test0.vb(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider'. - GetBasicExpectedDiagnostic(10, 7, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); + GetBasicExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); } [Fact] @@ -297,7 +297,7 @@ await VerifyCS.VerifyAnalyzerAsync(@" using Microsoft.CodeAnalysis.Diagnostics; using static Microsoft.CodeAnalysis.CodeActions.WarningAnnotation; -class MyAnalyzer : DiagnosticAnalyzer +class {|#0:MyAnalyzer|} : DiagnosticAnalyzer { void Method() { @@ -311,7 +311,7 @@ public override void Initialize(AnalysisContext context) } }", // Test0.cs(11,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeActions.WarningAnnotation'. - GetCSharpExpectedDiagnostic(11, 7, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeActions.WarningAnnotation")); + GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeActions.WarningAnnotation")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System @@ -323,7 +323,7 @@ Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic Imports WarningAnnotation = Microsoft.CodeAnalysis.CodeActions.WarningAnnotation -Class MyAnalyzer +Class {|#0:MyAnalyzer|} Inherits DiagnosticAnalyzer Sub Method() @@ -341,7 +341,7 @@ End Sub End Class ", // Test0.vb(11,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeActions.WarningAnnotation'. - GetBasicExpectedDiagnostic(11, 7, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeActions.WarningAnnotation")); + GetBasicExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeActions.WarningAnnotation")); } [Fact] @@ -357,7 +357,7 @@ await VerifyCS.VerifyAnalyzerAsync(@" using Microsoft.CodeAnalysis.Diagnostics; using static Microsoft.CodeAnalysis.CodeFixes.WellKnownFixAllProviders; -class MyAnalyzer : DiagnosticAnalyzer +class {|#0:MyAnalyzer|} : DiagnosticAnalyzer { void Method() { @@ -371,7 +371,7 @@ public override void Initialize(AnalysisContext context) } }", // Test0.cs(11,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeFixes.FixAllProvider, Microsoft.CodeAnalysis.CodeFixes.WellKnownFixAllProviders'. - GetCSharpExpectedDiagnostic(11, 7, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.FixAllProvider, Microsoft.CodeAnalysis.CodeFixes.WellKnownFixAllProviders")); + GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.FixAllProvider, Microsoft.CodeAnalysis.CodeFixes.WellKnownFixAllProviders")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System @@ -383,7 +383,7 @@ Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic Imports WellKnownFixAllProviders = Microsoft.CodeAnalysis.CodeFixes.WellKnownFixAllProviders -Class MyAnalyzer +Class {|#0:MyAnalyzer|} Inherits DiagnosticAnalyzer Sub Method() @@ -401,7 +401,7 @@ End Sub End Class ", // Test0.vb(11,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeFixes.FixAllProvider, Microsoft.CodeAnalysis.CodeFixes.WellKnownFixAllProviders'. - GetBasicExpectedDiagnostic(11, 7, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.FixAllProvider, Microsoft.CodeAnalysis.CodeFixes.WellKnownFixAllProviders")); + GetBasicExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.FixAllProvider, Microsoft.CodeAnalysis.CodeFixes.WellKnownFixAllProviders")); } [Fact] @@ -416,7 +416,7 @@ await VerifyCS.VerifyAnalyzerAsync(@" using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; -class MyAnalyzer : DiagnosticAnalyzer +class {|#0:MyAnalyzer|} : DiagnosticAnalyzer { void Method(object o) { @@ -431,7 +431,7 @@ public override void Initialize(AnalysisContext context) } }", // Test0.cs(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider'. - GetCSharpExpectedDiagnostic(10, 7, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); + GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System @@ -442,7 +442,7 @@ Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic -Class MyAnalyzer +Class {|#0:MyAnalyzer|} Inherits DiagnosticAnalyzer Sub Method(o As Object) @@ -461,7 +461,7 @@ End Sub End Class ", // Test0.vb(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct accesses to type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider'. - GetBasicExpectedDiagnostic(10, 7, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); + GetBasicExpectedDiagnostic(0, "MyAnalyzer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); } [Fact] @@ -478,7 +478,7 @@ await VerifyCS.VerifyAnalyzerAsync(@" using Microsoft.CodeAnalysis.Diagnostics; using static Fixer; -class MyAnalyzer : DiagnosticAnalyzer +class {|#0:MyAnalyzer|} : DiagnosticAnalyzer { private string Value => FixerValue; @@ -503,7 +503,7 @@ public sealed override Task RegisterCodeFixesAsync(CodeFixContext context) } ", // Test0.cs(12,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'Fixer', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixContext, Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider'. - GetCSharpExpectedDiagnostic(12, 7, "MyAnalyzer", "Fixer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixContext, Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); + GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "Fixer", "Microsoft.CodeAnalysis.CodeFixes.CodeFixContext, Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); } [Fact] @@ -519,7 +519,7 @@ await VerifyCS.VerifyAnalyzerAsync(@" using Microsoft.CodeAnalysis.Diagnostics; using static FixerExtensions; -class MyAnalyzer : DiagnosticAnalyzer +class {|#0:MyAnalyzer|} : DiagnosticAnalyzer { void M() { @@ -542,7 +542,7 @@ public static void ExtensionMethod(this DiagnosticAnalyzer analyzer) } ", // Test0.cs(11,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'FixerExtensions', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider'. - GetCSharpExpectedDiagnostic(11, 7, "MyAnalyzer", "FixerExtensions", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); + GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "FixerExtensions", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System @@ -555,7 +555,7 @@ Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic Imports FixerExtensions -Class MyAnalyzer +Class {|#0:MyAnalyzer|} Inherits DiagnosticAnalyzer Private Sub M() @@ -580,7 +580,7 @@ End Sub End Module ", // Test0.vb(12,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'FixerExtensions', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider'. - GetBasicExpectedDiagnostic(12, 7, "MyAnalyzer", "FixerExtensions", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); + GetBasicExpectedDiagnostic(0, "MyAnalyzer", "FixerExtensions", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); } [Fact] @@ -595,7 +595,7 @@ await VerifyCS.VerifyAnalyzerAsync(@" using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; -class MyAnalyzer : DiagnosticAnalyzer +class {|#0:MyAnalyzer|} : DiagnosticAnalyzer { void Method(Class2 c) { @@ -618,7 +618,7 @@ public void M() } ", // Test0.cs(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'Class2', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider'. - GetCSharpExpectedDiagnostic(10, 7, "MyAnalyzer", "Class2", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); + GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "Class2", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System @@ -629,7 +629,7 @@ Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic -Class MyAnalyzer +Class {|#0:MyAnalyzer|} Inherits DiagnosticAnalyzer Sub Method(c As Class2) @@ -654,7 +654,7 @@ End Class ", // Test0.vb(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'Class2', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider'. - GetBasicExpectedDiagnostic(10, 7, "MyAnalyzer", "Class2", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); + GetBasicExpectedDiagnostic(0, "MyAnalyzer", "Class2", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); } [Fact] @@ -672,7 +672,7 @@ await VerifyCS.VerifyAnalyzerAsync(@" using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; -class MyAnalyzer : DiagnosticAnalyzer +class {|#0:MyAnalyzer|} : DiagnosticAnalyzer { void Method(Class2 c2, Class3 c3) { @@ -708,7 +708,7 @@ public void M() } ", // Test0.cs(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'Class2, Class3', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider'. - GetCSharpExpectedDiagnostic(10, 7, "MyAnalyzer", "Class2, Class3", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); + GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "Class2, Class3", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System @@ -719,7 +719,7 @@ Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic -Class MyAnalyzer +Class {|#0:MyAnalyzer|} Inherits DiagnosticAnalyzer Sub Method(c2 As Class2, c3 As Class3) @@ -752,7 +752,7 @@ End Sub End Class ", // Test0.vb(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'Class2, Class3', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider'. - GetBasicExpectedDiagnostic(10, 7, "MyAnalyzer", "Class2, Class3", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); + GetBasicExpectedDiagnostic(0, "MyAnalyzer", "Class2, Class3", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); } [Fact] @@ -767,7 +767,7 @@ await VerifyCS.VerifyAnalyzerAsync(@" using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; -class MyAnalyzer : DiagnosticAnalyzer +class {|#0:MyAnalyzer|} : DiagnosticAnalyzer { void Method(Class2 c2) { @@ -796,7 +796,7 @@ public void M() } ", // Test0.cs(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'Class3', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider'. - GetCSharpExpectedDiagnostic(10, 7, "MyAnalyzer", "Class3", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); + GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "Class3", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System @@ -807,7 +807,7 @@ Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic -Class MyAnalyzer +Class {|#0:MyAnalyzer|} Inherits DiagnosticAnalyzer Sub Method(c2 As Class2) @@ -835,7 +835,7 @@ End Sub End Class ", // Test0.vb(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'Class3', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider'. - GetBasicExpectedDiagnostic(10, 7, "MyAnalyzer", "Class3", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); + GetBasicExpectedDiagnostic(0, "MyAnalyzer", "Class3", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider")); } [Fact] @@ -850,7 +850,7 @@ await VerifyCS.VerifyAnalyzerAsync(@" using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.Diagnostics; -class MyAnalyzer : DiagnosticAnalyzer +class {|#0:MyAnalyzer|} : DiagnosticAnalyzer { void Method(Class2 c2, Class3 c3) { @@ -884,7 +884,7 @@ public void M(Class2 c2) } ", // Test0.cs(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'Class2, Class3', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider'. - GetCSharpExpectedDiagnostic(10, 7, "MyAnalyzer", "Class2, Class3", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); + GetCSharpExpectedDiagnostic(0, "MyAnalyzer", "Class2, Class3", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); await VerifyVB.VerifyAnalyzerAsync(@" Imports System @@ -895,7 +895,7 @@ Imports Microsoft.CodeAnalysis.CodeFixes Imports Microsoft.CodeAnalysis.Diagnostics Imports Microsoft.CodeAnalysis.VisualBasic -Class MyAnalyzer +Class {|#0:MyAnalyzer|} Inherits DiagnosticAnalyzer Sub Method(c2 As Class2, c3 As Class3) @@ -927,35 +927,27 @@ End Sub End Class ", // Test0.vb(10,7): warning RS1022: Change diagnostic analyzer type 'MyAnalyzer' to remove all direct and/or indirect accesses to type(s) 'Class2, Class3', which access type(s) 'Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider'. - GetBasicExpectedDiagnostic(10, 7, "MyAnalyzer", "Class2, Class3", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); + GetBasicExpectedDiagnostic(0, "MyAnalyzer", "Class2, Class3", "Microsoft.CodeAnalysis.CodeFixes.CodeFixProvider, Microsoft.CodeAnalysis.CodeFixes.FixAllProvider")); } - private static DiagnosticResult GetCSharpExpectedDiagnostic(int line, int column, string analyzerTypeName, string violatingTypes) => -#pragma warning disable RS0030 // Do not use banned APIs + private static DiagnosticResult GetCSharpExpectedDiagnostic(int location, string analyzerTypeName, string violatingTypes) => VerifyCS.Diagnostic(CSharpDiagnosticAnalyzerApiUsageAnalyzer.DoNotUseTypesFromAssemblyDirectRule) - .WithLocation(line, column) -#pragma warning restore RS0030 // Do not use banned APIs + .WithLocation(location) .WithArguments(analyzerTypeName, violatingTypes); - private static DiagnosticResult GetCSharpExpectedDiagnostic(int line, int column, string analyzerTypeName, string violatingIndirectTypes, string violatingTypes) => -#pragma warning disable RS0030 // Do not use banned APIs + private static DiagnosticResult GetCSharpExpectedDiagnostic(int location, string analyzerTypeName, string violatingIndirectTypes, string violatingTypes) => VerifyCS.Diagnostic(CSharpDiagnosticAnalyzerApiUsageAnalyzer.DoNotUseTypesFromAssemblyIndirectRule) - .WithLocation(line, column) -#pragma warning restore RS0030 // Do not use banned APIs + .WithLocation(location) .WithArguments(analyzerTypeName, violatingIndirectTypes, violatingTypes); - private static DiagnosticResult GetBasicExpectedDiagnostic(int line, int column, string analyzerTypeName, string violatingTypes) => -#pragma warning disable RS0030 // Do not use banned APIs + private static DiagnosticResult GetBasicExpectedDiagnostic(int location, string analyzerTypeName, string violatingTypes) => VerifyVB.Diagnostic(BasicDiagnosticAnalyzerApiUsageAnalyzer.DoNotUseTypesFromAssemblyDirectRule) - .WithLocation(line, column) -#pragma warning restore RS0030 // Do not use banned APIs + .WithLocation(location) .WithArguments(analyzerTypeName, violatingTypes); - private static DiagnosticResult GetBasicExpectedDiagnostic(int line, int column, string analyzerTypeName, string violatingIndirectTypes, string violatingTypes) => -#pragma warning disable RS0030 // Do not use banned APIs + private static DiagnosticResult GetBasicExpectedDiagnostic(int location, string analyzerTypeName, string violatingIndirectTypes, string violatingTypes) => VerifyVB.Diagnostic(BasicDiagnosticAnalyzerApiUsageAnalyzer.DoNotUseTypesFromAssemblyIndirectRule) - .WithLocation(line, column) -#pragma warning restore RS0030 // Do not use banned APIs + .WithLocation(location) .WithArguments(analyzerTypeName, violatingIndirectTypes, violatingTypes); } } diff --git a/src/Utilities/Compiler/WellKnownTypeNames.cs b/src/Utilities/Compiler/WellKnownTypeNames.cs index bd800d4ee3..4054c18d1d 100644 --- a/src/Utilities/Compiler/WellKnownTypeNames.cs +++ b/src/Utilities/Compiler/WellKnownTypeNames.cs @@ -55,6 +55,8 @@ internal static class WellKnownTypeNames public const string MicrosoftCodeAnalysisDiagnosticsSyntaxTreeAnalysisContext = "Microsoft.CodeAnalysis.Diagnostics.SyntaxTreeAnalysisContext"; public const string MicrosoftCodeAnalysisGeneratorAttribute = "Microsoft.CodeAnalysis.GeneratorAttribute"; public const string MicrosoftCodeAnalysisHostMefMefConstruction = "Microsoft.CodeAnalysis.Host.Mef.MefConstruction"; + public const string MicrosoftCodeAnalysisIIncrementalGenerator = "Microsoft.CodeAnalysis.IIncrementalGenerator"; + public const string MicrosoftCodeAnalysisISourceGenerator = "Microsoft.CodeAnalysis.ISourceGenerator"; public const string MicrosoftCodeAnalysisLocalizableResourceString = "Microsoft.CodeAnalysis.LocalizableResourceString"; public const string MicrosoftCodeAnalysisLocalizableString = "Microsoft.CodeAnalysis.LocalizableString"; public const string MicrosoftCodeAnalysisSharedCollectionsTemporaryArrayExtensions = "Microsoft.CodeAnalysis.Shared.Collections.TemporaryArrayExtensions"; From 99079c7df2b23ac25d28e594c7bf3a378bb7c31b Mon Sep 17 00:00:00 2001 From: Sam Harwell Date: Thu, 22 Jun 2023 08:22:12 -0500 Subject: [PATCH 2/5] Add documentation for RS1038 --- docs/rules/RS1022.md | 16 +++++++ docs/rules/RS1038.md | 43 +++++++++++++++++++ .../CompilerExtensionStrictApiAnalyzer.cs | 4 ++ .../DiagnosticAnalyzerAPIUsageAnalyzer.cs | 3 ++ .../Microsoft.CodeAnalysis.Analyzers.md | 4 +- .../Microsoft.CodeAnalysis.Analyzers.sarif | 3 ++ .../RulesMissingDocumentation.md | 4 +- 7 files changed, 73 insertions(+), 4 deletions(-) create mode 100644 docs/rules/RS1022.md create mode 100644 docs/rules/RS1038.md diff --git a/docs/rules/RS1022.md b/docs/rules/RS1022.md new file mode 100644 index 0000000000..b0cf307ee8 --- /dev/null +++ b/docs/rules/RS1022.md @@ -0,0 +1,16 @@ +## RS1022: Do not use types from Workspaces assembly in an analyzer + +Diagnostic analyzer types should not use types from Workspaces assemblies. Workspaces assemblies are only available when the analyzer executes in Visual Studio IDE live analysis, but are not available during command line build. Referencing types from Workspaces assemblies will lead to runtime exception during analyzer execution in command line build. + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisCorrectness| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| +--- + +> **Warning** +> +> The analysis performed by RS1022 is slow and relies on implementation details of the JIT compiler for correctness. +> Authors of compiler extensions are encouraged to use the stricter (and faster) analyzer RS1038 instead of this rule. diff --git a/docs/rules/RS1038.md b/docs/rules/RS1038.md new file mode 100644 index 0000000000..184606e4b4 --- /dev/null +++ b/docs/rules/RS1038.md @@ -0,0 +1,43 @@ +## RS1038: Compiler extensions should be implemented in assemblies with compiler-provided references + +Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. + +|Item|Value| +|-|-| +|Category|MicrosoftCodeAnalysisCorrectness| +|Enabled|True| +|Severity|Warning| +|CodeFix|False| +--- + +This rule helps ensure compiler extensions (e.g. analyzers and source generators) will load correctly in all compilation +scenarios. Depending on the manner in which the compiler is invoked, some assemblies may not be present during a build, +and attempting to reference them will result in exceptions that prevent the compiler extension from loading. RS1038 is +the most strict and best performing validation for this scenario. + +### Rules for compiler feature references + +* Compiler features supporting C# code should only reference the NuGet packages **Microsoft.CodeAnalysis.Common** and/or **Microsoft.CodeAnalysis.CSharp** +* Compiler features supporting Visual Basic code should only reference **Microsoft.CodeAnalysis.Common** and/or **Microsoft.CodeAnalysis.VisualBasic** +* Compiler features supporting both C# and Visual Basic should only reference **Microsoft.CodeAnalysis.Common** +* Compiler features should not be implemented in assemblies containing a reference to **Microsoft.CodeAnalysis.Workspaces.Common** + +> **Note** +> +> This analyzer only checks references to the core Roslyn assemblies. Compiler extensions with other dependencies may +> face restrictions and/or packaging requirements outside the scope of this analyzer. + +### Compiler extension points + +The following compiler extension points are examined by this analyzer: + +* `DiagnosticAnalyzer` +* `DiagnosticSuppressor` +* `ISourceGenerator` +* `IIncrementalGenerator` + +### Other extension points + +Some extension points provided by Roslyn are IDE extensions (e.g. code fixes and completion providers). These features +may ship in the same package as compiler features, but should be implemented in their own assembly since they require a +reference to non-compiler package **Microsoft.CodeAnalysis.Workspaces.Common**. diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/CompilerExtensionStrictApiAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/CompilerExtensionStrictApiAnalyzer.cs index 852de7eadd..9f407cee83 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/CompilerExtensionStrictApiAnalyzer.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/CompilerExtensionStrictApiAnalyzer.cs @@ -15,6 +15,7 @@ internal sealed class CompilerExtensionStrictApiAnalyzer : DiagnosticAnalyzer { private static readonly LocalizableString s_localizableTitle = CreateLocalizableResourceString(nameof(DoNotRegisterCompilerTypesWithBadAssemblyReferenceRuleTitle)); private static readonly LocalizableString s_localizableDescription = CreateLocalizableResourceString(nameof(DoNotRegisterCompilerTypesWithBadAssemblyReferenceRuleDescription)); + private const string HelpLinkUri = "https://github.com/dotnet/roslyn-analyzers/blob/main/docs/rules/RS1038.md"; public static readonly DiagnosticDescriptor DoNotDeclareCompilerFeatureInAssemblyWithWorkspacesReferenceStrictRule = new( DiagnosticIds.DoNotRegisterCompilerTypesWithBadAssemblyReferenceRuleId, @@ -24,6 +25,7 @@ internal sealed class CompilerExtensionStrictApiAnalyzer : DiagnosticAnalyzer DiagnosticSeverity.Warning, isEnabledByDefault: true, description: s_localizableDescription, + helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTagsExtensions.Telemetry); public static readonly DiagnosticDescriptor DoNotDeclareCSharpCompilerFeatureInAssemblyWithVisualBasicReferenceStrictRule = new( @@ -34,6 +36,7 @@ internal sealed class CompilerExtensionStrictApiAnalyzer : DiagnosticAnalyzer DiagnosticSeverity.Warning, isEnabledByDefault: true, description: s_localizableDescription, + helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTagsExtensions.Telemetry); public static readonly DiagnosticDescriptor DoNotDeclareVisualBasicCompilerFeatureInAssemblyWithCSharpReferenceStrictRule = new( @@ -44,6 +47,7 @@ internal sealed class CompilerExtensionStrictApiAnalyzer : DiagnosticAnalyzer DiagnosticSeverity.Warning, isEnabledByDefault: true, description: s_localizableDescription, + helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTagsExtensions.Telemetry); public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create( diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAPIUsageAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAPIUsageAnalyzer.cs index ffbc827f19..9a718eeb3c 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAPIUsageAnalyzer.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAPIUsageAnalyzer.cs @@ -26,6 +26,7 @@ public abstract class DiagnosticAnalyzerApiUsageAnalyzer : Diagnost private static readonly LocalizableString s_localizableTitle = CreateLocalizableResourceString(nameof(DoNotUseTypesFromAssemblyRuleTitle)); private static readonly LocalizableString s_localizableDescription = CreateLocalizableResourceString(nameof(DoNotUseTypesFromAssemblyRuleDescription), nameof(AnalysisContext), DiagnosticWellKnownNames.RegisterCompilationStartActionName); private const string CodeActionMetadataName = "Microsoft.CodeAnalysis.CodeActions.CodeAction"; + private const string HelpLinkUri = "https://github.com/dotnet/roslyn-analyzers/blob/main/docs/rules/RS1022.md"; private static readonly ImmutableArray s_WorkspaceAssemblyNames = ImmutableArray.Create( "Microsoft.CodeAnalysis.Workspaces", "Microsoft.CodeAnalysis.CSharp.Workspaces", @@ -39,6 +40,7 @@ public abstract class DiagnosticAnalyzerApiUsageAnalyzer : Diagnost DiagnosticSeverity.Warning, isEnabledByDefault: true, description: s_localizableDescription, + helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTagsExtensions.CompilationEndAndTelemetry); public static readonly DiagnosticDescriptor DoNotUseTypesFromAssemblyIndirectRule = new( @@ -49,6 +51,7 @@ public abstract class DiagnosticAnalyzerApiUsageAnalyzer : Diagnost DiagnosticSeverity.Warning, isEnabledByDefault: true, description: s_localizableDescription, + helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTagsExtensions.CompilationEndAndTelemetry); protected abstract bool IsNamedTypeDeclarationBlock(SyntaxNode syntax); diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.md b/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.md index e41738d3d4..2d45eaeb90 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.md +++ b/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.md @@ -268,7 +268,7 @@ Invalid entry in analyzer category and diagnostic ID range specification file. |CodeFix|False| --- -## RS1022: Do not use types from Workspaces assembly in an analyzer +## [RS1022](https://github.com/dotnet/roslyn-analyzers/blob/main/docs/rules/RS1022.md): Do not use types from Workspaces assembly in an analyzer Diagnostic analyzer types should not use types from Workspaces assemblies. Workspaces assemblies are only available when the analyzer executes in Visual Studio IDE live analysis, but are not available during command line build. Referencing types from Workspaces assemblies will lead to runtime exception during analyzer execution in command line build. @@ -460,7 +460,7 @@ A project containing analyzers or source generators should specify the property |CodeFix|False| --- -## RS1038: Compiler extensions should be implemented in assemblies with compiler-provided references +## [RS1038](https://github.com/dotnet/roslyn-analyzers/blob/main/docs/rules/RS1038.md): Compiler extensions should be implemented in assemblies with compiler-provided references Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably. diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.sarif b/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.sarif index 79f9790be3..cc58c42b4f 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.sarif +++ b/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.sarif @@ -480,6 +480,7 @@ "shortDescription": "Compiler extensions should be implemented in assemblies with compiler-provided references", "fullDescription": "Types which implement compiler extension points should not be declared in assemblies that contain references to assemblies which are not provided by all compilation scenarios. Doing so may cause the feature to behave unpredictably.", "defaultLevel": "warning", + "helpUri": "https://github.com/dotnet/roslyn-analyzers/blob/main/docs/rules/RS1038.md", "properties": { "category": "MicrosoftCodeAnalysisCorrectness", "isEnabledByDefault": true, @@ -802,6 +803,7 @@ "shortDescription": "Do not use types from Workspaces assembly in an analyzer", "fullDescription": "Diagnostic analyzer types should not use types from Workspaces assemblies. Workspaces assemblies are only available when the analyzer executes in Visual Studio IDE live analysis, but are not available during command line build. Referencing types from Workspaces assemblies will lead to runtime exception during analyzer execution in command line build.", "defaultLevel": "warning", + "helpUri": "https://github.com/dotnet/roslyn-analyzers/blob/main/docs/rules/RS1022.md", "properties": { "category": "MicrosoftCodeAnalysisCorrectness", "isEnabledByDefault": true, @@ -1000,6 +1002,7 @@ "shortDescription": "Do not use types from Workspaces assembly in an analyzer", "fullDescription": "Diagnostic analyzer types should not use types from Workspaces assemblies. Workspaces assemblies are only available when the analyzer executes in Visual Studio IDE live analysis, but are not available during command line build. Referencing types from Workspaces assemblies will lead to runtime exception during analyzer execution in command line build.", "defaultLevel": "warning", + "helpUri": "https://github.com/dotnet/roslyn-analyzers/blob/main/docs/rules/RS1022.md", "properties": { "category": "MicrosoftCodeAnalysisCorrectness", "isEnabledByDefault": true, diff --git a/src/Microsoft.CodeAnalysis.Analyzers/RulesMissingDocumentation.md b/src/Microsoft.CodeAnalysis.Analyzers/RulesMissingDocumentation.md index 54222676dc..9a86eec801 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/RulesMissingDocumentation.md +++ b/src/Microsoft.CodeAnalysis.Analyzers/RulesMissingDocumentation.md @@ -23,7 +23,7 @@ RS1018 | | DiagnosticId for analyzers must be in specified format | RS1019 | | DiagnosticId must be unique across analyzers | RS1020 | | Category for analyzers must be from the specified values | RS1021 | | Invalid entry in analyzer category and diagnostic ID range specification file | -RS1022 | | Do not use types from Workspaces assembly in an analyzer | +RS1022 | | Do not use types from Workspaces assembly in an analyzer | RS1024 | | Symbols should be compared for equality | RS1025 | | Configure generated code analysis | RS1026 | | Enable concurrent execution | @@ -38,4 +38,4 @@ RS1034 | | Prefer 'IsKind' for checking syntax kinds | RS1035 | | Do not use APIs banned for analyzers | RS1036 | | Specify analyzer banned API enforcement setting | RS1037 | | Add "CompilationEnd" custom tag to compilation end diagnostic descriptor | -RS1038 | | Compiler extensions should be implemented in assemblies with compiler-provided references | +RS1038 | | Compiler extensions should be implemented in assemblies with compiler-provided references | From 21a5c52a78c84ab6c9a3166b2503ed9a4ef2a049 Mon Sep 17 00:00:00 2001 From: Sam Harwell Date: Thu, 22 Jun 2023 08:36:41 -0500 Subject: [PATCH 3/5] Disable RS1022 by default --- docs/rules/RS1022.md | 2 +- .../Core/AnalyzerReleases.Unshipped.md | 6 ++++++ .../MetaAnalyzers/DiagnosticAnalyzerAPIUsageAnalyzer.cs | 4 ++-- .../Microsoft.CodeAnalysis.Analyzers.md | 2 +- .../Microsoft.CodeAnalysis.Analyzers.sarif | 4 ++-- 5 files changed, 12 insertions(+), 6 deletions(-) diff --git a/docs/rules/RS1022.md b/docs/rules/RS1022.md index b0cf307ee8..9f070e3413 100644 --- a/docs/rules/RS1022.md +++ b/docs/rules/RS1022.md @@ -5,7 +5,7 @@ Diagnostic analyzer types should not use types from Workspaces assemblies. Works |Item|Value| |-|-| |Category|MicrosoftCodeAnalysisCorrectness| -|Enabled|True| +|Enabled|False| |Severity|Warning| |CodeFix|False| --- diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/AnalyzerReleases.Unshipped.md b/src/Microsoft.CodeAnalysis.Analyzers/Core/AnalyzerReleases.Unshipped.md index 0b96acefcc..be385a9850 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/AnalyzerReleases.Unshipped.md +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/AnalyzerReleases.Unshipped.md @@ -5,3 +5,9 @@ Rule ID | Category | Severity | Notes --------|----------|----------|------- RS1038 | MicrosoftCodeAnalysisCorrectness | Warning | CompilerExtensionStrictApiAnalyzer + +### Changed Rules + +Rule ID | New Category | New Severity | Old Category | Old Severity | Notes +--------|--------------|--------------|--------------|--------------|------- +RS1022 | MicrosoftCodeAnalysisCorrectness | Disabled | MicrosoftCodeAnalysisCorrectness | Warning | DiagnosticAnalyzerApiUsageAnalyzer diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAPIUsageAnalyzer.cs b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAPIUsageAnalyzer.cs index 9a718eeb3c..776d4ff94f 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAPIUsageAnalyzer.cs +++ b/src/Microsoft.CodeAnalysis.Analyzers/Core/MetaAnalyzers/DiagnosticAnalyzerAPIUsageAnalyzer.cs @@ -38,7 +38,7 @@ public abstract class DiagnosticAnalyzerApiUsageAnalyzer : Diagnost CreateLocalizableResourceString(nameof(DoNotUseTypesFromAssemblyRuleDirectMessage)), DiagnosticCategory.MicrosoftCodeAnalysisCorrectness, DiagnosticSeverity.Warning, - isEnabledByDefault: true, + isEnabledByDefault: false, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTagsExtensions.CompilationEndAndTelemetry); @@ -49,7 +49,7 @@ public abstract class DiagnosticAnalyzerApiUsageAnalyzer : Diagnost CreateLocalizableResourceString(nameof(DoNotUseTypesFromAssemblyRuleIndirectMessage)), DiagnosticCategory.MicrosoftCodeAnalysisCorrectness, DiagnosticSeverity.Warning, - isEnabledByDefault: true, + isEnabledByDefault: false, description: s_localizableDescription, helpLinkUri: HelpLinkUri, customTags: WellKnownDiagnosticTagsExtensions.CompilationEndAndTelemetry); diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.md b/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.md index 2d45eaeb90..b43d408970 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.md +++ b/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.md @@ -275,7 +275,7 @@ Diagnostic analyzer types should not use types from Workspaces assemblies. Works |Item|Value| |-|-| |Category|MicrosoftCodeAnalysisCorrectness| -|Enabled|True| +|Enabled|False| |Severity|Warning| |CodeFix|False| --- diff --git a/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.sarif b/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.sarif index cc58c42b4f..4d176eef1d 100644 --- a/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.sarif +++ b/src/Microsoft.CodeAnalysis.Analyzers/Microsoft.CodeAnalysis.Analyzers.sarif @@ -806,7 +806,7 @@ "helpUri": "https://github.com/dotnet/roslyn-analyzers/blob/main/docs/rules/RS1022.md", "properties": { "category": "MicrosoftCodeAnalysisCorrectness", - "isEnabledByDefault": true, + "isEnabledByDefault": false, "typeName": "CSharpDiagnosticAnalyzerApiUsageAnalyzer", "languages": [ "C#" @@ -1005,7 +1005,7 @@ "helpUri": "https://github.com/dotnet/roslyn-analyzers/blob/main/docs/rules/RS1022.md", "properties": { "category": "MicrosoftCodeAnalysisCorrectness", - "isEnabledByDefault": true, + "isEnabledByDefault": false, "typeName": "BasicDiagnosticAnalyzerApiUsageAnalyzer", "languages": [ "Visual Basic" From f9e434859affd7e0358cd104aca2892a154722da Mon Sep 17 00:00:00 2001 From: Sam Harwell Date: Thu, 22 Jun 2023 11:40:14 -0500 Subject: [PATCH 4/5] Update Microsoft.CodeAnalysis.Analyzers to use Roslyn 3.7.0 --- Directory.Build.props | 3 ++ eng/Versions.props | 2 +- .../Fixers/CSharpPreferIsKindFix.cs | 3 ++ .../FixerWithFixAllAnalyzer.Fixer.cs | 5 ++- .../InternalImplementationOnlyAnalyzer.cs | 2 +- .../CompareSymbolsCorrectlyAnalyzer.cs | 2 +- .../CompilerExtensionStrictApiAnalyzer.cs | 9 +++- .../DiagnosticAnalyzerAPIUsageAnalyzer.cs | 8 ++-- .../DiagnosticAnalyzerAttributeAnalyzer.cs | 2 +- ...deWithinAnalyzerTypeCompilationAnalyzer.cs | 2 +- .../DiagnosticAnalyzerFieldsAnalyzer.cs | 2 +- .../DiagnosticDescriptorCreationAnalyzer.cs | 21 +++++++-- ...onAnalyzer_IdRangeAndCategoryValidation.cs | 2 +- ...criptorCreationAnalyzer_ReleaseTracking.cs | 4 +- ...rCreationAnalyzer_ResourceStringsFormat.cs | 3 +- ...alyzerReleaseTrackingFix.FixAllProvider.cs | 4 +- .../Fixers/AnalyzerReleaseTrackingFix.cs | 4 +- .../ApplyDiagnosticAnalyzerAttributeFix.cs | 2 +- .../Fixers/CompareSymbolsCorrectlyFix.cs | 8 ++-- .../ConfigureGeneratedCodeAnalysisFix.cs | 4 +- ...umentsCorrectlyFix.CustomFixAllProvider.cs | 2 +- ...agnosticDescriptorArgumentsCorrectlyFix.cs | 4 +- .../Fixers/EnableConcurrentExecutionFix.cs | 2 +- .../MetaAnalyzers/RegisterActionAnalyzer.cs | 4 +- .../MetaAnalyzers/ReportDiagnosticAnalyzer.cs | 8 ++-- .../SymbolIsBannedInAnalyzersAnalyzer.cs | 5 ++- src/PublicApiAnalyzers/Directory.Build.props | 1 + .../Compiler/Analyzer.Utilities.projitems | 3 +- .../Extensions/AdditionalTextExtensions.cs | 18 ++++++++ ...ataAnalysis.TaintedDataOperationVisitor.cs | 2 +- .../DataFlow/AnalysisEntityFactory.cs | 2 +- .../Workspaces/DocumentExtensions.cs | 43 +++++++++++++++++++ .../Workspaces/Workspaces.Utilities.projitems | 1 + 33 files changed, 141 insertions(+), 46 deletions(-) create mode 100644 src/Utilities/Compiler/Extensions/AdditionalTextExtensions.cs create mode 100644 src/Utilities/Workspaces/DocumentExtensions.cs diff --git a/Directory.Build.props b/Directory.Build.props index a8feff3916..84c7774033 100644 --- a/Directory.Build.props +++ b/Directory.Build.props @@ -49,6 +49,9 @@ $(NoWarn);CS1574;CS8602 + + $(NoWarn);CS8603 diff --git a/eng/Versions.props b/eng/Versions.props index 728c5f7cd4..d87602ff15 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -69,7 +69,7 @@ 4.0.1 3.3.1 3.3.1 - 3.3.1 + 3.7.0 3.3.1