diff --git a/CommunityToolkit.Mvvm.SourceGenerators/ComponentModel/ObservablePropertyGenerator.cs b/CommunityToolkit.Mvvm.SourceGenerators/ComponentModel/ObservablePropertyGenerator.cs index 413664ef6..52ee92e71 100644 --- a/CommunityToolkit.Mvvm.SourceGenerators/ComponentModel/ObservablePropertyGenerator.cs +++ b/CommunityToolkit.Mvvm.SourceGenerators/ComponentModel/ObservablePropertyGenerator.cs @@ -12,7 +12,6 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using static CommunityToolkit.Mvvm.SourceGenerators.Diagnostics.DiagnosticDescriptors; namespace CommunityToolkit.Mvvm.SourceGenerators; @@ -30,8 +29,17 @@ public void Initialize(IncrementalGeneratorInitializationContext context) context.SyntaxProvider .CreateSyntaxProvider( static (node, _) => node is FieldDeclarationSyntax { Parent: ClassDeclarationSyntax or RecordDeclarationSyntax, AttributeLists.Count: > 0 }, - static (context, _) => ((FieldDeclarationSyntax)context.Node).Declaration.Variables.Select(v => (IFieldSymbol)context.SemanticModel.GetDeclaredSymbol(v)!)) - .SelectMany(static (item, _) => item); + static (context, _) => + { + if (!context.SemanticModel.Compilation.HasLanguageVersionAtLeastEqualTo(LanguageVersion.CSharp8)) + { + return default; + } + + return ((FieldDeclarationSyntax)context.Node).Declaration.Variables.Select(v => (IFieldSymbol)context.SemanticModel.GetDeclaredSymbol(v)!); + }) + .Where(static items => items is not null) + .SelectMany(static (item, _) => item!)!; // Filter the fields using [ObservableProperty] IncrementalValuesProvider fieldSymbolsWithAttribute = @@ -52,9 +60,6 @@ public void Initialize(IncrementalGeneratorInitializationContext context) // Output the diagnostics context.ReportDiagnostics(fieldSymbolsWithOrphanedDependentAttributeWithErrors); - // Filter by language version - context.FilterWithLanguageVersion(ref fieldSymbolsWithAttribute, LanguageVersion.CSharp8, UnsupportedCSharpLanguageVersionError); - // Gather info for all annotated fields IncrementalValuesProvider<(HierarchyInfo Hierarchy, Result Info)> propertyInfoWithErrors = fieldSymbolsWithAttribute diff --git a/CommunityToolkit.Mvvm.SourceGenerators/ComponentModel/ObservableValidatorValidateAllPropertiesGenerator.cs b/CommunityToolkit.Mvvm.SourceGenerators/ComponentModel/ObservableValidatorValidateAllPropertiesGenerator.cs index 42029748b..320db7f0f 100644 --- a/CommunityToolkit.Mvvm.SourceGenerators/ComponentModel/ObservableValidatorValidateAllPropertiesGenerator.cs +++ b/CommunityToolkit.Mvvm.SourceGenerators/ComponentModel/ObservableValidatorValidateAllPropertiesGenerator.cs @@ -28,7 +28,15 @@ public void Initialize(IncrementalGeneratorInitializationContext context) context.SyntaxProvider .CreateSyntaxProvider( static (node, _) => node is ClassDeclarationSyntax, - static (context, _) => (context.Node, Symbol: (INamedTypeSymbol)context.SemanticModel.GetDeclaredSymbol(context.Node)!)) + static (context, _) => + { + if (!context.SemanticModel.Compilation.HasLanguageVersionAtLeastEqualTo(LanguageVersion.CSharp8)) + { + return default; + } + + return (context.Node, Symbol: (INamedTypeSymbol)context.SemanticModel.GetDeclaredSymbol(context.Node)!); + }) .Where(static item => item.Symbol is { IsAbstract: false, IsGenericType: false } && item.Node.IsFirstSyntaxDeclarationForSymbol(item.Symbol)) .Select(static (item, _) => item.Symbol); diff --git a/CommunityToolkit.Mvvm.SourceGenerators/ComponentModel/TransitiveMembersGenerator.cs b/CommunityToolkit.Mvvm.SourceGenerators/ComponentModel/TransitiveMembersGenerator.cs index 82bdfbd87..8b0a01a04 100644 --- a/CommunityToolkit.Mvvm.SourceGenerators/ComponentModel/TransitiveMembersGenerator.cs +++ b/CommunityToolkit.Mvvm.SourceGenerators/ComponentModel/TransitiveMembersGenerator.cs @@ -75,7 +75,16 @@ public void Initialize(IncrementalGeneratorInitializationContext context) context.SyntaxProvider .CreateSyntaxProvider( static (node, _) => node is ClassDeclarationSyntax { AttributeLists.Count: > 0 }, - static (context, _) => (INamedTypeSymbol)context.SemanticModel.GetDeclaredSymbol(context.Node)!); + static (context, _) => + { + if (!context.SemanticModel.Compilation.HasLanguageVersionAtLeastEqualTo(LanguageVersion.CSharp8)) + { + return default; + } + + return (INamedTypeSymbol)context.SemanticModel.GetDeclaredSymbol(context.Node)!; + }) + .Where(static item => item is not null)!; // Filter the types with the target attribute IncrementalValuesProvider<(INamedTypeSymbol Symbol, AttributeData AttributeData)> typeSymbolsWithAttributeData = @@ -88,9 +97,6 @@ public void Initialize(IncrementalGeneratorInitializationContext context) // Transform the input data IncrementalValuesProvider<(INamedTypeSymbol Symbol, TInfo Info)> typeSymbolsWithInfo = GetInfo(context, typeSymbolsWithAttributeData); - // Filter by language version - context.FilterWithLanguageVersion(ref typeSymbolsWithInfo, LanguageVersion.CSharp8, UnsupportedCSharpLanguageVersionError); - // Gather all generation info, and any diagnostics IncrementalValuesProvider> generationInfoWithErrors = typeSymbolsWithInfo.Select((item, _) => diff --git a/CommunityToolkit.Mvvm.SourceGenerators/Diagnostics/Analyzers/UnsupportedCSharpLanguageVersionAnalyzer.cs b/CommunityToolkit.Mvvm.SourceGenerators/Diagnostics/Analyzers/UnsupportedCSharpLanguageVersionAnalyzer.cs new file mode 100644 index 000000000..b294d0bf6 --- /dev/null +++ b/CommunityToolkit.Mvvm.SourceGenerators/Diagnostics/Analyzers/UnsupportedCSharpLanguageVersionAnalyzer.cs @@ -0,0 +1,93 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Collections.Generic; +using System.Collections.Immutable; +using System.Linq; +using CommunityToolkit.Mvvm.SourceGenerators.Extensions; +using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Diagnostics; +using static CommunityToolkit.Mvvm.SourceGenerators.Diagnostics.DiagnosticDescriptors; + +namespace CommunityToolkit.Mvvm.SourceGenerators; + +/// +/// A diagnostic analyzer that generates an error whenever a source-generator attribute is used with not high enough C# version enabled. +/// +[DiagnosticAnalyzer(LanguageNames.CSharp)] +public sealed class UnsupportedCSharpLanguageVersionAnalyzer : DiagnosticAnalyzer +{ + /// + /// The mapping of target attributes that will trigger the analyzer. + /// + private static readonly ImmutableDictionary GeneratorAttributeNamesToFullyQualifiedNamesMap = ImmutableDictionary.CreateRange(new[] + { + new KeyValuePair("INotifyPropertyChangedAttribute", "CommunityToolkit.Mvvm.ComponentModel.INotifyPropertyChangedAttribute"), + new KeyValuePair("NotifyCanExecuteChangedForAttribute", "CommunityToolkit.Mvvm.ComponentModel.NotifyCanExecuteChangedForAttribute"), + new KeyValuePair("NotifyDataErrorInfoAttribute", "CommunityToolkit.Mvvm.ComponentModel.NotifyDataErrorInfoAttribute"), + new KeyValuePair("NotifyPropertyChangedForAttribute", "CommunityToolkit.Mvvm.ComponentModel.NotifyPropertyChangedForAttribute"), + new KeyValuePair("NotifyPropertyChangedRecipientsAttribute", "CommunityToolkit.Mvvm.ComponentModel.NotifyPropertyChangedRecipientsAttribute"), + new KeyValuePair("ObservableObjectAttribute", "CommunityToolkit.Mvvm.ComponentModel.ObservableObjectAttribute"), + new KeyValuePair("ObservablePropertyAttribute", "CommunityToolkit.Mvvm.ComponentModel.ObservablePropertyAttribute"), + new KeyValuePair("ObservableRecipientAttribute", "CommunityToolkit.Mvvm.ComponentModel.ObservableRecipientAttribute"), + new KeyValuePair("RelayCommandAttribute", "CommunityToolkit.Mvvm.Input.RelayCommandAttribute"), + }); + + /// + public override ImmutableArray SupportedDiagnostics { get; } = ImmutableArray.Create(UnsupportedCSharpLanguageVersionError); + + /// + public override void Initialize(AnalysisContext context) + { + context.ConfigureGeneratedCodeAnalysis(GeneratedCodeAnalysisFlags.Analyze | GeneratedCodeAnalysisFlags.ReportDiagnostics); + context.EnableConcurrentExecution(); + + // Defer the callback registration to when the compilation starts, so we can execute more + // preliminary checks and skip registering any kind of symbol analysis at all if not needed. + context.RegisterCompilationStartAction(static context => + { + // Check that the language version is not high enough, otherwise no diagnostic should ever be produced + if (context.Compilation.HasLanguageVersionAtLeastEqualTo(LanguageVersion.CSharp8)) + { + return; + } + + context.RegisterSymbolAction(static context => + { + // The possible attribute targets are only fields, classes and methods + if (context.Symbol is not (IFieldSymbol or INamedTypeSymbol { TypeKind: TypeKind.Class, IsImplicitlyDeclared: false } or IMethodSymbol)) + { + return; + } + + ImmutableArray attributes = context.Symbol.GetAttributes(); + + // If the symbol has no attributes, there's nothing left to do + if (attributes.IsEmpty) + { + return; + } + + foreach (AttributeData attribute in attributes) + { + // Go over each attribute on the target symbol, and check if the attribute type name is a candidate. + // If it is, double check by actually resolving the symbol from the compilation and comparing against it. + // This minimizes the calls to CompilationGetTypeByMetadataName(string) to only cases where it's almost + // guaranteed we'll actually get a match. If we do have one, then we can emit the diagnostic for the symbol. + if (attribute.AttributeClass is { Name: string attributeName } attributeClass && + GeneratorAttributeNamesToFullyQualifiedNamesMap.TryGetValue(attributeName, out string? fullyQualifiedAttributeName) && + context.Compilation.GetTypeByMetadataName(fullyQualifiedAttributeName) is INamedTypeSymbol attributeSymbol && + SymbolEqualityComparer.Default.Equals(attributeClass, attributeSymbol)) + { + context.ReportDiagnostic(Diagnostic.Create(UnsupportedCSharpLanguageVersionError, context.Symbol.Locations.FirstOrDefault())); + + // If we created a diagnostic for this symbol, we can stop. Even if there's multiple attributes, no need for repeated errors + return; + } + } + }, SymbolKind.Field, SymbolKind.NamedType, SymbolKind.Method); + }); + } +} diff --git a/CommunityToolkit.Mvvm.SourceGenerators/Extensions/CompilationExtensions.cs b/CommunityToolkit.Mvvm.SourceGenerators/Extensions/CompilationExtensions.cs index de3cf500f..878b62188 100644 --- a/CommunityToolkit.Mvvm.SourceGenerators/Extensions/CompilationExtensions.cs +++ b/CommunityToolkit.Mvvm.SourceGenerators/Extensions/CompilationExtensions.cs @@ -3,6 +3,7 @@ // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis; +using Microsoft.CodeAnalysis.CSharp; namespace CommunityToolkit.Mvvm.SourceGenerators.Extensions; @@ -11,6 +12,17 @@ namespace CommunityToolkit.Mvvm.SourceGenerators.Extensions; /// internal static class CompilationExtensions { + /// + /// Checks whether a given compilation (assumed to be for C#) is using at least a given language version. + /// + /// The to consider for analysis. + /// The minimum language version to check. + /// Whether is using at least the specified language version. + public static bool HasLanguageVersionAtLeastEqualTo(this Compilation compilation, LanguageVersion languageVersion) + { + return ((CSharpCompilation)compilation).LanguageVersion >= languageVersion; + } + /// /// /// Checks whether or not a type with a specified metadata name is accessible from a given instance. diff --git a/CommunityToolkit.Mvvm.SourceGenerators/Extensions/IncrementalGeneratorInitializationContextExtensions.cs b/CommunityToolkit.Mvvm.SourceGenerators/Extensions/IncrementalGeneratorInitializationContextExtensions.cs index 994518143..d009810eb 100644 --- a/CommunityToolkit.Mvvm.SourceGenerators/Extensions/IncrementalGeneratorInitializationContextExtensions.cs +++ b/CommunityToolkit.Mvvm.SourceGenerators/Extensions/IncrementalGeneratorInitializationContextExtensions.cs @@ -5,7 +5,6 @@ using System; using System.Collections.Immutable; using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; namespace CommunityToolkit.Mvvm.SourceGenerators.Extensions; @@ -14,54 +13,6 @@ namespace CommunityToolkit.Mvvm.SourceGenerators.Extensions; /// internal static class IncrementalGeneratorInitializationContextExtensions { - /// - /// Implements a gate for a language version over items in an input source. - /// - /// The type of items in the input source. - /// The input value being used. - /// The source instance. - /// The minimum language version to gate for. - /// The to emit if the gate detects invalid usage. - /// - /// Items in will be filtered out if the gate fails. If it passes, items will remain untouched. - /// - public static void FilterWithLanguageVersion( - this IncrementalGeneratorInitializationContext context, - ref IncrementalValuesProvider source, - LanguageVersion languageVersion, - DiagnosticDescriptor diagnosticDescriptor) - { - // Check whether the target language version is supported - IncrementalValueProvider isGeneratorSupported = - context.ParseOptionsProvider - .Select((item, _) => item is CSharpParseOptions options && options.LanguageVersion >= languageVersion); - - // Combine each data item with the supported flag - IncrementalValuesProvider<(T Data, bool IsGeneratorSupported)> dataWithSupportedInfo = - source - .Combine(isGeneratorSupported); - - // Get a marker node to show whether an invalid attribute is used - IncrementalValueProvider isUnsupportedAttributeUsed = - dataWithSupportedInfo - .Select(static (item, _) => item.IsGeneratorSupported) - .Where(static item => !item) - .Collect() - .Select(static (item, _) => item.Length > 0); - - // Report them to the output - context.RegisterConditionalSourceOutput(isUnsupportedAttributeUsed, context => - { - context.ReportDiagnostic(Diagnostic.Create(diagnosticDescriptor, null)); - }); - - // Only let data through if the minimum language version is supported - source = - dataWithSupportedInfo - .Where(static item => item.IsGeneratorSupported) - .Select(static (item, _) => item.Data); - } - /// /// Conditionally invokes /// if the value produced by the input is . diff --git a/CommunityToolkit.Mvvm.SourceGenerators/Input/RelayCommandGenerator.cs b/CommunityToolkit.Mvvm.SourceGenerators/Input/RelayCommandGenerator.cs index 766a333b9..06e2c7bc9 100644 --- a/CommunityToolkit.Mvvm.SourceGenerators/Input/RelayCommandGenerator.cs +++ b/CommunityToolkit.Mvvm.SourceGenerators/Input/RelayCommandGenerator.cs @@ -11,7 +11,6 @@ using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; -using static CommunityToolkit.Mvvm.SourceGenerators.Diagnostics.DiagnosticDescriptors; namespace CommunityToolkit.Mvvm.SourceGenerators; @@ -29,7 +28,16 @@ public void Initialize(IncrementalGeneratorInitializationContext context) context.SyntaxProvider .CreateSyntaxProvider( static (node, _) => node is MethodDeclarationSyntax { Parent: ClassDeclarationSyntax, AttributeLists.Count: > 0 }, - static (context, _) => (IMethodSymbol)context.SemanticModel.GetDeclaredSymbol(context.Node)!); + static (context, _) => + { + if (!context.SemanticModel.Compilation.HasLanguageVersionAtLeastEqualTo(LanguageVersion.CSharp8)) + { + return default; + } + + return (IMethodSymbol)context.SemanticModel.GetDeclaredSymbol(context.Node)!; + }) + .Where(static item => item is not null)!; // Filter the methods using [RelayCommand] IncrementalValuesProvider<(IMethodSymbol Symbol, AttributeData Attribute)> methodSymbolsWithAttributeData = @@ -39,9 +47,6 @@ public void Initialize(IncrementalGeneratorInitializationContext context) Attribute: item.GetAttributes().FirstOrDefault(a => a.AttributeClass?.HasFullyQualifiedName("global::CommunityToolkit.Mvvm.Input.RelayCommandAttribute") == true))) .Where(static item => item.Attribute is not null)!; - // Filter by language version - context.FilterWithLanguageVersion(ref methodSymbolsWithAttributeData, LanguageVersion.CSharp8, UnsupportedCSharpLanguageVersionError); - // Gather info for all annotated command methods IncrementalValuesProvider<(HierarchyInfo Hierarchy, Result Info)> commandInfoWithErrors = methodSymbolsWithAttributeData diff --git a/CommunityToolkit.Mvvm.SourceGenerators/Messaging/IMessengerRegisterAllGenerator.cs b/CommunityToolkit.Mvvm.SourceGenerators/Messaging/IMessengerRegisterAllGenerator.cs index dcb5f6633..66508983e 100644 --- a/CommunityToolkit.Mvvm.SourceGenerators/Messaging/IMessengerRegisterAllGenerator.cs +++ b/CommunityToolkit.Mvvm.SourceGenerators/Messaging/IMessengerRegisterAllGenerator.cs @@ -31,7 +31,15 @@ public void Initialize(IncrementalGeneratorInitializationContext context) context.SyntaxProvider .CreateSyntaxProvider( static (node, _) => node is ClassDeclarationSyntax, - static (context, _) => (context.Node, Symbol: (INamedTypeSymbol)context.SemanticModel.GetDeclaredSymbol(context.Node)!)) + static (context, _) => + { + if (!context.SemanticModel.Compilation.HasLanguageVersionAtLeastEqualTo(LanguageVersion.CSharp8)) + { + return default; + } + + return (context.Node, Symbol: (INamedTypeSymbol)context.SemanticModel.GetDeclaredSymbol(context.Node)!); + }) .Where(static item => item.Symbol is { IsAbstract: false, IsGenericType: false } && item.Node.IsFirstSyntaxDeclarationForSymbol(item.Symbol)) .Select(static (item, _) => item.Symbol); diff --git a/azure-pipelines.yml b/azure-pipelines.yml index 3259edb40..5210cebba 100644 --- a/azure-pipelines.yml +++ b/azure-pipelines.yml @@ -47,12 +47,12 @@ jobs: displayName: Run .NET 6 unit tests # Run the .NET 6 MVVM Toolkit tests targeting Roslyn 4.0.1 - - script: dotnet test tests\CommunityToolkit.Mvvm.UnitTests\CommunityToolkit.Mvvm.UnitTests.csproj -c Release -f net6.0 -l "trx;LogFileName=VSTestResults_net6.0_mvvmtoolkit_roslyn401.trx" + - script: dotnet test tests\CommunityToolkit.Mvvm.UnitTests\CommunityToolkit.Mvvm.UnitTests.csproj -c Release -f net6.0 -p:MvvmToolkitSourceGeneratorRoslynVersion=4.0.1 -l "trx;LogFileName=VSTestResults_net6.0_mvvmtoolkit_roslyn401.trx" displayName: Run CommunityToolkit.Mvvm.UnitTests unit tests with Roslyn 4.0.1 # Run the .NET 6 MVVM Toolkit source generator tests targeting Roslyn 4.0.1 - - script: dotnet test tests\CommunityToolkit.Mvvm.SourceGenerators.UnitTests\CommunityToolkit.Mvvm.SourceGenerators.UnitTests.csproj -c Release -f net6.0 -l "trx;LogFileName=VSTestResults_net6.0_mvvmtoolkit_generators_roslyn401.trx" - displayName: Run CommunityToolkit.Mvvm.UnitTests unit tests with Roslyn 4.0.1 + - script: dotnet test tests\CommunityToolkit.Mvvm.SourceGenerators.UnitTests\CommunityToolkit.Mvvm.SourceGenerators.UnitTests.csproj -c Release -f net6.0 -p:MvvmToolkitSourceGeneratorRoslynVersion=4.0.1 -l "trx;LogFileName=VSTestResults_net6.0_mvvmtoolkit_generators_roslyn401.trx" + displayName: Run CommunityToolkit.Mvvm.SourceGenerators.UnitTests unit tests with Roslyn 4.0.1 # Run .NET Core 3.1 tests - script: dotnet test -c Release -f netcoreapp3.1 -l "trx;LogFileName=VSTestResults_netcoreapp3.1.trx" diff --git a/tests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests.csproj b/tests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests.csproj index eba05a8ab..d30d2e3c9 100644 --- a/tests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests.csproj +++ b/tests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests.csproj @@ -5,6 +5,7 @@ + diff --git a/tests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests/Helpers/CSharpAnalyzerWithLanguageVersionTest{TAnalyzer}.cs b/tests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests/Helpers/CSharpAnalyzerWithLanguageVersionTest{TAnalyzer}.cs new file mode 100644 index 000000000..211ab92b7 --- /dev/null +++ b/tests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests/Helpers/CSharpAnalyzerWithLanguageVersionTest{TAnalyzer}.cs @@ -0,0 +1,67 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System.Threading; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.ComponentModel; +using Microsoft.CodeAnalysis.CSharp.Testing; +using Microsoft.CodeAnalysis.CSharp; +using Microsoft.CodeAnalysis.Diagnostics; +using Microsoft.CodeAnalysis.Testing.Verifiers; +using Microsoft.CodeAnalysis.Testing; +using Microsoft.CodeAnalysis; +#if NET472 +using System.ComponentModel.DataAnnotations; +#endif + +namespace CommunityToolkit.Mvvm.SourceGenerators.UnitTests.Helpers; + +/// +/// A custom that uses a specific C# language version to parse code. +/// +/// The type of the analyzer to test. +internal sealed class CSharpAnalyzerWithLanguageVersionTest : CSharpAnalyzerTest + where TAnalyzer : DiagnosticAnalyzer, new() +{ + /// + /// The C# language version to use to parse code. + /// + private readonly LanguageVersion languageVersion; + + /// + /// Creates a new instance with the specified paramaters. + /// + /// The C# language version to use to parse code. + private CSharpAnalyzerWithLanguageVersionTest(LanguageVersion languageVersion) + { + this.languageVersion = languageVersion; + } + + /// + protected override ParseOptions CreateParseOptions() + { + return new CSharpParseOptions(this.languageVersion, DocumentationMode.Diagnose); + } + + /// + /// The language version to use to run the test. + public static Task VerifyAnalyzerAsync(string source, LanguageVersion languageVersion, params DiagnosticResult[] expected) + { + CSharpAnalyzerWithLanguageVersionTest test = new(languageVersion) { TestCode = source }; + +#if NET6_0 + test.TestState.ReferenceAssemblies = ReferenceAssemblies.Net.Net60; +#elif NETCOREAPP3_1 + test.TestState.ReferenceAssemblies = ReferenceAssemblies.NetCore.NetCoreApp31; +#else + test.TestState.ReferenceAssemblies = ReferenceAssemblies.NetFramework.Net472.Default; + test.TestState.AdditionalReferences.Add(MetadataReference.CreateFromFile(typeof(RequiredAttribute).Assembly.Location)); +#endif + test.TestState.AdditionalReferences.Add(MetadataReference.CreateFromFile(typeof(ObservableObject).Assembly.Location)); + + test.ExpectedDiagnostics.AddRange(expected); + + return test.RunAsync(CancellationToken.None); + } +} diff --git a/tests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests/Test_SourceGeneratorsDiagnostics.cs b/tests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests/Test_SourceGeneratorsDiagnostics.cs index 319e0314e..8d9f3786c 100644 --- a/tests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests/Test_SourceGeneratorsDiagnostics.cs +++ b/tests/CommunityToolkit.Mvvm.SourceGenerators.UnitTests/Test_SourceGeneratorsDiagnostics.cs @@ -11,6 +11,9 @@ using Microsoft.CodeAnalysis.CSharp; using CommunityToolkit.Mvvm.ComponentModel; using Microsoft.VisualStudio.TestTools.UnitTesting; +using System.Threading.Tasks; +using CommunityToolkit.Mvvm.SourceGenerators.UnitTests.Helpers; +using System.Text.RegularExpressions; namespace CommunityToolkit.Mvvm.SourceGenerators.UnitTests; @@ -231,7 +234,7 @@ public partial class SampleViewModel } [TestMethod] - public void UnsupportedCSharpLanguageVersion_FromINotifyPropertyChangedGenerator() + public async Task UnsupportedCSharpLanguageVersion_FromINotifyPropertyChangedGenerator() { string source = @" using CommunityToolkit.Mvvm.ComponentModel; @@ -239,20 +242,16 @@ public void UnsupportedCSharpLanguageVersion_FromINotifyPropertyChangedGenerator namespace MyApp { [INotifyPropertyChanged] - public partial class SampleViewModel + public partial class {|MVVMTK0008:SampleViewModel|} { } }"; - VerifyGeneratedDiagnostics( - CSharpSyntaxTree.ParseText(source, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_3)), - "MVVMTK0008"); - - VerifySuccessfulGeneration(source); + await VerifyUnsupportedCSharpVersionAndSuccessfulGeneration(source); } [TestMethod] - public void UnsupportedCSharpLanguageVersion_FromObservableObjectGenerator() + public async Task UnsupportedCSharpLanguageVersion_FromObservableObjectGenerator() { string source = @" using CommunityToolkit.Mvvm.ComponentModel; @@ -260,20 +259,16 @@ public void UnsupportedCSharpLanguageVersion_FromObservableObjectGenerator() namespace MyApp { [ObservableObject] - public partial class SampleViewModel + public partial class {|MVVMTK0008:SampleViewModel|} { } }"; - VerifyGeneratedDiagnostics( - CSharpSyntaxTree.ParseText(source, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_3)), - "MVVMTK0008"); - - VerifySuccessfulGeneration(source); + await VerifyUnsupportedCSharpVersionAndSuccessfulGeneration(source); } [TestMethod] - public void UnsupportedCSharpLanguageVersion_FromObservablePropertyGenerator() + public async Task UnsupportedCSharpLanguageVersion_FromObservablePropertyGenerator() { string source = @" using CommunityToolkit.Mvvm.ComponentModel; @@ -281,23 +276,43 @@ public void UnsupportedCSharpLanguageVersion_FromObservablePropertyGenerator() namespace MyApp { [INotifyPropertyChanged] - public partial class SampleViewModel + public partial class {|MVVMTK0008:SampleViewModel|} { [ObservableProperty] - private string name; + private string {|MVVMTK0008:name|}; } }"; - VerifyGeneratedDiagnostics( - CSharpSyntaxTree.ParseText(source, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_3)), - "MVVMTK0008"); + await VerifyUnsupportedCSharpVersionAndSuccessfulGeneration(source); + } - VerifySuccessfulGeneration(source); + [TestMethod] + public async Task UnsupportedCSharpLanguageVersion_FromObservablePropertyGenerator_MultipleAttributes() + { + string source = @" + using CommunityToolkit.Mvvm.ComponentModel; + + namespace MyApp + { + [ObservableObject] + public partial class {|MVVMTK0008:SampleViewModel|} + { + [ObservableProperty] + string {|MVVMTK0008:name|}; + + [ObservableProperty] + [NotifyPropertyChangedFor(nameof(Bar))] + int {|MVVMTK0008:number|}; + + string Bar { get; set; } + } + }"; + + await VerifyUnsupportedCSharpVersionAndSuccessfulGeneration(source); } [TestMethod] - [Ignore("The generator should just not trigger at all in this scenario, update this after migrating diagnostics")] - public void UnsupportedCSharpLanguageVersion_FromObservableValidatorValidateAllPropertiesGenerator() + public async Task UnsupportedCSharpLanguageVersion_FromObservableValidatorValidateAllPropertiesGenerator() { string source = @" using System.ComponentModel.DataAnnotations; @@ -312,15 +327,11 @@ public partial class SampleViewModel : ObservableValidator } }"; - // Compilation should be fine on C# 7.3 as well (the generator just doesn't trigger) - VerifyGeneratedDiagnostics( - CSharpSyntaxTree.ParseText(source, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_3))); - - VerifySuccessfulGeneration(source); + await VerifyUnsupportedCSharpVersionAndSuccessfulGeneration(source); } [TestMethod] - public void UnsupportedCSharpLanguageVersion_FromRelayCommandGenerator() + public async Task UnsupportedCSharpLanguageVersion_FromRelayCommandGenerator() { string source = @" using CommunityToolkit.Mvvm.Input; @@ -330,21 +341,17 @@ namespace MyApp public partial class SampleViewModel { [RelayCommand] - private void GreetUser(object value) + private void {|MVVMTK0008:GreetUser|}(object value) { } } }"; - VerifyGeneratedDiagnostics( - CSharpSyntaxTree.ParseText(source, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_3)), - "MVVMTK0008"); - - VerifySuccessfulGeneration(source); + await VerifyUnsupportedCSharpVersionAndSuccessfulGeneration(source); } [TestMethod] - public void UnsupportedCSharpLanguageVersion_FromIMessengerRegisterAllGenerator() + public async Task UnsupportedCSharpLanguageVersion_FromIMessengerRegisterAllGenerator() { string source = @" using CommunityToolkit.Mvvm.Messaging; @@ -363,12 +370,7 @@ public void Receive(MyMessage message) } }"; - // This should run fine on C# 8.0 too, as it doesn't use any newer features. Additionally, when not supported this - // generator should just not run, not cause issues. The MVVM Toolkit has a reflection-based fallback path for this. - VerifyGeneratedDiagnostics( - CSharpSyntaxTree.ParseText(source, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8))); - - VerifySuccessfulGeneration(source); + await VerifyUnsupportedCSharpVersionAndSuccessfulGeneration(source); } [TestMethod] @@ -1425,35 +1427,14 @@ private void GreetUser(User user) VerifyGeneratedDiagnostics(source, "MVVMTK0031"); } - [TestMethod] - public void ValidObservablePropertyGeneratorScenarios() - { - string source = @" - using CommunityToolkit.Mvvm.ComponentModel; - - namespace MyApp - { - [ObservableObject] - public partial class SampleViewModel - { - [ObservableProperty] - string name; - - [ObservableProperty] - [NotifyPropertyChangedFor(nameof(Name))] - int number; - } - }"; - - VerifySuccessfulGeneration(source); - } - /// - /// Verifies that all available source generators can run successfully with the input source (including subsequent compilation). + /// Verifies the diagnostic error for unsupported C# version, and that all available source generators can run successfully with the input source (including subsequent compilation). /// - /// The input source to process. - private static void VerifySuccessfulGeneration(string source) + /// The input source to process with diagnostic annotations. + private static async Task VerifyUnsupportedCSharpVersionAndSuccessfulGeneration(string markdownSource) { + await CSharpAnalyzerWithLanguageVersionTest.VerifyAnalyzerAsync(markdownSource, LanguageVersion.CSharp7_3); + IIncrementalGenerator[] generators = { new IMessengerRegisterAllGenerator(), @@ -1466,7 +1447,10 @@ private static void VerifySuccessfulGeneration(string source) new RelayCommandGenerator() }; - VerifyGeneratedDiagnostics(CSharpSyntaxTree.ParseText(source, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp8)), generators, Array.Empty()); + // Transform diagnostic annotations back to normal C# (eg. "{|MVVMTK0008:Foo()|}" ---> "Foo()") + string source = Regex.Replace(markdownSource, @"{\|((?:,?\w+)+):(.+)\|}", m => m.Groups[2].Value); + + VerifyGeneratedDiagnostics(CSharpSyntaxTree.ParseText(source, CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp7_3)), generators, Array.Empty()); } /// @@ -1505,15 +1489,18 @@ private static void VerifyGeneratedDiagnostics(SyntaxTree syntaxTree /// The diagnostic ids to expect for the input source code. private static void VerifyGeneratedDiagnostics(SyntaxTree syntaxTree, IIncrementalGenerator[] generators, string[] generatorDiagnosticsIds) { + // Ensure CommunityToolkit.Mvvm and System.ComponentModel.DataAnnotations are loaded Type observableObjectType = typeof(ObservableObject); Type validationAttributeType = typeof(ValidationAttribute); + // Get all assembly references for the loaded assemblies (easy way to pull in all necessary dependencies) IEnumerable references = from assembly in AppDomain.CurrentDomain.GetAssemblies() where !assembly.IsDynamic let reference = MetadataReference.CreateFromFile(assembly.Location) select reference; + // Create a syntax tree with the input source CSharpCompilation compilation = CSharpCompilation.Create( "original", new SyntaxTree[] { syntaxTree }, @@ -1522,19 +1509,20 @@ from assembly in AppDomain.CurrentDomain.GetAssemblies() GeneratorDriver driver = CSharpGeneratorDriver.Create(generators).WithUpdatedParseOptions((CSharpParseOptions)syntaxTree.Options); + // Run all source generators on the input source code _ = driver.RunGeneratorsAndUpdateCompilation(compilation, out Compilation outputCompilation, out ImmutableArray diagnostics); - HashSet resultingIds = diagnostics.Select(diagnostic => diagnostic.Id).ToHashSet(); + string[] resultingIds = diagnostics.Select(diagnostic => diagnostic.Id).ToArray(); - CollectionAssert.AreEquivalent(generatorDiagnosticsIds, resultingIds.ToArray(), $"resultingIds: {string.Join(", ", resultingIds)}"); + CollectionAssert.AreEquivalent(generatorDiagnosticsIds, resultingIds, $"resultingIds: {string.Join(", ", resultingIds)}"); // If the compilation was supposed to succeed, ensure that no further errors were generated - if (resultingIds.Count == 0) + if (resultingIds.Length == 0) { // Compute diagnostics for the final compiled output (just include errors) List outputCompilationDiagnostics = outputCompilation.GetDiagnostics().Where(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error).ToList(); - Assert.IsTrue(outputCompilationDiagnostics.Count == 0, $"resultingIds:{Environment.NewLine} {string.Join(Environment.NewLine, outputCompilationDiagnostics)}"); + Assert.IsTrue(outputCompilationDiagnostics.Count == 0, $"resultingIds: {string.Join(", ", outputCompilationDiagnostics)}"); } GC.KeepAlive(observableObjectType);