diff --git a/eng/Version.Details.xml b/eng/Version.Details.xml index fc8c4b88e0d0..af59585c0372 100644 --- a/eng/Version.Details.xml +++ b/eng/Version.Details.xml @@ -233,6 +233,10 @@ https://github.com/dotnet/razor-compiler 55e950892723d077c2707450ae8a8218bf4abc9c + + https://github.com/dotnet/razor-compiler + 55e950892723d077c2707450ae8a8218bf4abc9c + https://github.com/dotnet/aspnetcore ac67d32b92520edb35139645074c704cc2605fbd diff --git a/eng/Versions.props b/eng/Versions.props index f9bd3b1fb919..c57998446c39 100644 --- a/eng/Versions.props +++ b/eng/Versions.props @@ -150,9 +150,13 @@ 7.0.0-rc.1.22364.1 7.0.0-rc.1.22364.1 7.0.0-rc.1.22364.1 - 7.0.0-preview.5.22357.2 - 7.0.0-preview.5.22357.2 - 7.0.0-preview.5.22357.2 + + + + 7.0.0-preview.5.22356.1 + 7.0.0-preview.5.22356.1 + 7.0.0-preview.5.22356.1 + 7.0.0-preview.5.22357.2 diff --git a/sdk.sln b/sdk.sln index 49168558be70..fd10face428b 100644 --- a/sdk.sln +++ b/sdk.sln @@ -337,16 +337,10 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Rules", "Rules", "{A117DF29 src\RazorSdk\Targets\Rules\RazorGenerateWithTargetPath.xaml = src\RazorSdk\Targets\Rules\RazorGenerateWithTargetPath.xaml EndProjectSection EndProject -Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "SourceGenerators", "SourceGenerators", "{C2B15A41-A9C0-456A-A9FF-649E9237D850}" -EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.NET.Sdk.Razor.SourceGenerators", "src\RazorSdk\SourceGenerators\Microsoft.NET.Sdk.Razor.SourceGenerators.csproj", "{56C34654-DE8F-4F14-B2F8-6C37285B786E}" -EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.Extensions.DotNetDeltaApplier", "src\BuiltInTools\DotNetDeltaApplier\Microsoft.Extensions.DotNetDeltaApplier.csproj", "{1BBFA19C-03F0-4D27-9D0D-0F8172642107}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.DotNet.NativeWrapper", "src\Resolvers\Microsoft.DotNet.NativeWrapper\Microsoft.DotNet.NativeWrapper.csproj", "{E97E9E7F-11B4-42F7-8B55-D0451F5E82A0}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.NET.Sdk.Razor.SourceGenerators.Tests", "src\Tests\Microsoft.NET.Sdk.Razor.SourceGenerators.Tests\Microsoft.NET.Sdk.Razor.SourceGenerators.Tests.csproj", "{A71FC21D-D90A-49B5-9B5A-AD4776287B55}" -EndProject Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Compatibility", "Compatibility", "{AF683E5C-421E-4DE0-ADD7-9841E5D12BFA}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Microsoft.DotNet.ApiCompatibility", "src\Compatibility\Microsoft.DotNet.ApiCompatibility\Microsoft.DotNet.ApiCompatibility.csproj", "{3F5A028C-C51B-434A-8C10-37680CD2635C}" @@ -633,10 +627,6 @@ Global {08C9E634-39F3-4B24-BCEA-D0B21971EBBE}.Debug|Any CPU.Build.0 = Debug|Any CPU {08C9E634-39F3-4B24-BCEA-D0B21971EBBE}.Release|Any CPU.ActiveCfg = Release|Any CPU {08C9E634-39F3-4B24-BCEA-D0B21971EBBE}.Release|Any CPU.Build.0 = Release|Any CPU - {56C34654-DE8F-4F14-B2F8-6C37285B786E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {56C34654-DE8F-4F14-B2F8-6C37285B786E}.Debug|Any CPU.Build.0 = Debug|Any CPU - {56C34654-DE8F-4F14-B2F8-6C37285B786E}.Release|Any CPU.ActiveCfg = Release|Any CPU - {56C34654-DE8F-4F14-B2F8-6C37285B786E}.Release|Any CPU.Build.0 = Release|Any CPU {1BBFA19C-03F0-4D27-9D0D-0F8172642107}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {1BBFA19C-03F0-4D27-9D0D-0F8172642107}.Debug|Any CPU.Build.0 = Debug|Any CPU {1BBFA19C-03F0-4D27-9D0D-0F8172642107}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -645,10 +635,6 @@ Global {E97E9E7F-11B4-42F7-8B55-D0451F5E82A0}.Debug|Any CPU.Build.0 = Debug|Any CPU {E97E9E7F-11B4-42F7-8B55-D0451F5E82A0}.Release|Any CPU.ActiveCfg = Release|Any CPU {E97E9E7F-11B4-42F7-8B55-D0451F5E82A0}.Release|Any CPU.Build.0 = Release|Any CPU - {A71FC21D-D90A-49B5-9B5A-AD4776287B55}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {A71FC21D-D90A-49B5-9B5A-AD4776287B55}.Debug|Any CPU.Build.0 = Debug|Any CPU - {A71FC21D-D90A-49B5-9B5A-AD4776287B55}.Release|Any CPU.ActiveCfg = Release|Any CPU - {A71FC21D-D90A-49B5-9B5A-AD4776287B55}.Release|Any CPU.Build.0 = Release|Any CPU {3F5A028C-C51B-434A-8C10-37680CD2635C}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {3F5A028C-C51B-434A-8C10-37680CD2635C}.Debug|Any CPU.Build.0 = Debug|Any CPU {3F5A028C-C51B-434A-8C10-37680CD2635C}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -685,10 +671,6 @@ Global {87AE3308-8CCB-4383-8F51-C5061E348C36}.Debug|Any CPU.Build.0 = Debug|Any CPU {87AE3308-8CCB-4383-8F51-C5061E348C36}.Release|Any CPU.ActiveCfg = Release|Any CPU {87AE3308-8CCB-4383-8F51-C5061E348C36}.Release|Any CPU.Build.0 = Release|Any CPU - {08A18C0B-8985-49EE-AC80-EFEEDF18BCC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU - {08A18C0B-8985-49EE-AC80-EFEEDF18BCC5}.Debug|Any CPU.Build.0 = Debug|Any CPU - {08A18C0B-8985-49EE-AC80-EFEEDF18BCC5}.Release|Any CPU.ActiveCfg = Release|Any CPU - {08A18C0B-8985-49EE-AC80-EFEEDF18BCC5}.Release|Any CPU.Build.0 = Release|Any CPU {920F6448-C2D0-4B01-AC25-16214C5A6006}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {920F6448-C2D0-4B01-AC25-16214C5A6006}.Debug|Any CPU.Build.0 = Debug|Any CPU {920F6448-C2D0-4B01-AC25-16214C5A6006}.Release|Any CPU.ActiveCfg = Release|Any CPU @@ -697,6 +679,10 @@ Global {9D08CED8-02CC-4566-A3B7-3434D205F0A2}.Debug|Any CPU.Build.0 = Debug|Any CPU {9D08CED8-02CC-4566-A3B7-3434D205F0A2}.Release|Any CPU.ActiveCfg = Release|Any CPU {9D08CED8-02CC-4566-A3B7-3434D205F0A2}.Release|Any CPU.Build.0 = Release|Any CPU + {08A18C0B-8985-49EE-AC80-EFEEDF18BCC5}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {08A18C0B-8985-49EE-AC80-EFEEDF18BCC5}.Debug|Any CPU.Build.0 = Debug|Any CPU + {08A18C0B-8985-49EE-AC80-EFEEDF18BCC5}.Release|Any CPU.ActiveCfg = Release|Any CPU + {08A18C0B-8985-49EE-AC80-EFEEDF18BCC5}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE @@ -805,11 +791,8 @@ Global {4ACCAC39-8ECD-45F8-B5AF-EB7E37CD36CC} = {E9BDA8A6-1AD2-4D0E-A37C-9EC10D7FE773} {D64884FD-A3F3-4082-A814-A9377B661509} = {E9BDA8A6-1AD2-4D0E-A37C-9EC10D7FE773} {A117DF29-1D72-453B-A24C-3B53F47609F2} = {D64884FD-A3F3-4082-A814-A9377B661509} - {C2B15A41-A9C0-456A-A9FF-649E9237D850} = {E9BDA8A6-1AD2-4D0E-A37C-9EC10D7FE773} - {56C34654-DE8F-4F14-B2F8-6C37285B786E} = {C2B15A41-A9C0-456A-A9FF-649E9237D850} {1BBFA19C-03F0-4D27-9D0D-0F8172642107} = {71A9F549-0EB6-41F9-BC16-4A6C5007FC91} {E97E9E7F-11B4-42F7-8B55-D0451F5E82A0} = {8F22FBD6-BDC8-431E-8402-B7460D3A9724} - {A71FC21D-D90A-49B5-9B5A-AD4776287B55} = {580D1AE7-AA8F-4912-8B76-105594E00B3B} {AF683E5C-421E-4DE0-ADD7-9841E5D12BFA} = {22AB674F-ED91-4FBC-BFEE-8A1E82F9F05E} {3F5A028C-C51B-434A-8C10-37680CD2635C} = {AF683E5C-421E-4DE0-ADD7-9841E5D12BFA} {24F084ED-35BB-401E-89F5-63E5E22C3B3B} = {580D1AE7-AA8F-4912-8B76-105594E00B3B} @@ -820,10 +803,10 @@ Global {69C03400-12AC-4E4D-B970-6A880616BF68} = {580D1AE7-AA8F-4912-8B76-105594E00B3B} {FAAC2E23-A460-40FE-9207-C10EEE5A6A07} = {580D1AE7-AA8F-4912-8B76-105594E00B3B} {87AE3308-8CCB-4383-8F51-C5061E348C36} = {AF683E5C-421E-4DE0-ADD7-9841E5D12BFA} - {08A18C0B-8985-49EE-AC80-EFEEDF18BCC5} = {580D1AE7-AA8F-4912-8B76-105594E00B3B} {920F6448-C2D0-4B01-AC25-16214C5A6006} = {580D1AE7-AA8F-4912-8B76-105594E00B3B} {9D08CED8-02CC-4566-A3B7-3434D205F0A2} = {AF683E5C-421E-4DE0-ADD7-9841E5D12BFA} {68E743E6-5D4B-4CD4-941A-07285032451F} = {AF683E5C-421E-4DE0-ADD7-9841E5D12BFA} + {08A18C0B-8985-49EE-AC80-EFEEDF18BCC5} = {580D1AE7-AA8F-4912-8B76-105594E00B3B} EndGlobalSection GlobalSection(ExtensibilityGlobals) = postSolution SolutionGuid = {FB8F26CE-4DE6-433F-B32A-79183020BBD6} diff --git a/source-build.slnf b/source-build.slnf index 15db481dddd2..31c59f407e86 100644 --- a/source-build.slnf +++ b/source-build.slnf @@ -23,7 +23,6 @@ "src\\Layout\\toolset-tasks\\toolset-tasks.csproj", "src\\Microsoft.DotNet.TemplateLocator\\Microsoft.DotNet.TemplateLocator.csproj", "src\\Microsoft.Win32.Msi\\Microsoft.Win32.Msi.csproj", - "src\\RazorSdk\\SourceGenerators\\Microsoft.NET.Sdk.Razor.SourceGenerators.csproj", "src\\RazorSdk\\Tasks\\Microsoft.NET.Sdk.Razor.Tasks.csproj", "src\\RazorSdk\\Tool\\Microsoft.NET.Sdk.Razor.Tool.csproj", "src\\Resolvers\\Microsoft.DotNet.MSBuildSdkResolver\\Microsoft.DotNet.MSBuildSdkResolver.csproj", diff --git a/src/Layout/redist/redist.csproj b/src/Layout/redist/redist.csproj index c20f726736b8..7c11e957f1d1 100644 --- a/src/Layout/redist/redist.csproj +++ b/src/Layout/redist/redist.csproj @@ -36,6 +36,7 @@ + diff --git a/src/Layout/redist/targets/GenerateLayout.targets b/src/Layout/redist/targets/GenerateLayout.targets index db647b6c246d..c493a1111cb0 100644 --- a/src/Layout/redist/targets/GenerateLayout.targets +++ b/src/Layout/redist/targets/GenerateLayout.targets @@ -299,10 +299,6 @@ Targets="Publish" Projects="$(RepoRoot)/src/RazorSdk/Tool/Microsoft.NET.Sdk.Razor.Tool.csproj" Properties="Configuration=$(Configuration)" /> - @@ -313,9 +309,7 @@ rzc executable. --> <_RazorToolOutput Remove="$(ArtifactsBinDir)Microsoft.NET.Sdk.Razor.Tool\$(Configuration)\$(SdkTargetFramework)\publish\Microsoft.CodeAnalysis.dll" /> <_RazorToolOutput Remove="$(ArtifactsBinDir)Microsoft.NET.Sdk.Razor.Tool\$(Configuration)\$(SdkTargetFramework)\publish\Microsoft.CodeAnalysis.CSharp.dll" /> - <_RazorSourceGeneratorsOutput Include="$(ArtifactsBinDir)Microsoft.NET.Sdk.Razor.SourceGenerators\$(Configuration)\netstandard2.0\publish\Microsoft.AspNetCore.Razor.SourceGenerator.Tooling.Internal.dll" /> - <_RazorSourceGeneratorsOutput Include="$(ArtifactsBinDir)Microsoft.NET.Sdk.Razor.SourceGenerators\$(Configuration)\netstandard2.0\publish\Microsoft.NET.Sdk.Razor.SourceGenerators.dll" /> - <_RazorSourceGeneratorsOutput Include="$(ArtifactsBinDir)Microsoft.NET.Sdk.Razor.SourceGenerators\$(Configuration)\netstandard2.0\publish\RazorSourceGenerator.razorencconfig " /> + <_RazorSourceGeneratorsOutput Include="$(PkgMicrosoft_NET_Sdk_Razor_SourceGenerators_Transport)\source-generators\*" /> _action; - - public ConfigureRazorCodeGenerationOptions(Action action) - { - _action = action; - } - - public int Order { get; set; } - - public void Configure(RazorCodeGenerationOptionsBuilder options) => _action(options); - } -} diff --git a/src/RazorSdk/SourceGenerators/Diagnostics/DiagnosticIds.cs b/src/RazorSdk/SourceGenerators/Diagnostics/DiagnosticIds.cs deleted file mode 100644 index 762a70463f0c..000000000000 --- a/src/RazorSdk/SourceGenerators/Diagnostics/DiagnosticIds.cs +++ /dev/null @@ -1,19 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -namespace Microsoft.NET.Sdk.Razor.SourceGenerators -{ - internal static class DiagnosticIds - { - public const string InvalidRazorLangVersionRuleId = "RZ3600"; - public const string ReComputingTagHelpersRuleId = "RSG001"; - public const string TargetPathNotProvidedRuleId = "RSG002"; - public const string GeneratedOutputFullPathNotProvidedRuleId = "RSG003"; - public const string CurrentCompilationReferenceNotFoundId = "RSG004"; - public const string SkippingGeneratedFileWriteId = "RSG005"; - public const string SourceTextNotFoundId = "RSG006"; - public const string UnexpectedProjectItemReadCallId = "RSG007"; - public const string InvalidRazorContextComputedId = "RSG008"; - public const string MetadataReferenceNotProvidedId = "RSG009"; - } -} diff --git a/src/RazorSdk/SourceGenerators/Diagnostics/RazorDiagnostics.cs b/src/RazorSdk/SourceGenerators/Diagnostics/RazorDiagnostics.cs deleted file mode 100644 index 1589e0d79943..000000000000 --- a/src/RazorSdk/SourceGenerators/Diagnostics/RazorDiagnostics.cs +++ /dev/null @@ -1,141 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Globalization; -using Microsoft.AspNetCore.Razor.Language; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Text; -using Microsoft.CodeAnalysis.Razor; -using Microsoft.NET.Sdk.Razor.SourceGenerators.Diagnostics; - -namespace Microsoft.NET.Sdk.Razor.SourceGenerators -{ - internal static class RazorDiagnostics - { - public static readonly DiagnosticDescriptor InvalidRazorLangVersionDescriptor = new DiagnosticDescriptor( - DiagnosticIds.InvalidRazorLangVersionRuleId, - new LocalizableResourceString(nameof(RazorSourceGeneratorResources.InvalidRazorLangTitle), RazorSourceGeneratorResources.ResourceManager, typeof(RazorSourceGeneratorResources)), - new LocalizableResourceString(nameof(RazorSourceGeneratorResources.InvalidRazorLangMessage), RazorSourceGeneratorResources.ResourceManager, typeof(RazorSourceGeneratorResources)), - "RazorSourceGenerator", - DiagnosticSeverity.Error, - isEnabledByDefault: true); - - public static readonly DiagnosticDescriptor ReComputingTagHelpersDescriptor = new DiagnosticDescriptor( - DiagnosticIds.ReComputingTagHelpersRuleId, - new LocalizableResourceString(nameof(RazorSourceGeneratorResources.RecomputingTagHelpersTitle), RazorSourceGeneratorResources.ResourceManager, typeof(RazorSourceGeneratorResources)), - new LocalizableResourceString(nameof(RazorSourceGeneratorResources.RecomputingTagHelpersMessage), RazorSourceGeneratorResources.ResourceManager, typeof(RazorSourceGeneratorResources)), - "RazorSourceGenerator", - DiagnosticSeverity.Info, - isEnabledByDefault: true); - - public static readonly DiagnosticDescriptor TargetPathNotProvided = new DiagnosticDescriptor( - DiagnosticIds.TargetPathNotProvidedRuleId, - new LocalizableResourceString(nameof(RazorSourceGeneratorResources.TargetPathNotProvidedTitle), RazorSourceGeneratorResources.ResourceManager, typeof(RazorSourceGeneratorResources)), - new LocalizableResourceString(nameof(RazorSourceGeneratorResources.TargetPathNotProvidedMessage), RazorSourceGeneratorResources.ResourceManager, typeof(RazorSourceGeneratorResources)), - "RazorSourceGenerator", - DiagnosticSeverity.Warning, - isEnabledByDefault: true - ); - - public static readonly DiagnosticDescriptor GeneratedOutputFullPathNotProvided = new DiagnosticDescriptor( - DiagnosticIds.GeneratedOutputFullPathNotProvidedRuleId, - new LocalizableResourceString(nameof(RazorSourceGeneratorResources.GeneratedOutputFullPathNotProvidedTitle), RazorSourceGeneratorResources.ResourceManager, typeof(RazorSourceGeneratorResources)), - new LocalizableResourceString(nameof(RazorSourceGeneratorResources.GeneratedOutputFullPathNotProvidedMessage), RazorSourceGeneratorResources.ResourceManager, typeof(RazorSourceGeneratorResources)), - "RazorSourceGenerator", - DiagnosticSeverity.Warning, - isEnabledByDefault: true - ); - - public static readonly DiagnosticDescriptor CurrentCompilationReferenceNotFoundDescriptor = new DiagnosticDescriptor( - DiagnosticIds.CurrentCompilationReferenceNotFoundId, - new LocalizableResourceString(nameof(RazorSourceGeneratorResources.CurrentCompilationReferenceNotFoundTitle), RazorSourceGeneratorResources.ResourceManager, typeof(RazorSourceGeneratorResources)), - new LocalizableResourceString(nameof(RazorSourceGeneratorResources.CurrentCompilationReferenceNotFoundMessage), RazorSourceGeneratorResources.ResourceManager, typeof(RazorSourceGeneratorResources)), - "RazorSourceGenerator", - DiagnosticSeverity.Warning, - isEnabledByDefault: true - ); - - public static readonly DiagnosticDescriptor SkippingGeneratedFileWriteDescriptor = new DiagnosticDescriptor( - DiagnosticIds.SkippingGeneratedFileWriteId, - new LocalizableResourceString(nameof(RazorSourceGeneratorResources.SkippingGeneratedFileWriteTitle), RazorSourceGeneratorResources.ResourceManager, typeof(RazorSourceGeneratorResources)), - new LocalizableResourceString(nameof(RazorSourceGeneratorResources.SkippingGeneratedFileWriteMessage), RazorSourceGeneratorResources.ResourceManager, typeof(RazorSourceGeneratorResources)), - "RazorSourceGenerator", - DiagnosticSeverity.Warning, - isEnabledByDefault: true - ); - - public static readonly DiagnosticDescriptor SourceTextNotFoundDescriptor = new DiagnosticDescriptor( - DiagnosticIds.SourceTextNotFoundId, - new LocalizableResourceString(nameof(RazorSourceGeneratorResources.SourceTextNotFoundTitle), RazorSourceGeneratorResources.ResourceManager, typeof(RazorSourceGeneratorResources)), - new LocalizableResourceString(nameof(RazorSourceGeneratorResources.SourceTextNotFoundMessage), RazorSourceGeneratorResources.ResourceManager, typeof(RazorSourceGeneratorResources)), - "RazorSourceGenerator", - DiagnosticSeverity.Error, - isEnabledByDefault: true - ); - - public static readonly DiagnosticDescriptor UnexpectedProjectItemReadCallDescriptor = new DiagnosticDescriptor( - DiagnosticIds.UnexpectedProjectItemReadCallId, - new LocalizableResourceString(nameof(RazorSourceGeneratorResources.UnexpectedProjectItemReadCallTitle), RazorSourceGeneratorResources.ResourceManager, typeof(RazorSourceGeneratorResources)), - new LocalizableResourceString(nameof(RazorSourceGeneratorResources.UnexpectedProjectItemReadCallMessage), RazorSourceGeneratorResources.ResourceManager, typeof(RazorSourceGeneratorResources)), - "RazorSourceGenerator", - DiagnosticSeverity.Error, - isEnabledByDefault: true - ); - - public static readonly DiagnosticDescriptor InvalidRazorContextComputedDescriptor = new DiagnosticDescriptor( - DiagnosticIds.InvalidRazorContextComputedId, - new LocalizableResourceString(nameof(RazorSourceGeneratorResources.InvalidRazorContextComputedTitle), RazorSourceGeneratorResources.ResourceManager, typeof(RazorSourceGeneratorResources)), - new LocalizableResourceString(nameof(RazorSourceGeneratorResources.InvalidRazorContextComputedMessage), RazorSourceGeneratorResources.ResourceManager, typeof(RazorSourceGeneratorResources)), - "RazorSourceGenerator", - DiagnosticSeverity.Info, - isEnabledByDefault: true - ); - - public static readonly DiagnosticDescriptor MetadataReferenceNotProvidedDescriptor = new DiagnosticDescriptor( - DiagnosticIds.MetadataReferenceNotProvidedId, - new LocalizableResourceString(nameof(RazorSourceGeneratorResources.MetadataReferenceNotProvidedTitle), RazorSourceGeneratorResources.ResourceManager, typeof(RazorSourceGeneratorResources)), - new LocalizableResourceString(nameof(RazorSourceGeneratorResources.MetadataReferenceNotProvidedMessage), RazorSourceGeneratorResources.ResourceManager, typeof(RazorSourceGeneratorResources)), - "RazorSourceGenerator", - DiagnosticSeverity.Info, - isEnabledByDefault: true - ); - - public static Diagnostic AsDiagnostic(this RazorDiagnostic razorDiagnostic) - { - var descriptor = new DiagnosticDescriptor( - razorDiagnostic.Id, - razorDiagnostic.GetMessage(CultureInfo.CurrentCulture), - razorDiagnostic.GetMessage(CultureInfo.CurrentCulture), - "Razor", - razorDiagnostic.Severity switch - { - RazorDiagnosticSeverity.Error => DiagnosticSeverity.Error, - RazorDiagnosticSeverity.Warning => DiagnosticSeverity.Warning, - _ => DiagnosticSeverity.Hidden, - }, - isEnabledByDefault: true); - - var span = razorDiagnostic.Span; - - Location location; - if (span == SourceSpan.Undefined) - { - // TextSpan.Empty - location = Location.None; - } - else - { - var linePosition = new LinePositionSpan( - new LinePosition(span.LineIndex, span.CharacterIndex), - new LinePosition(span.LineIndex, span.CharacterIndex + span.Length)); - - location = Location.Create( - span.FilePath, - span.AsTextSpan(), - linePosition); - } - - return Diagnostic.Create(descriptor, location); - } - } -} diff --git a/src/RazorSdk/SourceGenerators/Diagnostics/RazorSourceGeneratorResources.Designer.cs b/src/RazorSdk/SourceGenerators/Diagnostics/RazorSourceGeneratorResources.Designer.cs deleted file mode 100644 index e9b6ea32ef1c..000000000000 --- a/src/RazorSdk/SourceGenerators/Diagnostics/RazorSourceGeneratorResources.Designer.cs +++ /dev/null @@ -1,244 +0,0 @@ -//------------------------------------------------------------------------------ -// -// This code was generated by a tool. -// Runtime Version:4.0.30319.42000 -// -// Changes to this file may cause incorrect behavior and will be lost if -// the code is regenerated. -// -//------------------------------------------------------------------------------ - -namespace Microsoft.NET.Sdk.Razor.SourceGenerators.Diagnostics { - using System; - - - /// - /// A strongly-typed resource class, for looking up localized strings, etc. - /// - // This class was auto-generated by the StronglyTypedResourceBuilder - // class via a tool like ResGen or Visual Studio. - // To add or remove a member, edit your .ResX file then rerun ResGen - // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] - [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] - [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class RazorSourceGeneratorResources { - - private static global::System.Resources.ResourceManager resourceMan; - - private static global::System.Globalization.CultureInfo resourceCulture; - - [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] - internal RazorSourceGeneratorResources() { - } - - /// - /// Returns the cached ResourceManager instance used by this class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { - get { - if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Microsoft.NET.Sdk.Razor.SourceGenerators.Diagnostics.RazorSourceGeneratorResource" + - "s", typeof(RazorSourceGeneratorResources).Assembly); - resourceMan = temp; - } - return resourceMan; - } - } - - /// - /// Overrides the current thread's CurrentUICulture property for all - /// resource lookups using this strongly typed resource class. - /// - [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { - get { - return resourceCulture; - } - set { - resourceCulture = value; - } - } - - /// - /// Looks up a localized string similar to MetadataReference for current compilation not found'.. - /// - internal static string CurrentCompilationReferenceNotFoundMessage { - get { - return ResourceManager.GetString("CurrentCompilationReferenceNotFoundMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to MetadataReference not found. - /// - internal static string CurrentCompilationReferenceNotFoundTitle { - get { - return ResourceManager.GetString("CurrentCompilationReferenceNotFoundTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to GeneratedOutputFullPath not specified for additional file: {0}. - /// - internal static string GeneratedOutputFullPathNotProvidedMessage { - get { - return ResourceManager.GetString("GeneratedOutputFullPathNotProvidedMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to GeneratedOutputFullPath not defined. - /// - internal static string GeneratedOutputFullPathNotProvidedTitle { - get { - return ResourceManager.GetString("GeneratedOutputFullPathNotProvidedTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Could not create a valid Razor generator context.. - /// - internal static string InvalidRazorContextComputedMessage { - get { - return ResourceManager.GetString("InvalidRazorContextComputedMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid Razor generator context. - /// - internal static string InvalidRazorContextComputedTitle { - get { - return ResourceManager.GetString("InvalidRazorContextComputedTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid value '{0}'' for RazorLangVersion. Valid values include 'Latest' or a valid version in range 1.0 to 5.0.. - /// - internal static string InvalidRazorLangMessage { - get { - return ResourceManager.GetString("InvalidRazorLangMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Invalid RazorLangVersion. - /// - internal static string InvalidRazorLangTitle { - get { - return ResourceManager.GetString("InvalidRazorLangTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to MetadataReference not provided. - /// - internal static string MetadataReferenceNotProvidedTitle { - get { - return ResourceManager.GetString("MetadataReferenceNotProvidedTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Expected a valid MetadataReference but found none.. - /// - internal static string MetadataReferenceNotProvidedMessage { - get { - return ResourceManager.GetString("MetadataReferenceNotProvidedMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Recomputing tag helpers from target MetadataReference: {0}. Found {1} descriptors.. - /// - internal static string RecomputingTagHelpersMessage { - get { - return ResourceManager.GetString("RecomputingTagHelpersMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Recomputing tag helpers. - /// - internal static string RecomputingTagHelpersTitle { - get { - return ResourceManager.GetString("RecomputingTagHelpersTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Generated source for '{0}' was not written to disk because output path was not defined.. - /// - internal static string SkippingGeneratedFileWriteMessage { - get { - return ResourceManager.GetString("SkippingGeneratedFileWriteMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Generated file not written disk. - /// - internal static string SkippingGeneratedFileWriteTitle { - get { - return ResourceManager.GetString("SkippingGeneratedFileWriteTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Source text for '{0}' was not resolved.. - /// - internal static string SourceTextNotFoundMessage { - get { - return ResourceManager.GetString("SourceTextNotFoundMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to SourceText not found. - /// - internal static string SourceTextNotFoundTitle { - get { - return ResourceManager.GetString("SourceTextNotFoundTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to TargetPath not specified for additional file: {0}. - /// - internal static string TargetPathNotProvidedMessage { - get { - return ResourceManager.GetString("TargetPathNotProvidedMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to TargetPath not defined. - /// - internal static string TargetPathNotProvidedTitle { - get { - return ResourceManager.GetString("TargetPathNotProvidedTitle", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Attempted to read source document for '{0}' from stream. Should use RazorSourceDocument instead.. - /// - internal static string UnexpectedProjectItemReadCallMessage { - get { - return ResourceManager.GetString("UnexpectedProjectItemReadCallMessage", resourceCulture); - } - } - - /// - /// Looks up a localized string similar to Unexpected call to read from stream. - /// - internal static string UnexpectedProjectItemReadCallTitle { - get { - return ResourceManager.GetString("UnexpectedProjectItemReadCallTitle", resourceCulture); - } - } - } -} diff --git a/src/RazorSdk/SourceGenerators/Diagnostics/RazorSourceGeneratorResources.resx b/src/RazorSdk/SourceGenerators/Diagnostics/RazorSourceGeneratorResources.resx deleted file mode 100644 index 0b33e3d77cfc..000000000000 --- a/src/RazorSdk/SourceGenerators/Diagnostics/RazorSourceGeneratorResources.resx +++ /dev/null @@ -1,180 +0,0 @@ - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - text/microsoft-resx - - - 2.0 - - - System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 - - - Invalid RazorLangVersion - - - Invalid value '{0}'' for RazorLangVersion. Valid values include 'Latest' or a valid version in range 1.0 to 7.0. - - - Recomputing tag helpers - - - Recomputing tag helpers from target MetadataReference: {0}. Found {1} descriptors. - - - TargetPath not defined - - - TargetPath not specified for additional file: {0}. - - - GeneratedOutputFullPath not defined - - - GeneratedOutputFullPath not specified for additional file: {0}. - - - MetadataReference not found - - - MetadataReference for current compilation not found. - - - Generated file not written disk - - - Generated source for '{0}' was not written to disk because output path was not defined. - - - SourceText not found - - - Source text for '{0}' was not resolved. - - - Unexpected call to read from stream - - - Attempted to read source document for '{0}' from stream. Should use RazorSourceDocument instead. - - - Invalid Razor generator context - - - Could not create a valid Razor source generator context. - - - MetadataReference not provided - - - Expected a valid MetadataReference, but found none. - - diff --git a/src/RazorSdk/SourceGenerators/IncrementalValueProviderExtensions.cs b/src/RazorSdk/SourceGenerators/IncrementalValueProviderExtensions.cs deleted file mode 100644 index a2a0ec755430..000000000000 --- a/src/RazorSdk/SourceGenerators/IncrementalValueProviderExtensions.cs +++ /dev/null @@ -1,69 +0,0 @@ - -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using Microsoft.CodeAnalysis; - -namespace Microsoft.NET.Sdk.Razor.SourceGenerators -{ - internal static class IncrementalValuesProviderExtensions - { - internal static IncrementalValueProvider WithLambdaComparer(this IncrementalValueProvider source, Func equal, Func getHashCode) - { - var comparer = new LambdaComparer(equal, getHashCode); - return source.WithComparer(comparer); - } - - internal static IncrementalValuesProvider WithLambdaComparer(this IncrementalValuesProvider source, Func equal, Func getHashCode) - { - var comparer = new LambdaComparer(equal, getHashCode); - return source.WithComparer(comparer); - } - - internal static IncrementalValuesProvider ReportDiagnostics(this IncrementalValuesProvider<(TSource?, Diagnostic?)> source, IncrementalGeneratorInitializationContext context) - { - context.RegisterSourceOutput(source, (spc, source) => - { - var (sourceItem, diagnostic) = source; - if (sourceItem == null && diagnostic != null) - { - spc.ReportDiagnostic(diagnostic); - } - }); - - return source.Where((pair) => pair.Item1 != null).Select((pair, ct) => pair.Item1!); - } - - internal static IncrementalValueProvider ReportDiagnostics(this IncrementalValueProvider<(TSource?, Diagnostic?)> source, IncrementalGeneratorInitializationContext context) - { - context.RegisterSourceOutput(source, (spc, source) => - { - var (sourceItem, diagnostic) = source; - if (sourceItem == null && diagnostic != null) - { - spc.ReportDiagnostic(diagnostic); - } - }); - - return source.Select((pair, ct) => pair.Item1!); - } - } - - internal sealed class LambdaComparer : IEqualityComparer - { - private readonly Func _equal; - private readonly Func _getHashCode; - - public LambdaComparer(Func equal, Func getHashCode) - { - _equal = equal; - _getHashCode = getHashCode; - } - - public bool Equals(T x, T y) => _equal(x, y); - - public int GetHashCode(T obj) => _getHashCode(obj); - } -} diff --git a/src/RazorSdk/SourceGenerators/Microsoft.NET.Sdk.Razor.SourceGenerators.csproj b/src/RazorSdk/SourceGenerators/Microsoft.NET.Sdk.Razor.SourceGenerators.csproj deleted file mode 100644 index f472a960c4a3..000000000000 --- a/src/RazorSdk/SourceGenerators/Microsoft.NET.Sdk.Razor.SourceGenerators.csproj +++ /dev/null @@ -1,40 +0,0 @@ - - - - netstandard2.0 - MicrosoftAspNetCore - - - false - false - RS2008 - enable - - - - - $(MicrosoftCodeAnalysisCSharpAnalyzerPinnedVersionPackageVersion) - $(MicrosoftCodeAnalysisCSharpPackageVersion) - - - - - - - - - - - - - - $(GetTargetPathDependsOn);GetDependencyTargetPaths - - - - - - - - - diff --git a/src/RazorSdk/SourceGenerators/Properties/AssemblyInfo.cs b/src/RazorSdk/SourceGenerators/Properties/AssemblyInfo.cs deleted file mode 100644 index b6d2580478c6..000000000000 --- a/src/RazorSdk/SourceGenerators/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,6 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Runtime.CompilerServices; - -[assembly: InternalsVisibleTo("Microsoft.NET.Sdk.Razor.SourceGenerators.Tests, PublicKey=0024000004800000940000000602000000240000525341310004000001000100b5fc90e7027f67871e773a8fde8938c81dd402ba65b9201d60593e96c492651e889cc13f1415ebb53fac1131ae0bd333c5ee6021672d9718ea31a8aebd0da0072f25d87dba6fc90ffd598ed4da35e44c398c454307e8e33b8426143daec9f596836f97c8f74750e5975c64e2189f45def46b2a2b1247adc3652bf5c308055da9")] diff --git a/src/RazorSdk/SourceGenerators/RazorSourceGenerationOptions.cs b/src/RazorSdk/SourceGenerators/RazorSourceGenerationOptions.cs deleted file mode 100644 index dd5ab8f05b30..000000000000 --- a/src/RazorSdk/SourceGenerators/RazorSourceGenerationOptions.cs +++ /dev/null @@ -1,46 +0,0 @@ - -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using Microsoft.AspNetCore.Razor.Language; -using Microsoft.CodeAnalysis.CSharp; - -namespace Microsoft.NET.Sdk.Razor.SourceGenerators -{ - internal sealed class RazorSourceGenerationOptions : IEquatable - { - public string RootNamespace { get; set; } = "ASP"; - - public RazorConfiguration Configuration { get; set; } = RazorConfiguration.Default; - - /// - /// Gets a flag that determines if generated Razor views and Pages includes the RazorSourceChecksumAttribute. - /// - public bool GenerateMetadataSourceChecksumAttributes { get; set; } = false; - - /// - /// Gets the CSharp language version currently used by the compilation. - /// - public LanguageVersion CSharpLanguageVersion { get; set; } = LanguageVersion.CSharp10; - - /// - /// Gets a flag that determines if localized component names should be supported.. - /// - public bool SupportLocalizedComponentNames { get; set; } = false; - - public bool Equals(RazorSourceGenerationOptions other) - { - return - RootNamespace == other.RootNamespace && - Configuration.Equals(other.Configuration) && - GenerateMetadataSourceChecksumAttributes == other.GenerateMetadataSourceChecksumAttributes && - CSharpLanguageVersion == other.CSharpLanguageVersion && - SupportLocalizedComponentNames == other.SupportLocalizedComponentNames; - } - - public override bool Equals(object obj) => obj is RazorSourceGenerationOptions other && Equals(other); - - public override int GetHashCode() => Configuration.GetHashCode(); - } -} diff --git a/src/RazorSdk/SourceGenerators/RazorSourceGenerator.Helpers.cs b/src/RazorSdk/SourceGenerators/RazorSourceGenerator.Helpers.cs deleted file mode 100644 index 105f6be00dff..000000000000 --- a/src/RazorSdk/SourceGenerators/RazorSourceGenerator.Helpers.cs +++ /dev/null @@ -1,122 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.Text; -using Microsoft.AspNetCore.Mvc.Razor.Extensions; -using Microsoft.AspNetCore.Razor.Language; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Razor; - -namespace Microsoft.NET.Sdk.Razor.SourceGenerators -{ - public partial class RazorSourceGenerator - { - private static string GetIdentifierFromPath(string filePath) - { - var builder = new StringBuilder(filePath.Length); - - for (var i = 0; i < filePath.Length; i++) - { - switch (filePath[i]) - { - case ':' or '\\' or '/': - case char ch when !char.IsLetterOrDigit(ch): - builder.Append('_'); - break; - default: - builder.Append(filePath[i]); - break; - } - } - - return builder.ToString(); - } - - private static RazorProjectEngine GetDeclarationProjectEngine( - SourceGeneratorProjectItem item, - IEnumerable imports, - RazorSourceGenerationOptions razorSourceGeneratorOptions) - { - var fileSystem = new VirtualRazorProjectFileSystem(); - fileSystem.Add(item); - foreach (var import in imports) - { - fileSystem.Add(import); - } - - var discoveryProjectEngine = RazorProjectEngine.Create(razorSourceGeneratorOptions.Configuration, fileSystem, b => - { - b.Features.Add(new DefaultTypeNameFeature()); - b.Features.Add(new ConfigureRazorCodeGenerationOptions(options => - { - options.SuppressPrimaryMethodBody = true; - options.SuppressChecksum = true; - options.SupportLocalizedComponentNames = razorSourceGeneratorOptions.SupportLocalizedComponentNames; - })); - - b.SetRootNamespace(razorSourceGeneratorOptions.RootNamespace); - - CompilerFeatures.Register(b); - RazorExtensions.Register(b); - - b.SetCSharpLanguageVersion(razorSourceGeneratorOptions.CSharpLanguageVersion); - }); - - return discoveryProjectEngine; - } - - private static RazorProjectEngine GetDiscoveryProjectEngine( - IReadOnlyList references, - StaticCompilationTagHelperFeature tagHelperFeature) - { - var discoveryProjectEngine = RazorProjectEngine.Create(RazorConfiguration.Default, new VirtualRazorProjectFileSystem(), b => - { - b.Features.Add(new DefaultMetadataReferenceFeature { References = references }); - b.Features.Add(tagHelperFeature); - b.Features.Add(new DefaultTagHelperDescriptorProvider()); - - CompilerFeatures.Register(b); - RazorExtensions.Register(b); - }); - - return discoveryProjectEngine; - } - - private static RazorProjectEngine GetGenerationProjectEngine( - IReadOnlyList tagHelpers, - SourceGeneratorProjectItem item, - IEnumerable imports, - RazorSourceGenerationOptions razorSourceGeneratorOptions) - { - var fileSystem = new VirtualRazorProjectFileSystem(); - fileSystem.Add(item); - foreach (var import in imports) - { - fileSystem.Add(import); - } - - var projectEngine = RazorProjectEngine.Create(razorSourceGeneratorOptions.Configuration, fileSystem, b => - { - b.Features.Add(new DefaultTypeNameFeature()); - b.SetRootNamespace(razorSourceGeneratorOptions.RootNamespace); - - b.Features.Add(new ConfigureRazorCodeGenerationOptions(options => - { - options.SuppressMetadataSourceChecksumAttributes = !razorSourceGeneratorOptions.GenerateMetadataSourceChecksumAttributes; - options.SupportLocalizedComponentNames = razorSourceGeneratorOptions.SupportLocalizedComponentNames; - })); - - b.Features.Add(new StaticTagHelperFeature { TagHelpers = tagHelpers }); - b.Features.Add(new DefaultTagHelperDescriptorProvider()); - - CompilerFeatures.Register(b); - RazorExtensions.Register(b); - - b.SetCSharpLanguageVersion(razorSourceGeneratorOptions.CSharpLanguageVersion); - }); - - return projectEngine; - } - } -} diff --git a/src/RazorSdk/SourceGenerators/RazorSourceGenerator.RazorProviders.cs b/src/RazorSdk/SourceGenerators/RazorSourceGenerator.RazorProviders.cs deleted file mode 100644 index 5385771d2289..000000000000 --- a/src/RazorSdk/SourceGenerators/RazorSourceGenerator.RazorProviders.cs +++ /dev/null @@ -1,97 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using System.Text; -using System.Threading; -using Microsoft.AspNetCore.Razor.Language; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; - -namespace Microsoft.NET.Sdk.Razor.SourceGenerators -{ - public partial class RazorSourceGenerator - { - /// - /// Gets a flag that determines if the source generator should no-op. - /// - /// This flag exists to support scenarios in VS where design-time and EnC builds need - /// to run without invoking the source generator to avoid duplicate types being produced. - /// The property is set by the SDK via an editor config. - /// - /// - private static bool GetSuppressionStatus(AnalyzerConfigOptionsProvider optionsProvider, CancellationToken _) - { - return optionsProvider.GlobalOptions.TryGetValue("build_property.SuppressRazorSourceGenerator", out var suppressRazorSourceGenerator) - && suppressRazorSourceGenerator == "true"; - } - - private static (RazorSourceGenerationOptions?, Diagnostic?) ComputeRazorSourceGeneratorOptions((AnalyzerConfigOptionsProvider, ParseOptions) pair, CancellationToken ct) - { - Log.ComputeRazorSourceGeneratorOptions(); - - var (options, parseOptions) = pair; - var globalOptions = options.GlobalOptions; - - globalOptions.TryGetValue("build_property.RazorConfiguration", out var configurationName); - globalOptions.TryGetValue("build_property.RootNamespace", out var rootNamespace); - globalOptions.TryGetValue("build_property.SupportLocalizedComponentNames", out var supportLocalizedComponentNames); - globalOptions.TryGetValue("build_property.GenerateRazorMetadataSourceChecksumAttributes", out var generateMetadataSourceChecksumAttributes); - - var razorLanguageVersion = RazorLanguageVersion.Latest; - Diagnostic? diagnostic = null; - if (!globalOptions.TryGetValue("build_property.RazorLangVersion", out var razorLanguageVersionString) || - !RazorLanguageVersion.TryParse(razorLanguageVersionString, out razorLanguageVersion)) - { - diagnostic = Diagnostic.Create( - RazorDiagnostics.InvalidRazorLangVersionDescriptor, - Location.None, - razorLanguageVersionString); - } - - var razorConfiguration = RazorConfiguration.Create(razorLanguageVersion, configurationName ?? "default", System.Linq.Enumerable.Empty(), true); - - var razorSourceGenerationOptions = new RazorSourceGenerationOptions() - { - Configuration = razorConfiguration, - GenerateMetadataSourceChecksumAttributes = generateMetadataSourceChecksumAttributes == "true", - RootNamespace = rootNamespace ?? "ASP", - SupportLocalizedComponentNames = supportLocalizedComponentNames == "true", - CSharpLanguageVersion = ((CSharpParseOptions)parseOptions).LanguageVersion, - }; - - return (razorSourceGenerationOptions, diagnostic); - } - - private static (SourceGeneratorProjectItem?, Diagnostic?) ComputeProjectItems((AdditionalText, AnalyzerConfigOptionsProvider) pair, CancellationToken ct) - { - var (additionalText, globalOptions) = pair; - var options = globalOptions.GetOptions(additionalText); - - if (!options.TryGetValue("build_metadata.AdditionalFiles.TargetPath", out var encodedRelativePath)) - { - var diagnostic = Diagnostic.Create( - RazorDiagnostics.TargetPathNotProvided, - Location.None, - additionalText.Path); - return (null, diagnostic); - } - - options.TryGetValue("build_metadata.AdditionalFiles.CssScope", out var cssScope); - var relativePath = Encoding.UTF8.GetString(Convert.FromBase64String(encodedRelativePath)); - - var projectItem = new SourceGeneratorProjectItem( - basePath: "/", - filePath: '/' + relativePath - .Replace(Path.DirectorySeparatorChar, '/') - .Replace("//", "/"), - relativePhysicalPath: relativePath, - fileKind: additionalText.Path.EndsWith(".razor") ? FileKinds.Component : FileKinds.Legacy, - additionalText: additionalText, - cssScope: cssScope); - return (projectItem, null); - } - } -} diff --git a/src/RazorSdk/SourceGenerators/RazorSourceGenerator.TagHelpers.cs b/src/RazorSdk/SourceGenerators/RazorSourceGenerator.TagHelpers.cs deleted file mode 100644 index 845b4136471e..000000000000 --- a/src/RazorSdk/SourceGenerators/RazorSourceGenerator.TagHelpers.cs +++ /dev/null @@ -1,37 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using Microsoft.AspNetCore.Razor.Language; -using Microsoft.CodeAnalysis; - -namespace Microsoft.NET.Sdk.Razor.SourceGenerators -{ - public partial class RazorSourceGenerator - { - private IReadOnlyList GetTagHelpers(IEnumerable references, StaticCompilationTagHelperFeature tagHelperFeature, Compilation compilation) - { - List descriptors = new(); - tagHelperFeature.Compilation = compilation; - foreach (var reference in references) - { - if (compilation.GetAssemblyOrModuleSymbol(reference) is IAssemblySymbol assembly) - { - tagHelperFeature.TargetAssembly = assembly; - descriptors.AddRange(tagHelperFeature.GetDescriptors()); - } - } - return descriptors; - } - - private static IReadOnlyList GetTagHelpersFromCompilation(Compilation compilation, StaticCompilationTagHelperFeature tagHelperFeature, SyntaxTree syntaxTrees) - { - var compilationWithDeclarations = compilation.AddSyntaxTrees(syntaxTrees); - - tagHelperFeature.Compilation = compilationWithDeclarations; - tagHelperFeature.TargetAssembly = compilationWithDeclarations.Assembly; - - return tagHelperFeature.GetDescriptors(); - } - } -} diff --git a/src/RazorSdk/SourceGenerators/RazorSourceGenerator.cs b/src/RazorSdk/SourceGenerators/RazorSourceGenerator.cs deleted file mode 100644 index c77718e75733..000000000000 --- a/src/RazorSdk/SourceGenerators/RazorSourceGenerator.cs +++ /dev/null @@ -1,254 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.IO; -using System.Linq; -using Microsoft.AspNetCore.Razor.Language; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; - -namespace Microsoft.NET.Sdk.Razor.SourceGenerators -{ - [Generator] - public partial class RazorSourceGenerator : IIncrementalGenerator - { - private static RazorSourceGeneratorEventSource Log => RazorSourceGeneratorEventSource.Log; - - public void Initialize(IncrementalGeneratorInitializationContext context) - { - var analyzerConfigOptions = context.AnalyzerConfigOptionsProvider; - var parseOptions = context.ParseOptionsProvider; - var compilation = context.CompilationProvider; - - // determine if we should suppress this run and filter out all the additional files if so - var isGeneratorSuppressed = context.AnalyzerConfigOptionsProvider.Select(GetSuppressionStatus); - var additionalTexts = context.AdditionalTextsProvider - .Combine(isGeneratorSuppressed) - .Where(pair => !pair.Right) - .Select((pair, _) => pair.Left); - - var razorSourceGeneratorOptions = analyzerConfigOptions - .Combine(parseOptions) - .Select(ComputeRazorSourceGeneratorOptions) - .ReportDiagnostics(context); - - var sourceItems = additionalTexts - .Where(static (file) => file.Path.EndsWith(".razor", StringComparison.OrdinalIgnoreCase) || file.Path.EndsWith(".cshtml", StringComparison.OrdinalIgnoreCase)) - .Combine(analyzerConfigOptions) - .Select(ComputeProjectItems) - .ReportDiagnostics(context); - - var hasRazorFiles = sourceItems.Collect() - .Select(static (sourceItems, _) => sourceItems.Any()); - - var importFiles = sourceItems.Where(static file => - { - var path = file.FilePath; - if (path.EndsWith(".razor", StringComparison.OrdinalIgnoreCase)) - { - var fileName = Path.GetFileNameWithoutExtension(path); - return string.Equals(fileName, "_Imports", StringComparison.OrdinalIgnoreCase); - } - else if (path.EndsWith(".cshtml", StringComparison.OrdinalIgnoreCase)) - { - var fileName = Path.GetFileNameWithoutExtension(path); - return string.Equals(fileName, "_ViewImports", StringComparison.OrdinalIgnoreCase); - } - - return false; - }); - - var componentFiles = sourceItems.Where(static file => file.FilePath.EndsWith(".razor", StringComparison.OrdinalIgnoreCase)); - - var generatedDeclarationCode = componentFiles - .Combine(importFiles.Collect()) - .Combine(razorSourceGeneratorOptions) - .Select(static (pair, _) => - { - - var ((sourceItem, importFiles), razorSourceGeneratorOptions) = pair; - RazorSourceGeneratorEventSource.Log.GenerateDeclarationCodeStart(sourceItem.FilePath); - - var projectEngine = GetDeclarationProjectEngine(sourceItem, importFiles, razorSourceGeneratorOptions); - - var codeGen = projectEngine.Process(sourceItem); - - var result = codeGen.GetCSharpDocument().GeneratedCode; - - RazorSourceGeneratorEventSource.Log.GenerateDeclarationCodeStop(sourceItem.FilePath); - - return result; - }); - - var generatedDeclarationSyntaxTrees = generatedDeclarationCode - .Combine(parseOptions) - .Select(static (pair, _) => - { - var (generatedDeclarationCode, parseOptions) = pair; - return CSharpSyntaxTree.ParseText(generatedDeclarationCode, (CSharpParseOptions)parseOptions); - }); - - var tagHelpersFromCompilation = compilation - .Combine(generatedDeclarationSyntaxTrees.Collect()) - .Combine(razorSourceGeneratorOptions) - .Select(static (pair, _) => - { - RazorSourceGeneratorEventSource.Log.DiscoverTagHelpersFromCompilationStart(); - - var ((compilation, generatedDeclarationSyntaxTrees), razorSourceGeneratorOptions) = pair; - - var tagHelperFeature = new StaticCompilationTagHelperFeature(); - var discoveryProjectEngine = GetDiscoveryProjectEngine(compilation.References.ToImmutableArray(), tagHelperFeature); - - var compilationWithDeclarations = compilation.AddSyntaxTrees(generatedDeclarationSyntaxTrees); - - tagHelperFeature.Compilation = compilationWithDeclarations; - tagHelperFeature.TargetAssembly = compilationWithDeclarations.Assembly; - - var result = (IList)tagHelperFeature.GetDescriptors(); - RazorSourceGeneratorEventSource.Log.DiscoverTagHelpersFromCompilationStop(); - return result; - }) - .WithLambdaComparer(static (a, b) => - { - if (a.Count != b.Count) - { - return false; - } - - for (var i = 0; i < a.Count; i++) - { - if (!a[i].Equals(b[i])) - { - return false; - } - } - - return true; - }, getHashCode: static a => a.Count); - - var tagHelpersFromReferences = compilation - .Combine(razorSourceGeneratorOptions) - .Combine(hasRazorFiles) - .WithLambdaComparer(static (a, b) => - { - var ((compilationA, razorSourceGeneratorOptionsA), hasRazorFilesA) = a; - var ((compilationB, razorSourceGeneratorOptionsB), hasRazorFilesB) = b; - - if (!compilationA.References.SequenceEqual(compilationB.References)) - { - return false; - } - - if (razorSourceGeneratorOptionsA != razorSourceGeneratorOptionsB) - { - return false; - } - - return hasRazorFilesA == hasRazorFilesB; - }, - static item => - { - // we'll use the number of references as a hashcode. - var ((compilationA, razorSourceGeneratorOptionsA), hasRazorFilesA) = item; - return compilationA.References.GetHashCode(); - }) - .Select(static (pair, _) => - { - RazorSourceGeneratorEventSource.Log.DiscoverTagHelpersFromReferencesStart(); - - var ((compilation, razorSourceGeneratorOptions), hasRazorFiles) = pair; - if (!hasRazorFiles) - { - // If there's no razor code in this app, don't do anything. - RazorSourceGeneratorEventSource.Log.DiscoverTagHelpersFromReferencesStop(); - return ImmutableArray.Empty; - } - - var tagHelperFeature = new StaticCompilationTagHelperFeature(); - var discoveryProjectEngine = GetDiscoveryProjectEngine(compilation.References.ToImmutableArray(), tagHelperFeature); - - List descriptors = new(); - tagHelperFeature.Compilation = compilation; - foreach (var reference in compilation.References) - { - if (compilation.GetAssemblyOrModuleSymbol(reference) is IAssemblySymbol assembly) - { - tagHelperFeature.TargetAssembly = assembly; - descriptors.AddRange(tagHelperFeature.GetDescriptors()); - } - } - - RazorSourceGeneratorEventSource.Log.DiscoverTagHelpersFromReferencesStop(); - return (ICollection)descriptors; - }); - - var allTagHelpers = tagHelpersFromCompilation - .Combine(tagHelpersFromReferences) - .Select(static (pair, _) => - { - var (tagHelpersFromCompilation, tagHelpersFromReferences) = pair; - var count = tagHelpersFromCompilation.Count + tagHelpersFromReferences.Count; - if (count == 0) - { - return Array.Empty(); - } - - var allTagHelpers = new TagHelperDescriptor[count]; - tagHelpersFromCompilation.CopyTo(allTagHelpers, 0); - tagHelpersFromReferences.CopyTo(allTagHelpers, tagHelpersFromCompilation.Count); - - return allTagHelpers; - }); - - var generatedOutput = sourceItems - .Combine(importFiles.Collect()) - .Combine(allTagHelpers) - .Combine(razorSourceGeneratorOptions) - .Select(static (pair, _) => - { - var (((sourceItem, imports), allTagHelpers), razorSourceGeneratorOptions) = pair; - - RazorSourceGeneratorEventSource.Log.RazorCodeGenerateStart(sourceItem.FilePath); - - // Add a generated suffix so tools, such as coverlet, consider the file to be generated - var hintName = GetIdentifierFromPath(sourceItem.RelativePhysicalPath) + ".g.cs"; - - var projectEngine = GetGenerationProjectEngine(allTagHelpers, sourceItem, imports, razorSourceGeneratorOptions); - - var codeDocument = projectEngine.Process(sourceItem); - var csharpDocument = codeDocument.GetCSharpDocument(); - - RazorSourceGeneratorEventSource.Log.RazorCodeGenerateStop(sourceItem.FilePath); - return (hintName, csharpDocument); - }) - .WithLambdaComparer(static (a, b) => - { - if (a.csharpDocument.Diagnostics.Count > 0 || b.csharpDocument.Diagnostics.Count > 0) - { - // if there are any diagnostics, treat the documents as unequal and force RegisterSourceOutput to be called uncached. - return false; - } - - return string.Equals(a.csharpDocument.GeneratedCode, b.csharpDocument.GeneratedCode, StringComparison.Ordinal); - }, static a => StringComparer.Ordinal.GetHashCode(a.csharpDocument)); - - context.RegisterSourceOutput(generatedOutput, static (context, pair) => - { - var (hintName, csharpDocument) = pair; - RazorSourceGeneratorEventSource.Log.AddSyntaxTrees(hintName); - for (var i = 0; i < csharpDocument.Diagnostics.Count; i++) - { - var razorDiagnostic = csharpDocument.Diagnostics[i]; - var csharpDiagnostic = razorDiagnostic.AsDiagnostic(); - context.ReportDiagnostic(csharpDiagnostic); - } - - context.AddSource(hintName, csharpDocument.GeneratedCode); - }); - } - } -} diff --git a/src/RazorSdk/SourceGenerators/RazorSourceGenerator.razorencconfig b/src/RazorSdk/SourceGenerators/RazorSourceGenerator.razorencconfig deleted file mode 100644 index d202155f918f..000000000000 --- a/src/RazorSdk/SourceGenerators/RazorSourceGenerator.razorencconfig +++ /dev/null @@ -1,2 +0,0 @@ -is_global = true -build_property.SuppressRazorSourceGenerator = true \ No newline at end of file diff --git a/src/RazorSdk/SourceGenerators/RazorSourceGeneratorEventSource.cs b/src/RazorSdk/SourceGenerators/RazorSourceGeneratorEventSource.cs deleted file mode 100644 index 758d0069b8b1..000000000000 --- a/src/RazorSdk/SourceGenerators/RazorSourceGeneratorEventSource.cs +++ /dev/null @@ -1,63 +0,0 @@ -// Copyright (c) .NET Foundation and contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Diagnostics.Tracing; - -namespace Microsoft.NET.Sdk.Razor.SourceGenerators -{ - [EventSource(Name = "Microsoft-DotNet-SDK-Razor-SourceGenerator")] - internal sealed class RazorSourceGeneratorEventSource : EventSource - { - public static readonly RazorSourceGeneratorEventSource Log = new(); - - private RazorSourceGeneratorEventSource() { } - - private const int ComputeRazorSourceGeneratorOptionsId = 1; - [Event(ComputeRazorSourceGeneratorOptionsId, Level = EventLevel.Informational)] - public void ComputeRazorSourceGeneratorOptions() => WriteEvent(ComputeRazorSourceGeneratorOptionsId); - - private const int GenerateDeclarationCodeStartId = 2; - [Event(GenerateDeclarationCodeStartId, Level = EventLevel.Informational)] - public void GenerateDeclarationCodeStart(string filePath) => WriteEvent(GenerateDeclarationCodeStartId, filePath); - - private const int GenerateDeclarationCodeStopId = 4; - [Event(GenerateDeclarationCodeStopId, Level = EventLevel.Informational)] - public void GenerateDeclarationCodeStop(string filePath) => WriteEvent(GenerateDeclarationCodeStopId, filePath); - - private const int DiscoverTagHelpersFromCompilationStartId = 6; - [Event(DiscoverTagHelpersFromCompilationStartId, Level = EventLevel.Informational)] - public void DiscoverTagHelpersFromCompilationStart() => WriteEvent(DiscoverTagHelpersFromCompilationStartId); - - private const int DiscoverTagHelpersFromCompilationStopId = 7; - [Event(DiscoverTagHelpersFromCompilationStopId, Level = EventLevel.Informational)] - public void DiscoverTagHelpersFromCompilationStop() => WriteEvent(DiscoverTagHelpersFromCompilationStopId); - - private const int DiscoverTagHelpersFromReferencesStartId = 8; - [Event(DiscoverTagHelpersFromReferencesStartId, Level = EventLevel.Informational)] - public void DiscoverTagHelpersFromReferencesStart() => WriteEvent(DiscoverTagHelpersFromReferencesStartId); - - private const int DiscoverTagHelpersFromReferencesStopId = 9; - [Event(DiscoverTagHelpersFromReferencesStopId, Level = EventLevel.Informational)] - public void DiscoverTagHelpersFromReferencesStop() => WriteEvent(DiscoverTagHelpersFromReferencesStopId); - - private const int RazorCodeGenerateStartId = 10; - [Event(RazorCodeGenerateStartId, Level = EventLevel.Informational)] - public void RazorCodeGenerateStart(string file) => WriteEvent(RazorCodeGenerateStartId, file); - - private const int RazorCodeGenerateStopId = 11; - [Event(RazorCodeGenerateStopId, Level = EventLevel.Informational)] - public void RazorCodeGenerateStop(string file) => WriteEvent(RazorCodeGenerateStopId, file); - - private const int AddSyntaxTreesId = 12; - [Event(AddSyntaxTreesId, Level = EventLevel.Informational)] - public void AddSyntaxTrees(string file) => WriteEvent(AddSyntaxTreesId, file); - - private const int GenerateDeclarationSyntaxTreeStartId = 13; - [Event(GenerateDeclarationSyntaxTreeStartId, Level = EventLevel.Informational)] - public void GenerateDeclarationSyntaxTreeStart() => WriteEvent(GenerateDeclarationSyntaxTreeStartId); - - private const int GenerateDeclarationSyntaxTreeStopId = 14; - [Event(GenerateDeclarationSyntaxTreeStopId, Level = EventLevel.Informational)] - public void GenerateDeclarationSyntaxTreeStop() => WriteEvent(GenerateDeclarationSyntaxTreeStopId); - } -} diff --git a/src/RazorSdk/SourceGenerators/SourceGeneratorProjectItem.cs b/src/RazorSdk/SourceGenerators/SourceGeneratorProjectItem.cs deleted file mode 100644 index 9cd3bdf7cef1..000000000000 --- a/src/RazorSdk/SourceGenerators/SourceGeneratorProjectItem.cs +++ /dev/null @@ -1,56 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.IO; -using Microsoft.AspNetCore.Razor.Language; -using Microsoft.CodeAnalysis; - -namespace Microsoft.NET.Sdk.Razor.SourceGenerators -{ - internal class SourceGeneratorProjectItem : RazorProjectItem, IEquatable - { - private readonly string _fileKind; - - public SourceGeneratorProjectItem(string basePath, string filePath, string relativePhysicalPath, string fileKind, AdditionalText additionalText, string? cssScope) - { - BasePath = basePath; - FilePath = filePath; - RelativePhysicalPath = relativePhysicalPath; - _fileKind = fileKind; - AdditionalText = additionalText; - CssScope = cssScope; - var text = AdditionalText.GetText(); - if (text is not null) - { - RazorSourceDocument = new SourceTextRazorSourceDocument(AdditionalText.Path, relativePhysicalPath, text); - } - } - - public AdditionalText AdditionalText { get; } - - public override string BasePath { get; } - - public override string FilePath { get; } - - public override bool Exists => true; - - public override string PhysicalPath => AdditionalText.Path; - - public override string RelativePhysicalPath { get; } - - public override string FileKind => _fileKind ?? base.FileKind; - - public override string? CssScope { get; } - - public override Stream Read() - => throw new NotSupportedException("This API should not be invoked. We should instead be relying on " + - "the RazorSourceDocument associated with this item instead."); - - public bool Equals(SourceGeneratorProjectItem other) => AdditionalText == other.AdditionalText; - - public override int GetHashCode() => AdditionalText.GetHashCode(); - - public override bool Equals(object obj) => obj is SourceGeneratorProjectItem projectItem && Equals(projectItem); - } -} diff --git a/src/RazorSdk/SourceGenerators/SourceTextRazorSourceDocument.cs b/src/RazorSdk/SourceGenerators/SourceTextRazorSourceDocument.cs deleted file mode 100644 index 8dc54cc729c4..000000000000 --- a/src/RazorSdk/SourceGenerators/SourceTextRazorSourceDocument.cs +++ /dev/null @@ -1,44 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Linq; -using System.Text; -using Microsoft.AspNetCore.Razor.Language; -using Microsoft.CodeAnalysis.Text; - -namespace Microsoft.NET.Sdk.Razor.SourceGenerators -{ - internal class SourceTextRazorSourceDocument : RazorSourceDocument - { - private readonly SourceText _sourceText; - - public SourceTextRazorSourceDocument(string filePath, string relativePath, SourceText sourceText) - { - FilePath = filePath; - RelativePath = relativePath; - _sourceText = sourceText; - Lines = new SourceTextSourceLineCollection(filePath, sourceText.Lines); - } - - public override char this[int position] => _sourceText[position]; - - public override Encoding? Encoding => _sourceText.Encoding; - - public override string FilePath { get; } - - public override int Length => _sourceText.Length; - - public override string RelativePath { get; } - - public override RazorSourceLineCollection Lines { get; } - - public override void CopyTo(int sourceIndex, char[] destination, int destinationIndex, int count) - { - _sourceText.CopyTo(sourceIndex, destination, destinationIndex, count); - } - - public override byte[] GetChecksum() => _sourceText.GetChecksum().ToArray(); - - public override string GetChecksumAlgorithm() => _sourceText.ChecksumAlgorithm.ToString().ToUpperInvariant(); - } -} diff --git a/src/RazorSdk/SourceGenerators/SourceTextSourceLineCollection.cs b/src/RazorSdk/SourceGenerators/SourceTextSourceLineCollection.cs deleted file mode 100644 index d6a4649a6229..000000000000 --- a/src/RazorSdk/SourceGenerators/SourceTextSourceLineCollection.cs +++ /dev/null @@ -1,36 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Linq; -using System.Text; -using Microsoft.AspNetCore.Razor.Language; -using Microsoft.CodeAnalysis.Text; - -namespace Microsoft.NET.Sdk.Razor.SourceGenerators -{ - public class SourceTextSourceLineCollection : RazorSourceLineCollection - { - private readonly string _filePath; - private readonly TextLineCollection _textLines; - - public SourceTextSourceLineCollection(string filePath, TextLineCollection textLines) - { - _filePath = filePath; - _textLines = textLines; - } - - public override int Count => _textLines.Count; - - public override int GetLineLength(int index) - { - var line = _textLines[index]; - return line.EndIncludingLineBreak - line.Start; - } - - internal override SourceLocation GetLocation(int position) - { - var line = _textLines.GetLineFromPosition(position); - return new SourceLocation(_filePath, position, line.LineNumber, position - line.Start); - } - } -} diff --git a/src/RazorSdk/SourceGenerators/StaticCompilationTagHelperFeature.cs b/src/RazorSdk/SourceGenerators/StaticCompilationTagHelperFeature.cs deleted file mode 100644 index ef3be7d49b2c..000000000000 --- a/src/RazorSdk/SourceGenerators/StaticCompilationTagHelperFeature.cs +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using System.Linq; -using Microsoft.AspNetCore.Razor.Language; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Razor; - -namespace Microsoft.NET.Sdk.Razor.SourceGenerators -{ - internal sealed class StaticCompilationTagHelperFeature : RazorEngineFeatureBase, ITagHelperFeature - { - private static readonly List EmptyList = new(); - - private ITagHelperDescriptorProvider[]? _providers; - - public List GetDescriptors() - { - if (Compilation is null) - { - return EmptyList; - } - - var results = new List(); - var context = TagHelperDescriptorProviderContext.Create(results); - context.SetCompilation(Compilation); - context.Items.SetTargetAssembly(TargetAssembly!); - - for (var i = 0; i < _providers?.Length; i++) - { - _providers[i].Execute(context); - } - - return results; - } - - IReadOnlyList ITagHelperFeature.GetDescriptors() => GetDescriptors(); - - public Compilation? Compilation { get; set; } - - public IAssemblySymbol? TargetAssembly { get; set; } - - protected override void OnInitialized() - { - _providers = Engine.Features.OfType().OrderBy(f => f.Order).ToArray(); - } - } -} diff --git a/src/RazorSdk/SourceGenerators/StaticTagHelperFeature.cs b/src/RazorSdk/SourceGenerators/StaticTagHelperFeature.cs deleted file mode 100644 index 1d5d5a366991..000000000000 --- a/src/RazorSdk/SourceGenerators/StaticTagHelperFeature.cs +++ /dev/null @@ -1,25 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Collections.Generic; -using Microsoft.AspNetCore.Razor.Language; - -namespace Microsoft.NET.Sdk.Razor.SourceGenerators -{ - internal sealed class StaticTagHelperFeature : RazorEngineFeatureBase, ITagHelperFeature - { - public IReadOnlyList TagHelpers { get; set; } - - public IReadOnlyList GetDescriptors() => TagHelpers; - - public StaticTagHelperFeature() - { - TagHelpers = new List(); - } - - public StaticTagHelperFeature(IEnumerable tagHelpers) - { - TagHelpers = new List(tagHelpers); - } - } -} diff --git a/src/RazorSdk/Targets/Microsoft.NET.Sdk.Razor.SourceGenerators.targets b/src/RazorSdk/Targets/Microsoft.NET.Sdk.Razor.SourceGenerators.targets index 41b30bc70c6a..49bd4ec41166 100644 --- a/src/RazorSdk/Targets/Microsoft.NET.Sdk.Razor.SourceGenerators.targets +++ b/src/RazorSdk/Targets/Microsoft.NET.Sdk.Razor.SourceGenerators.targets @@ -30,8 +30,7 @@ Copyright (c) .NET Foundation. All rights reserved. - <_RazorAnalyzer Include="$(_RazorSdkSourceGeneratorDirectoryRoot)Microsoft.AspNetCore.Razor.SourceGenerator.Tooling.Internal.dll" /> - <_RazorAnalyzer Include="$(_RazorSdkSourceGeneratorDirectoryRoot)Microsoft.NET.Sdk.Razor.SourceGenerators.dll" /> + <_RazorAnalyzer Include="$(_RazorSdkSourceGeneratorDirectoryRoot)*.dll" /> diff --git a/src/Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests.csproj b/src/Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests.csproj deleted file mode 100644 index eb3227d4a08c..000000000000 --- a/src/Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests.csproj +++ /dev/null @@ -1,33 +0,0 @@ - - - - false - - - - $(SdkTargetFramework) - Exe - testSdkRSG - true - - - - - - - - - - - - - - - - - - - - - - diff --git a/src/Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/RazorDiagnosticTest.cs b/src/Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/RazorDiagnosticTest.cs deleted file mode 100644 index 9714d774e3b1..000000000000 --- a/src/Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/RazorDiagnosticTest.cs +++ /dev/null @@ -1,52 +0,0 @@ -// Copyright (c) .NET Foundation and contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using Microsoft.AspNetCore.Razor.Language; -using Microsoft.CodeAnalysis; -using Xunit; - -namespace Microsoft.NET.Sdk.Razor.SourceGenerators -{ - public class RazorDiagnosticTest - { - [Fact] - public void AsDiagnostic_WithUndefinedSpanWorks() - { - // Arrange - var diagnostics = RazorDiagnostic.Create(new RazorDiagnosticDescriptor("RZC1001", () => "Some message", RazorDiagnosticSeverity.Error), SourceSpan.Undefined); - - // Act - var csharpDiagnostic = diagnostics.AsDiagnostic(); - - // Assert - Assert.Equal("Some message", csharpDiagnostic.GetMessage()); - Assert.Equal("RZC1001", csharpDiagnostic.Descriptor.Id); - Assert.Equal(DiagnosticSeverity.Error, csharpDiagnostic.Severity); - Assert.Equal(Location.None, csharpDiagnostic.Location); - } - - [Fact] - public void AsDiagnostic_WithSpanWorks() - { - // Arrange - var span = new SourceSpan("some-file", 100, 1, 5, 10); - var diagnostics = RazorDiagnostic.Create(new RazorDiagnosticDescriptor("RZC1001", () => "Some message", RazorDiagnosticSeverity.Error), span); - - // Act - var csharpDiagnostic = diagnostics.AsDiagnostic(); - - // Assert - Assert.Equal("Some message", csharpDiagnostic.GetMessage()); - Assert.Equal("RZC1001", csharpDiagnostic.Descriptor.Id); - Assert.Equal(DiagnosticSeverity.Error, csharpDiagnostic.Severity); - Assert.Equal(100, csharpDiagnostic.Location.SourceSpan.Start); - - var lineSpan = csharpDiagnostic.Location.GetLineSpan(); - Assert.Equal("some-file", lineSpan.Path); - Assert.Equal(1, lineSpan.StartLinePosition.Line); - Assert.Equal(5, lineSpan.StartLinePosition.Character); - Assert.Equal(1, lineSpan.EndLinePosition.Line); - Assert.Equal(15, lineSpan.EndLinePosition.Character); - } - } -} diff --git a/src/Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/RazorEventListener.cs b/src/Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/RazorEventListener.cs deleted file mode 100644 index c1e9b8f7889c..000000000000 --- a/src/Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/RazorEventListener.cs +++ /dev/null @@ -1,43 +0,0 @@ -// Copyright (c) .NET Foundation and contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -using System.Collections.Concurrent; -using System.Diagnostics.Tracing; -using System.Linq; - -namespace Microsoft.NET.Sdk.Razor.SourceGenerators -{ - public class RazorEventListener : EventListener - { - protected override void OnEventSourceCreated(EventSource source) - { - if (source.Name == "Microsoft-DotNet-SDK-Razor-SourceGenerator") - { - EnableEvents(source, EventLevel.Informational); - } - } - - public ConcurrentQueue Events { get; } = new(); - - protected override void OnEventWritten(EventWrittenEventArgs eventData) - { - var @event = new RazorEvent - { - EventId = eventData.EventId, - EventName = eventData.EventName, - Payload = eventData.Payload.ToArray(), - }; - - Events.Enqueue(@event); - } - - public sealed class RazorEvent - { - public int EventId { get; init; } - - public string EventName { get; init; } - - public object[] Payload { get; init; } - } - } -} diff --git a/src/Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/RazorSourceGeneratorTests.cs b/src/Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/RazorSourceGeneratorTests.cs deleted file mode 100644 index 4e3ca4db2315..000000000000 --- a/src/Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/RazorSourceGeneratorTests.cs +++ /dev/null @@ -1,2599 +0,0 @@ -// Copyright (c) .NET Foundation and contributors. All rights reserved. -// Licensed under the MIT license. See LICENSE file in the project root for full license information. - -#nullable enable - -using System; -using System.Collections.Generic; -using System.Collections.Immutable; -using System.Diagnostics.CodeAnalysis; -using System.IO; -using System.Linq; -using System.Text; -using System.Threading; -using System.Threading.Tasks; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.CSharp; -using Microsoft.CodeAnalysis.Diagnostics; -using Microsoft.CodeAnalysis.Text; -using Microsoft.Extensions.DependencyModel; -using Microsoft.Extensions.DependencyModel.Resolution; -using Xunit; -using Xunit.Sdk; - -namespace Microsoft.NET.Sdk.Razor.SourceGenerators -{ - public class RazorSourceGeneratorTests - { - private static readonly Project _baseProject = CreateBaseProject(); - - [Fact] - public async Task SourceGenerator_RazorFiles_Works() - { - // Arrange - var project = CreateTestProject(new() - { - ["Pages/Index.razor"] = "

Hello world

", - }); - - var compilation = await project.GetCompilationAsync(); - var driver = await GetDriverAsync(project); - - var result = RunGenerator(compilation!, ref driver) - .VerifyPageOutput( -@"#pragma checksum ""Pages/Index.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""6b5db227a6aa2228c777b0771108b184b1fc5df3"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; - public partial class Index : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Hello world

""); - } - #pragma warning restore 1998 - } -} -#pragma warning restore 1591 -"); - - Assert.Empty(result.Diagnostics); - Assert.Single(result.GeneratedSources); - } - - internal class InMemoryAdditionalText : AdditionalText - { - private readonly SourceText _content; - - public InMemoryAdditionalText(string path, string content) - { - Path = path; - _content = SourceText.From(content, Encoding.UTF8); - } - - public override string Path { get; } - - public override SourceText GetText(CancellationToken cancellationToken = default) => _content; - } - - [Fact] - public async Task SourceGeneratorEvents_RazorFiles_Works() - { - // Arrange - using var eventListener = new RazorEventListener(); - var project = CreateTestProject(new() - { - ["Pages/Index.razor"] = "

Hello world

", - ["Pages/Counter.razor"] = "

Counter

", - }); - var compilation = await project.GetCompilationAsync(); - var driver = await GetDriverAsync(project); - - var result = RunGenerator(compilation!, ref driver) - .VerifyPageOutput( -@"#pragma checksum ""Pages/Index.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""6b5db227a6aa2228c777b0771108b184b1fc5df3"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; - public partial class Index : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Hello world

""); - } - #pragma warning restore 1998 - } -} -#pragma warning restore 1591 -", -@"#pragma checksum ""Pages/Counter.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""0de17e526cd536d59072aa0e924e99111b16b97a"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; - public partial class Counter : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Counter

""); - } - #pragma warning restore 1998 - } -} -#pragma warning restore 1591 -"); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - Assert.Collection(eventListener.Events, - e => Assert.Equal("ComputeRazorSourceGeneratorOptions", e.EventName), - e => - { - Assert.Equal("GenerateDeclarationCodeStart", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Index.razor", file); - }, - e => - { - Assert.Equal("GenerateDeclarationCodeStop", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Index.razor", file); - }, - e => - { - Assert.Equal("GenerateDeclarationCodeStart", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Counter.razor", file); - }, - e => - { - Assert.Equal("GenerateDeclarationCodeStop", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Counter.razor", file); - }, - e => Assert.Equal("DiscoverTagHelpersFromCompilationStart", e.EventName), - e => Assert.Equal("DiscoverTagHelpersFromCompilationStop", e.EventName), - e => Assert.Equal("DiscoverTagHelpersFromReferencesStart", e.EventName), - e => Assert.Equal("DiscoverTagHelpersFromReferencesStop", e.EventName), - e => - { - Assert.Equal("RazorCodeGenerateStart", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Index.razor", file); - }, - e => - { - Assert.Equal("RazorCodeGenerateStop", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Index.razor", file); - }, - e => - { - Assert.Equal("RazorCodeGenerateStart", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Counter.razor", file); - }, - e => - { - Assert.Equal("RazorCodeGenerateStop", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Counter.razor", file); - }, - e => - { - Assert.Equal("AddSyntaxTrees", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("Pages_Index_razor.g.cs", file); - }, - e => - { - Assert.Equal("AddSyntaxTrees", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("Pages_Counter_razor.g.cs", file); - }); - } - - [Fact] - public async Task IncrementalCompilation_DoesNotReexecuteSteps_WhenRazorFilesAreUnchanged() - { - // Arrange - using var eventListener = new RazorEventListener(); - var project = CreateTestProject(new() - { - ["Pages/Index.razor"] = "

Hello world

", - ["Pages/Counter.razor"] = "

Counter

", - }); - var compilation = await project.GetCompilationAsync(); - var driver = await GetDriverAsync(project); - - var result = RunGenerator(compilation!, ref driver) - .VerifyPageOutput(@" -#pragma checksum ""Pages/Index.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""6b5db227a6aa2228c777b0771108b184b1fc5df3"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; - public partial class Index : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Hello world

""); - } - #pragma warning restore 1998 - } -} -#pragma warning restore 1591", -@" -#pragma checksum ""Pages/Counter.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""0de17e526cd536d59072aa0e924e99111b16b97a"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; - public partial class Counter : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Counter

""); - } - #pragma warning restore 1998 - } -} -#pragma warning restore 1591"); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - eventListener.Events.Clear(); - - result = RunGenerator(compilation!, ref driver) - .VerifyOutputsMatch(result); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - Assert.Empty(eventListener.Events); - } - - [Fact] - public async Task IncrementalCompilation_WhenRazorFileMarkupChanges() - { - // Arrange - using var eventListener = new RazorEventListener(); - var project = CreateTestProject(new() - { - ["Pages/Index.razor"] = "

Hello world

", - ["Pages/Counter.razor"] = "

Counter

", - }); - var compilation = await project.GetCompilationAsync(); - var (driver, additionalTexts) = await GetDriverWithAdditionalTextAsync(project); - - var result = RunGenerator(compilation!, ref driver) - .VerifyPageOutput( -@"#pragma checksum ""Pages/Index.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""6b5db227a6aa2228c777b0771108b184b1fc5df3"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; - public partial class Index : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Hello world

""); - } - #pragma warning restore 1998 - } -} -#pragma warning restore 1591 -", -@"#pragma checksum ""Pages/Counter.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""0de17e526cd536d59072aa0e924e99111b16b97a"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; - public partial class Counter : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Counter

""); - } - #pragma warning restore 1998 - } -} -#pragma warning restore 1591 -"); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - eventListener.Events.Clear(); - - result = RunGenerator(compilation!, ref driver) - .VerifyOutputsMatch(result); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - Assert.Empty(eventListener.Events); - - var updatedText = new TestAdditionalText("Pages/Counter.razor", SourceText.From("

Counter

", Encoding.UTF8)); - driver = driver.ReplaceAdditionalText(additionalTexts.First(f => f.Path == updatedText.Path), updatedText); - - result = RunGenerator(compilation!, ref driver) - .VerifyOutputsMatch(result, (1, -@"#pragma checksum ""Pages/Counter.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""e022c3eac864ad044e9b7d56f4c493ab4eab36da"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; - public partial class Counter : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Counter

""); - } - #pragma warning restore 1998 - } -} -#pragma warning restore 1591 -")); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - Assert.Collection(eventListener.Events, - e => - { - Assert.Equal("GenerateDeclarationCodeStart", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Counter.razor", file); - }, - e => - { - Assert.Equal("GenerateDeclarationCodeStop", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Counter.razor", file); - }, - e => - { - Assert.Equal("RazorCodeGenerateStart", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Counter.razor", file); - }, - e => - { - Assert.Equal("RazorCodeGenerateStop", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Counter.razor", file); - }, - e => - { - Assert.Equal("AddSyntaxTrees", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("Pages_Counter_razor.g.cs", file); - }); - } - - [Fact] - public async Task IncrementalCompilation_RazorFiles_WhenNewTypeIsAdded() - { - // Arrange - using var eventListener = new RazorEventListener(); - var project = CreateTestProject(new() - { - ["Pages/Index.razor"] = "

Hello world

", - ["Pages/Counter.razor"] = "

Counter

", - }); - var compilation = await project.GetCompilationAsync(); - var (driver, additionalTexts) = await GetDriverWithAdditionalTextAsync(project); - - var result = RunGenerator(compilation!, ref driver) - .VerifyPageOutput( -@"#pragma checksum ""Pages/Index.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""6b5db227a6aa2228c777b0771108b184b1fc5df3"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; - public partial class Index : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Hello world

""); - } - #pragma warning restore 1998 - } -} -#pragma warning restore 1591 -", -@"#pragma checksum ""Pages/Counter.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""0de17e526cd536d59072aa0e924e99111b16b97a"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; - public partial class Counter : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Counter

""); - } - #pragma warning restore 1998 - } -} -#pragma warning restore 1591 -"); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - eventListener.Events.Clear(); - - result = RunGenerator(compilation!, ref driver) - .VerifyOutputsMatch(result); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - project = project.AddDocument("Person.cs", SourceText.From(@" -public class Person -{ - public string Name { get; set; } -}", Encoding.UTF8)).Project; - compilation = await project.GetCompilationAsync(); - - result = RunGenerator(compilation!, ref driver) - .VerifyOutputsMatch(result); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - Assert.Collection(eventListener.Events, - e => Assert.Equal("DiscoverTagHelpersFromCompilationStart", e.EventName), - e => Assert.Equal("DiscoverTagHelpersFromCompilationStop", e.EventName)); - } - - [Fact] - public async Task IncrementalCompilation_RazorFiles_WhenCSharpTypeChanges() - { - // Arrange - using var eventListener = new RazorEventListener(); - var project = CreateTestProject(new() - { - ["Pages/Index.razor"] = "

Hello world

", - ["Pages/Counter.razor"] = "

Counter

", - }, - new() - { - ["Person.cs"] = @" -public class Person -{ - public string Name { get; set; } -}" - }); - var compilation = await project.GetCompilationAsync(); - var (driver, additionalTexts) = await GetDriverWithAdditionalTextAsync(project); - - var result = RunGenerator(compilation!, ref driver) - .VerifyPageOutput( -@"#pragma checksum ""Pages/Index.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""6b5db227a6aa2228c777b0771108b184b1fc5df3"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; - public partial class Index : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Hello world

""); - } - #pragma warning restore 1998 - } -} -#pragma warning restore 1591 -", -@"#pragma checksum ""Pages/Counter.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""0de17e526cd536d59072aa0e924e99111b16b97a"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; - public partial class Counter : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Counter

""); - } - #pragma warning restore 1998 - } -} -#pragma warning restore 1591 -"); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - eventListener.Events.Clear(); - - result = RunGenerator(compilation!, ref driver) - .VerifyOutputsMatch(result); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - project = project.Documents.First().WithText(SourceText.From(@" -public class Person -{ - public string Name { get; set; } - public int Age { get; set; } -}", Encoding.UTF8)).Project; - compilation = await project.GetCompilationAsync(); - - result = RunGenerator(compilation!, ref driver) - .VerifyOutputsMatch(result); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - Assert.Collection(eventListener.Events, - e => Assert.Equal("DiscoverTagHelpersFromCompilationStart", e.EventName), - e => Assert.Equal("DiscoverTagHelpersFromCompilationStop", e.EventName)); - } - - [Fact] - public async Task IncrementalCompilation_RazorFiles_WhenChildComponentsAreAdded() - { - // Arrange - using var eventListener = new RazorEventListener(); - var project = CreateTestProject(new() - { - ["Pages/Index.razor"] = "

Hello world

", - ["Pages/Counter.razor"] = "

Counter

", - }); - var compilation = await project.GetCompilationAsync(); - var (driver, additionalTexts) = await GetDriverWithAdditionalTextAsync(project); - - var result = RunGenerator(compilation!, ref driver) - .VerifyPageOutput( -@"#pragma checksum ""Pages/Index.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""6b5db227a6aa2228c777b0771108b184b1fc5df3"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; - public partial class Index : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Hello world

""); - } - #pragma warning restore 1998 - } -} -#pragma warning restore 1591 -", -@"#pragma checksum ""Pages/Counter.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""0de17e526cd536d59072aa0e924e99111b16b97a"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; - public partial class Counter : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Counter

""); - } - #pragma warning restore 1998 - } -} -#pragma warning restore 1591 -"); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - eventListener.Events.Clear(); - - result = RunGenerator(compilation!, ref driver) - .VerifyOutputsMatch(result); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - Assert.Empty(eventListener.Events); - - var updatedText = new TestAdditionalText("Pages/Counter.razor", SourceText.From(@" -

Counter

-

Current count: @count

- - -@code -{ - private int count; - - public void Click() => count++; -} - -", Encoding.UTF8)); - driver = driver.ReplaceAdditionalText(additionalTexts.First(f => f.Path == updatedText.Path), updatedText); - - result = RunGenerator(compilation!, ref driver) - .VerifyOutputsMatch(result, (1, -@"#pragma checksum ""Pages/Counter.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""1ea7ff43d3a2eecc5502dd3771378e334a8fb068"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; - public partial class Counter : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Counter

\r\n""); - __builder.OpenElement(1, ""h3""); - __builder.AddContent(2, ""Current count: ""); -#nullable restore -#line (3,21)-(3,26) 24 ""Pages/Counter.razor"" -__builder.AddContent(3, count); - -#line default -#line hidden -#nullable disable - __builder.CloseElement(); - __builder.AddMarkupContent(4, ""\r\n""); - __builder.AddMarkupContent(5, """"); - } - #pragma warning restore 1998 -#nullable restore -#line 7 ""Pages/Counter.razor"" - - private int count; - - public void Click() => count++; - -#line default -#line hidden -#nullable disable - } -} -#pragma warning restore 1591 -")); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - Assert.Collection(eventListener.Events, - e => - { - Assert.Equal("GenerateDeclarationCodeStart", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Counter.razor", file); - }, - e => - { - Assert.Equal("GenerateDeclarationCodeStop", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Counter.razor", file); - }, - e => Assert.Equal("DiscoverTagHelpersFromCompilationStart", e.EventName), - e => Assert.Equal("DiscoverTagHelpersFromCompilationStop", e.EventName), - e => - { - Assert.Equal("RazorCodeGenerateStart", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Counter.razor", file); - }, - e => - { - Assert.Equal("RazorCodeGenerateStop", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Counter.razor", file); - }, - e => - { - Assert.Equal("AddSyntaxTrees", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("Pages_Counter_razor.g.cs", file); - }); - } - - [Fact] - public async Task IncrementalCompilation_RazorFiles_WhenNewComponentParameterIsAdded() - { - // Arrange - using var eventListener = new RazorEventListener(); - var project = CreateTestProject(new() - { - ["Pages/Index.razor"] = "

Hello world

", - ["Pages/Counter.razor"] = "

Counter

", - }); - var compilation = await project.GetCompilationAsync(); - var (driver, additionalTexts) = await GetDriverWithAdditionalTextAsync(project); - - var result = RunGenerator(compilation!, ref driver) - .VerifyPageOutput( -@"#pragma checksum ""Pages/Index.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""6b5db227a6aa2228c777b0771108b184b1fc5df3"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; - public partial class Index : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Hello world

""); - } - #pragma warning restore 1998 - } -} -#pragma warning restore 1591 -", -@"#pragma checksum ""Pages/Counter.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""0de17e526cd536d59072aa0e924e99111b16b97a"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; - public partial class Counter : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Counter

""); - } - #pragma warning restore 1998 - } -} -#pragma warning restore 1591 -"); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - eventListener.Events.Clear(); - - result = RunGenerator(compilation!, ref driver) - .VerifyOutputsMatch(result); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - Assert.Empty(eventListener.Events); - - var updatedText = new TestAdditionalText("Pages/Counter.razor", SourceText.From(@" -

Counter

-

Current count: @count

- - -@code -{ - private int count; - - public void Click() => count++; - - [Parameter] public int IncrementAmount { get; set; } -} - -", Encoding.UTF8)); - driver = driver.ReplaceAdditionalText(additionalTexts.First(f => f.Path == updatedText.Path), updatedText); - - result = RunGenerator(compilation!, ref driver) - .VerifyOutputsMatch(result, (1, -@"#pragma checksum ""Pages/Counter.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""fb93b97dc0d4885250500697f41ffde70decc444"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; - public partial class Counter : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Counter

\r\n""); - __builder.OpenElement(1, ""h3""); - __builder.AddContent(2, ""Current count: ""); -#nullable restore -#line (3,21)-(3,26) 24 ""Pages/Counter.razor"" -__builder.AddContent(3, count); - -#line default -#line hidden -#nullable disable - __builder.CloseElement(); - __builder.AddMarkupContent(4, ""\r\n""); - __builder.AddMarkupContent(5, """"); - } - #pragma warning restore 1998 -#nullable restore -#line 7 ""Pages/Counter.razor"" - - private int count; - - public void Click() => count++; - - [Parameter] public int IncrementAmount { get; set; } - -#line default -#line hidden -#nullable disable - } -} -#pragma warning restore 1591 -")); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - Assert.Collection(eventListener.Events, - e => - { - Assert.Equal("GenerateDeclarationCodeStart", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Counter.razor", file); - }, - e => - { - Assert.Equal("GenerateDeclarationCodeStop", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Counter.razor", file); - }, - e => Assert.Equal("DiscoverTagHelpersFromCompilationStart", e.EventName), - e => Assert.Equal("DiscoverTagHelpersFromCompilationStop", e.EventName), - e => - { - Assert.Equal("RazorCodeGenerateStart", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Index.razor", file); - }, - e => - { - Assert.Equal("RazorCodeGenerateStop", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Index.razor", file); - }, - e => - { - Assert.Equal("RazorCodeGenerateStart", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Counter.razor", file); - }, - e => - { - Assert.Equal("RazorCodeGenerateStop", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Counter.razor", file); - }, - e => - { - Assert.Equal("AddSyntaxTrees", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("Pages_Counter_razor.g.cs", file); - }); - } - - [Fact] - public async Task IncrementalCompilation_RazorFiles_WhenProjectReferencesChange() - { - // Arrange - using var eventListener = new RazorEventListener(); - var project = CreateTestProject(new() - { - ["Pages/Index.razor"] = -@" -@using SurveyPromptRootNamspace; -

Hello world

- -", - ["Pages/Counter.razor"] = "

Counter

", - }); - var compilation = await project.GetCompilationAsync(); - var (driver, additionalTexts) = await GetDriverWithAdditionalTextAsync(project); - - var result = RunGenerator(compilation!, ref driver) - .VerifyPageOutput( -@"#pragma checksum ""Pages/Index.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""4745828f8a0ab77b58022ed5d1095a0242f2a7ee"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; -#nullable restore -#line 2 ""Pages/Index.razor"" -using SurveyPromptRootNamspace; - -#line default -#line hidden -#nullable disable - public partial class Index : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Hello world

\r\n""); - __builder.OpenElement(1, ""SurveyPrompt""); - __builder.CloseElement(); - } - #pragma warning restore 1998 - } -} -#pragma warning restore 1591 -", -@"#pragma checksum ""Pages/Counter.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""0de17e526cd536d59072aa0e924e99111b16b97a"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; - public partial class Counter : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Counter

""); - } - #pragma warning restore 1998 - } -} -#pragma warning restore 1591 -"); - - var diagnostic = Assert.Single(result.Diagnostics); - Assert.Equal("RZ10012", diagnostic.Id); - Assert.Equal(2, result.GeneratedSources.Length); - - eventListener.Events.Clear(); - - var surveyPromptAssembly = GetSurveyPromptMetadataReference(compilation!); - compilation = compilation!.AddReferences(surveyPromptAssembly); - - result = RunGenerator(compilation, ref driver) - .VerifyOutputsMatch(result, (0, -@"#pragma checksum ""Pages/Index.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""4745828f8a0ab77b58022ed5d1095a0242f2a7ee"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; -#nullable restore -#line 2 ""Pages/Index.razor"" -using SurveyPromptRootNamspace; - -#line default -#line hidden -#nullable disable - public partial class Index : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Hello world

\r\n""); - __builder.OpenComponent(1); - __builder.CloseComponent(); - } - #pragma warning restore 1998 - } -} -#pragma warning restore 1591 -" -)); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - Assert.Collection(eventListener.Events, - e => Assert.Equal("DiscoverTagHelpersFromCompilationStart", e.EventName), - e => Assert.Equal("DiscoverTagHelpersFromCompilationStop", e.EventName), - e => Assert.Equal("DiscoverTagHelpersFromReferencesStart", e.EventName), - e => Assert.Equal("DiscoverTagHelpersFromReferencesStop", e.EventName), - e => - { - Assert.Equal("RazorCodeGenerateStart", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Index.razor", file); - }, - e => - { - Assert.Equal("RazorCodeGenerateStop", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Index.razor", file); - }, - e => - { - Assert.Equal("RazorCodeGenerateStart", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Counter.razor", file); - }, - e => - { - Assert.Equal("RazorCodeGenerateStop", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Counter.razor", file); - }, - e => - { - Assert.Equal("AddSyntaxTrees", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("Pages_Index_razor.g.cs", file); - }); - - // Verify caching - eventListener.Events.Clear(); - result = RunGenerator(compilation, ref driver); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - Assert.Empty(eventListener.Events); - - static MetadataReference GetSurveyPromptMetadataReference(Compilation currentCompilation) - { - var updatedCompilation = currentCompilation.RemoveAllSyntaxTrees() - .WithAssemblyName("SurveyPromptAssembly") - .AddSyntaxTrees(CSharpSyntaxTree.ParseText(@" -using Microsoft.AspNetCore.Components; -using Microsoft.AspNetCore.Components.Rendering; -namespace SurveyPromptRootNamspace; -public class SurveyPrompt : ComponentBase -{ - protected override void BuildRenderTree(RenderTreeBuilder builder) {} -}")); - var stream = new MemoryStream(); - var emitResult = updatedCompilation.Emit(stream); - Assert.True(emitResult.Success); - - stream.Position = 0; - return MetadataReference.CreateFromStream(stream); - } - } - - [Fact] - public async Task SourceGenerator_CshtmlFiles_Works() - { - // Arrange - using var eventListener = new RazorEventListener(); - var project = CreateTestProject(new() - { - ["Pages/Index.cshtml"] = "

Hello world

", - ["Views/Shared/_Layout.cshtml"] = "

Layout

", - }); - var compilation = await project.GetCompilationAsync(); - var driver = await GetDriverAsync(project); - - var result = RunGenerator(compilation!, ref driver) - .VerifyPageOutput( -@"#pragma checksum ""Pages/Index.cshtml"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""6b5db227a6aa2228c777b0771108b184b1fc5df3"" -// -#pragma warning disable 1591 -[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCoreGeneratedDocument.Pages_Index), @""mvc.1.0.view"", @""/Pages/Index.cshtml"")] -namespace AspNetCoreGeneratedDocument -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Mvc; - using Microsoft.AspNetCore.Mvc.Rendering; - using Microsoft.AspNetCore.Mvc.ViewFeatures; - [global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemMetadataAttribute(""Identifier"", ""/Pages/Index.cshtml"")] - [global::System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute] - #nullable restore - internal sealed class Pages_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage - #nullable disable - { - #pragma warning disable 1998 - public async override global::System.Threading.Tasks.Task ExecuteAsync() - { - WriteLiteral(""

Hello world

""); - } - #pragma warning restore 1998 - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper Html { get; private set; } = default!; - #nullable disable - } -} -#pragma warning restore 1591 -", -@"#pragma checksum ""Views/Shared/_Layout.cshtml"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""99939b97abcdd846bd8ea59f7a08dacbe060cb3e"" -// -#pragma warning disable 1591 -[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCoreGeneratedDocument.Views_Shared__Layout), @""mvc.1.0.view"", @""/Views/Shared/_Layout.cshtml"")] -namespace AspNetCoreGeneratedDocument -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Mvc; - using Microsoft.AspNetCore.Mvc.Rendering; - using Microsoft.AspNetCore.Mvc.ViewFeatures; - [global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemMetadataAttribute(""Identifier"", ""/Views/Shared/_Layout.cshtml"")] - [global::System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute] - #nullable restore - internal sealed class Views_Shared__Layout : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage - #nullable disable - { - #pragma warning disable 1998 - public async override global::System.Threading.Tasks.Task ExecuteAsync() - { - WriteLiteral(""

Layout

""); - } - #pragma warning restore 1998 - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper Html { get; private set; } = default!; - #nullable disable - } -} -#pragma warning restore 1591 -"); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - Assert.Collection(eventListener.Events, - e => Assert.Equal("ComputeRazorSourceGeneratorOptions", e.EventName), - e => Assert.Equal("DiscoverTagHelpersFromCompilationStart", e.EventName), - e => Assert.Equal("DiscoverTagHelpersFromCompilationStop", e.EventName), - e => Assert.Equal("DiscoverTagHelpersFromReferencesStart", e.EventName), - e => Assert.Equal("DiscoverTagHelpersFromReferencesStop", e.EventName), - e => - { - Assert.Equal("RazorCodeGenerateStart", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Index.cshtml", file); - }, - e => - { - Assert.Equal("RazorCodeGenerateStop", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Index.cshtml", file); - }, - e => - { - Assert.Equal("RazorCodeGenerateStart", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Views/Shared/_Layout.cshtml", file); - }, - e => - { - Assert.Equal("RazorCodeGenerateStop", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Views/Shared/_Layout.cshtml", file); - }, - e => - { - Assert.Equal("AddSyntaxTrees", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("Pages_Index_cshtml.g.cs", file); - }, - e => - { - Assert.Equal("AddSyntaxTrees", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("Views_Shared__Layout_cshtml.g.cs", file); - }); - } - - [Fact] - public async Task SourceGenerator_CshtmlFiles_WhenMarkupChanges() - { - // Arrange - using var eventListener = new RazorEventListener(); - var project = CreateTestProject(new() - { - ["Pages/Index.cshtml"] = "

Hello world

", - ["Views/Shared/_Layout.cshtml"] = "

Layout

", - }); - var compilation = await project.GetCompilationAsync(); - var (driver, additionalTexts) = await GetDriverWithAdditionalTextAsync(project); - - var result = RunGenerator(compilation!, ref driver) - .VerifyPageOutput( -@"#pragma checksum ""Pages/Index.cshtml"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""6b5db227a6aa2228c777b0771108b184b1fc5df3"" -// -#pragma warning disable 1591 -[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCoreGeneratedDocument.Pages_Index), @""mvc.1.0.view"", @""/Pages/Index.cshtml"")] -namespace AspNetCoreGeneratedDocument -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Mvc; - using Microsoft.AspNetCore.Mvc.Rendering; - using Microsoft.AspNetCore.Mvc.ViewFeatures; - [global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemMetadataAttribute(""Identifier"", ""/Pages/Index.cshtml"")] - [global::System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute] - #nullable restore - internal sealed class Pages_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage - #nullable disable - { - #pragma warning disable 1998 - public async override global::System.Threading.Tasks.Task ExecuteAsync() - { - WriteLiteral(""

Hello world

""); - } - #pragma warning restore 1998 - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper Html { get; private set; } = default!; - #nullable disable - } -} -#pragma warning restore 1591 -", -@"#pragma checksum ""Views/Shared/_Layout.cshtml"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""99939b97abcdd846bd8ea59f7a08dacbe060cb3e"" -// -#pragma warning disable 1591 -[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCoreGeneratedDocument.Views_Shared__Layout), @""mvc.1.0.view"", @""/Views/Shared/_Layout.cshtml"")] -namespace AspNetCoreGeneratedDocument -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Mvc; - using Microsoft.AspNetCore.Mvc.Rendering; - using Microsoft.AspNetCore.Mvc.ViewFeatures; - [global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemMetadataAttribute(""Identifier"", ""/Views/Shared/_Layout.cshtml"")] - [global::System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute] - #nullable restore - internal sealed class Views_Shared__Layout : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage - #nullable disable - { - #pragma warning disable 1998 - public async override global::System.Threading.Tasks.Task ExecuteAsync() - { - WriteLiteral(""

Layout

""); - } - #pragma warning restore 1998 - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper Html { get; private set; } = default!; - #nullable disable - } -} -#pragma warning restore 1591 -"); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - eventListener.Events.Clear(); - - result = RunGenerator(compilation!, ref driver) - .VerifyOutputsMatch(result); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - Assert.Empty(eventListener.Events); - - var updatedText = new TestAdditionalText("Views/Shared/_Layout.cshtml", SourceText.From("

Updated Layout

", Encoding.UTF8)); - driver = driver.ReplaceAdditionalText(additionalTexts.First(f => f.Path == updatedText.Path), updatedText); - - result = RunGenerator(compilation!, ref driver) - .VerifyOutputsMatch(result, (1, -@"#pragma checksum ""Views/Shared/_Layout.cshtml"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""525ae8e5f9273913494d7a628b965837c601aed4"" -// -#pragma warning disable 1591 -[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCoreGeneratedDocument.Views_Shared__Layout), @""mvc.1.0.view"", @""/Views/Shared/_Layout.cshtml"")] -namespace AspNetCoreGeneratedDocument -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Mvc; - using Microsoft.AspNetCore.Mvc.Rendering; - using Microsoft.AspNetCore.Mvc.ViewFeatures; - [global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemMetadataAttribute(""Identifier"", ""/Views/Shared/_Layout.cshtml"")] - [global::System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute] - #nullable restore - internal sealed class Views_Shared__Layout : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage - #nullable disable - { - #pragma warning disable 1998 - public async override global::System.Threading.Tasks.Task ExecuteAsync() - { - WriteLiteral(""

Updated Layout

""); - } - #pragma warning restore 1998 - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper Html { get; private set; } = default!; - #nullable disable - } -} -#pragma warning restore 1591 -")); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - Assert.Collection(eventListener.Events, - e => - { - Assert.Equal("RazorCodeGenerateStart", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Views/Shared/_Layout.cshtml", file); - }, - e => - { - Assert.Equal("RazorCodeGenerateStop", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Views/Shared/_Layout.cshtml", file); - }, - e => - { - Assert.Equal("AddSyntaxTrees", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("Views_Shared__Layout_cshtml.g.cs", file); - }); - } - - [Fact] - public async Task SourceGenerator_CshtmlFiles_CSharpTypeChanges() - { - // Arrange - using var eventListener = new RazorEventListener(); - var project = CreateTestProject(new() - { - ["Pages/Index.cshtml"] = "

Hello world

", - ["Views/Shared/_Layout.cshtml"] = "

Layout

", - }, - new() - { - ["Person.cs"] = @" -public class Person -{ - public string Name { get; set; } -}" - }); - var compilation = await project.GetCompilationAsync(); - var (driver, additionalTexts) = await GetDriverWithAdditionalTextAsync(project); - - var result = RunGenerator(compilation!, ref driver) - .VerifyPageOutput(@"#pragma checksum ""Pages/Index.cshtml"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""6b5db227a6aa2228c777b0771108b184b1fc5df3"" -// -#pragma warning disable 1591 -[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCoreGeneratedDocument.Pages_Index), @""mvc.1.0.view"", @""/Pages/Index.cshtml"")] -namespace AspNetCoreGeneratedDocument -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Mvc; - using Microsoft.AspNetCore.Mvc.Rendering; - using Microsoft.AspNetCore.Mvc.ViewFeatures; - [global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemMetadataAttribute(""Identifier"", ""/Pages/Index.cshtml"")] - [global::System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute] - #nullable restore - internal sealed class Pages_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage - #nullable disable - { - #pragma warning disable 1998 - public async override global::System.Threading.Tasks.Task ExecuteAsync() - { - WriteLiteral(""

Hello world

""); - } - #pragma warning restore 1998 - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper Html { get; private set; } = default!; - #nullable disable - } -} -#pragma warning restore 1591 -", -@"#pragma checksum ""Views/Shared/_Layout.cshtml"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""99939b97abcdd846bd8ea59f7a08dacbe060cb3e"" -// -#pragma warning disable 1591 -[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCoreGeneratedDocument.Views_Shared__Layout), @""mvc.1.0.view"", @""/Views/Shared/_Layout.cshtml"")] -namespace AspNetCoreGeneratedDocument -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Mvc; - using Microsoft.AspNetCore.Mvc.Rendering; - using Microsoft.AspNetCore.Mvc.ViewFeatures; - [global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemMetadataAttribute(""Identifier"", ""/Views/Shared/_Layout.cshtml"")] - [global::System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute] - #nullable restore - internal sealed class Views_Shared__Layout : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage - #nullable disable - { - #pragma warning disable 1998 - public async override global::System.Threading.Tasks.Task ExecuteAsync() - { - WriteLiteral(""

Layout

""); - } - #pragma warning restore 1998 - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper Html { get; private set; } = default!; - #nullable disable - } -} -#pragma warning restore 1591 -"); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - eventListener.Events.Clear(); - - result = RunGenerator(compilation!, ref driver) - .VerifyOutputsMatch(result); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - project = project.Documents.First().WithText(SourceText.From(@" -public class Person -{ - public string Name { get; set; } - public int Age { get; set; } -}", Encoding.UTF8)).Project; - compilation = await project.GetCompilationAsync(); - - result = RunGenerator(compilation!, ref driver) - .VerifyOutputsMatch(result); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - Assert.Collection(eventListener.Events, - e => Assert.Equal("DiscoverTagHelpersFromCompilationStart", e.EventName), - e => Assert.Equal("DiscoverTagHelpersFromCompilationStop", e.EventName)); - - } - - [Fact] - public async Task SourceGenerator_CshtmlFiles_NewTagHelper() - { - // Arrange - using var eventListener = new RazorEventListener(); - var project = CreateTestProject(new() - { - ["Pages/Index.cshtml"] = -@" -@addTagHelper *, TestProject -

Hello world

", - ["Views/Shared/_Layout.cshtml"] = "

Layout

", - }); - var compilation = await project.GetCompilationAsync(); - var (driver, additionalTexts) = await GetDriverWithAdditionalTextAsync(project); - - var result = RunGenerator(compilation!, ref driver) - .VerifyPageOutput( -@"#pragma checksum ""Pages/Index.cshtml"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""5d59ecd7b7cf7355d7f60234988be34b81a8b614"" -// -#pragma warning disable 1591 -[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCoreGeneratedDocument.Pages_Index), @""mvc.1.0.view"", @""/Pages/Index.cshtml"")] -namespace AspNetCoreGeneratedDocument -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Mvc; - using Microsoft.AspNetCore.Mvc.Rendering; - using Microsoft.AspNetCore.Mvc.ViewFeatures; - [global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemMetadataAttribute(""Identifier"", ""/Pages/Index.cshtml"")] - [global::System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute] - #nullable restore - internal sealed class Pages_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage - #nullable disable - { - #pragma warning disable 1998 - public async override global::System.Threading.Tasks.Task ExecuteAsync() - { - WriteLiteral(""\r\n""); - WriteLiteral(""

Hello world

""); - } - #pragma warning restore 1998 - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper Html { get; private set; } = default!; - #nullable disable - } -} -#pragma warning restore 1591 -", -@"#pragma checksum ""Views/Shared/_Layout.cshtml"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""99939b97abcdd846bd8ea59f7a08dacbe060cb3e"" -// -#pragma warning disable 1591 -[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCoreGeneratedDocument.Views_Shared__Layout), @""mvc.1.0.view"", @""/Views/Shared/_Layout.cshtml"")] -namespace AspNetCoreGeneratedDocument -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Mvc; - using Microsoft.AspNetCore.Mvc.Rendering; - using Microsoft.AspNetCore.Mvc.ViewFeatures; - [global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemMetadataAttribute(""Identifier"", ""/Views/Shared/_Layout.cshtml"")] - [global::System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute] - #nullable restore - internal sealed class Views_Shared__Layout : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage - #nullable disable - { - #pragma warning disable 1998 - public async override global::System.Threading.Tasks.Task ExecuteAsync() - { - WriteLiteral(""

Layout

""); - } - #pragma warning restore 1998 - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper Html { get; private set; } = default!; - #nullable disable - } -} -#pragma warning restore 1591 -"); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - eventListener.Events.Clear(); - - result = RunGenerator(compilation!, ref driver) - .VerifyOutputsMatch(result); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - project = project.AddDocument("HeaderTagHelper.cs", SourceText.From(@" -using Microsoft.AspNetCore.Razor.TagHelpers; -namespace MyApp; - -[HtmlTargetElement(""h2"")] -public class HeaderTagHelper : TagHelper -{ - public override int Order => 0; - - public override void Process(TagHelperContext context, TagHelperOutput output) - { - output.Attributes.Add(""role"", ""heading""); - } -}", Encoding.UTF8)).Project; - compilation = await project.GetCompilationAsync(); - - result = RunGenerator(compilation!, ref driver); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - Assert.Collection(eventListener.Events, - e => Assert.Equal("DiscoverTagHelpersFromCompilationStart", e.EventName), - e => Assert.Equal("DiscoverTagHelpersFromCompilationStop", e.EventName), - e => - { - Assert.Equal("RazorCodeGenerateStart", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Index.cshtml", file); - }, - e => - { - Assert.Equal("RazorCodeGenerateStop", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Pages/Index.cshtml", file); - }, - e => - { - Assert.Equal("RazorCodeGenerateStart", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Views/Shared/_Layout.cshtml", file); - }, - e => - { - Assert.Equal("RazorCodeGenerateStop", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("/Views/Shared/_Layout.cshtml", file); - }, - e => - { - Assert.Equal("AddSyntaxTrees", e.EventName); - var file = Assert.Single(e.Payload); - Assert.Equal("Pages_Index_cshtml.g.cs", file); - }); - } - - [Fact] - public async Task SourceGenerator_CshtmlFiles_RazorDiagnostics_Fixed() - { - // Arrange - var project = CreateTestProject(new() - { - ["Pages/Index.cshtml"] = -@" -@{ -

Malformed h1 -} -

", - ["Views/Shared/_Layout.cshtml"] = "

Layout

", - }); - var compilation = await project.GetCompilationAsync(); - var (driver, additionalTexts) = await GetDriverWithAdditionalTextAsync(project); - - var result = RunGenerator(compilation!, ref driver) - .VerifyPageOutput( -@"#pragma checksum ""Pages/Index.cshtml"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""8e83eb537e49cadda4aff01de0bd33aa716fc633"" -// -#pragma warning disable 1591 -[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCoreGeneratedDocument.Pages_Index), @""mvc.1.0.view"", @""/Pages/Index.cshtml"")] -namespace AspNetCoreGeneratedDocument -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Mvc; - using Microsoft.AspNetCore.Mvc.Rendering; - using Microsoft.AspNetCore.Mvc.ViewFeatures; - [global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemMetadataAttribute(""Identifier"", ""/Pages/Index.cshtml"")] - [global::System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute] - #nullable restore - internal sealed class Pages_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage - #nullable disable - { - #pragma warning disable 1998 - public async override global::System.Threading.Tasks.Task ExecuteAsync() - { - WriteLiteral(""\r\n""); - WriteLiteral(""

Malformed h1\r\n}\r\n

""); - } - #pragma warning restore 1998 - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper Html { get; private set; } = default!; - #nullable disable - } -} -#pragma warning restore 1591 -", -@"#pragma checksum ""Views/Shared/_Layout.cshtml"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""99939b97abcdd846bd8ea59f7a08dacbe060cb3e"" -// -#pragma warning disable 1591 -[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCoreGeneratedDocument.Views_Shared__Layout), @""mvc.1.0.view"", @""/Views/Shared/_Layout.cshtml"")] -namespace AspNetCoreGeneratedDocument -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Mvc; - using Microsoft.AspNetCore.Mvc.Rendering; - using Microsoft.AspNetCore.Mvc.ViewFeatures; - [global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemMetadataAttribute(""Identifier"", ""/Views/Shared/_Layout.cshtml"")] - [global::System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute] - #nullable restore - internal sealed class Views_Shared__Layout : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage - #nullable disable - { - #pragma warning disable 1998 - public async override global::System.Threading.Tasks.Task ExecuteAsync() - { - WriteLiteral(""

Layout

""); - } - #pragma warning restore 1998 - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper Html { get; private set; } = default!; - #nullable disable - } -} -#pragma warning restore 1591 -"); - - var diagnostic = Assert.Single(result.Diagnostics); - Assert.Equal("RZ1006", diagnostic.Id); - Assert.Equal(2, result.GeneratedSources.Length); - - var updatedText = new TestAdditionalText("Pages/Index.cshtml", SourceText.From("

Fixed header

", Encoding.UTF8)); - driver = driver.ReplaceAdditionalText(additionalTexts.First(f => f.Path == updatedText.Path), updatedText); - - result = RunGenerator(compilation!, ref driver) - .VerifyOutputsMatch(result, (0, -@"#pragma checksum ""Pages/Index.cshtml"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""26b4fe0ac8d17fb3e02d5cba709603ceba9ae3ef"" -// -#pragma warning disable 1591 -[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCoreGeneratedDocument.Pages_Index), @""mvc.1.0.view"", @""/Pages/Index.cshtml"")] -namespace AspNetCoreGeneratedDocument -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Mvc; - using Microsoft.AspNetCore.Mvc.Rendering; - using Microsoft.AspNetCore.Mvc.ViewFeatures; - [global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemMetadataAttribute(""Identifier"", ""/Pages/Index.cshtml"")] - [global::System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute] - #nullable restore - internal sealed class Pages_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage - #nullable disable - { - #pragma warning disable 1998 - public async override global::System.Threading.Tasks.Task ExecuteAsync() - { - WriteLiteral(""

Fixed header

""); - } - #pragma warning restore 1998 - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper Html { get; private set; } = default!; - #nullable disable - } -} -#pragma warning restore 1591 -")); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - } - - [Fact] - public async Task SourceGenerator_CshtmlFiles_RazorDiagnostics_Introduced() - { - // Arrange - var project = CreateTestProject(new() - { - ["Pages/Index.cshtml"] = "

Valid h1

", - ["Views/Shared/_Layout.cshtml"] = "

Layout

", - }); - var compilation = await project.GetCompilationAsync(); - var (driver, additionalTexts) = await GetDriverWithAdditionalTextAsync(project); - - var result = RunGenerator(compilation!, ref driver) - .VerifyPageOutput( -@"#pragma checksum ""Pages/Index.cshtml"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""7f59d2951cc70dc08bc4e89b90bd3c5ba68459b9"" -// -#pragma warning disable 1591 -[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCoreGeneratedDocument.Pages_Index), @""mvc.1.0.view"", @""/Pages/Index.cshtml"")] -namespace AspNetCoreGeneratedDocument -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Mvc; - using Microsoft.AspNetCore.Mvc.Rendering; - using Microsoft.AspNetCore.Mvc.ViewFeatures; - [global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemMetadataAttribute(""Identifier"", ""/Pages/Index.cshtml"")] - [global::System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute] - #nullable restore - internal sealed class Pages_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage - #nullable disable - { - #pragma warning disable 1998 - public async override global::System.Threading.Tasks.Task ExecuteAsync() - { - WriteLiteral(""

Valid h1

""); - } - #pragma warning restore 1998 - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper Html { get; private set; } = default!; - #nullable disable - } -} -#pragma warning restore 1591 -", -@"#pragma checksum ""Views/Shared/_Layout.cshtml"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""99939b97abcdd846bd8ea59f7a08dacbe060cb3e"" -// -#pragma warning disable 1591 -[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCoreGeneratedDocument.Views_Shared__Layout), @""mvc.1.0.view"", @""/Views/Shared/_Layout.cshtml"")] -namespace AspNetCoreGeneratedDocument -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Mvc; - using Microsoft.AspNetCore.Mvc.Rendering; - using Microsoft.AspNetCore.Mvc.ViewFeatures; - [global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemMetadataAttribute(""Identifier"", ""/Views/Shared/_Layout.cshtml"")] - [global::System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute] - #nullable restore - internal sealed class Views_Shared__Layout : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage - #nullable disable - { - #pragma warning disable 1998 - public async override global::System.Threading.Tasks.Task ExecuteAsync() - { - WriteLiteral(""

Layout

""); - } - #pragma warning restore 1998 - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper Html { get; private set; } = default!; - #nullable disable - } -} -#pragma warning restore 1591 -"); - - Assert.Empty(result.Diagnostics); - Assert.Equal(2, result.GeneratedSources.Length); - - var updatedText = new TestAdditionalText("Pages/Index.cshtml", SourceText.From(@" -@{ -

Malformed h1 -} -

", Encoding.UTF8)); - driver = driver.ReplaceAdditionalText(additionalTexts.First(f => f.Path == updatedText.Path), updatedText); - - result = RunGenerator(compilation!, ref driver) - .VerifyOutputsMatch(result, (0, -@"#pragma checksum ""Pages/Index.cshtml"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""d088006c7620c4503e95ef0b4cd1dbc82362bf8b"" -// -#pragma warning disable 1591 -[assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCoreGeneratedDocument.Pages_Index), @""mvc.1.0.view"", @""/Pages/Index.cshtml"")] -namespace AspNetCoreGeneratedDocument -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Mvc; - using Microsoft.AspNetCore.Mvc.Rendering; - using Microsoft.AspNetCore.Mvc.ViewFeatures; - [global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemMetadataAttribute(""Identifier"", ""/Pages/Index.cshtml"")] - [global::System.Runtime.CompilerServices.CreateNewOnMetadataUpdateAttribute] - #nullable restore - internal sealed class Pages_Index : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage - #nullable disable - { - #pragma warning disable 1998 - public async override global::System.Threading.Tasks.Task ExecuteAsync() - { - WriteLiteral(""\r\n""); - WriteLiteral(""

Malformed h1\r\n}\r\n

""); - } - #pragma warning restore 1998 - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } = default!; - #nullable disable - #nullable restore - [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] - public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper Html { get; private set; } = default!; - #nullable disable - } -} -#pragma warning restore 1591 -")); - - var diagnostic = Assert.Single(result.Diagnostics); - Assert.Equal("RZ1006", diagnostic.Id); - Assert.Equal(2, result.GeneratedSources.Length); - } - - [Fact] - public async Task SourceGenerator_DoesNotUpdateSources_WhenSourceGeneratorIsSuppressed() - { - // Regression test for https://github.com/dotnet/aspnetcore/issues/36227 - var project = CreateTestProject(new() - { - ["Pages/Index.razor"] = "

Hello world

", - ["Pages/Counter.razor"] = "

Counter

", - }); - - var compilation = await project.GetCompilationAsync(); - var (driver, additionalTexts, optionsProvider) = await GetDriverWithAdditionalTextAndProviderAsync(project); - - var result = RunGenerator(compilation!, ref driver); - result.VerifyPageOutput( -@"#pragma checksum ""Pages/Index.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""6b5db227a6aa2228c777b0771108b184b1fc5df3"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; - public partial class Index : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Hello world

""); - } - #pragma warning restore 1998 - } -} -#pragma warning restore 1591 -", -@"#pragma checksum ""Pages/Counter.razor"" ""{ff1816ec-aa5e-4d10-87f7-6f4963833460}"" ""0de17e526cd536d59072aa0e924e99111b16b97a"" -// -#pragma warning disable 1591 -namespace MyApp.Pages -{ - #line hidden - using System; - using System.Collections.Generic; - using System.Linq; - using System.Threading.Tasks; - using Microsoft.AspNetCore.Components; - public partial class Counter : global::Microsoft.AspNetCore.Components.ComponentBase - { - #pragma warning disable 1998 - protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder __builder) - { - __builder.AddMarkupContent(0, ""

Counter

""); - } - #pragma warning restore 1998 - } -} -#pragma warning restore 1591 -"); - - // now run the generator with suppression - var suppressedOptions = optionsProvider.Clone(); - suppressedOptions.TestGlobalOptions["build_property.SuppressRazorSourceGenerator"] = "true"; - driver = driver.WithUpdatedAnalyzerConfigOptions(suppressedOptions); - - // results should be empty - var emptyResult = RunGenerator(compilation!, ref driver) - .VerifyPageOutput(); - - // now unsuppress and re-run - driver = driver.WithUpdatedAnalyzerConfigOptions(optionsProvider); - - result = RunGenerator(compilation!, ref driver) - .VerifyOutputsMatch(result); - } - - - private static async ValueTask GetDriverAsync(Project project) - { - var (driver, _) = await GetDriverWithAdditionalTextAsync(project); - return driver; - } - - private static async ValueTask<(GeneratorDriver, ImmutableArray)> GetDriverWithAdditionalTextAsync(Project project, Action? configureGlobalOptions = null) - { - var result = await GetDriverWithAdditionalTextAndProviderAsync(project, configureGlobalOptions); - return (result.Item1, result.Item2); - } - - private static async ValueTask<(GeneratorDriver, ImmutableArray, TestAnalyzerConfigOptionsProvider)> GetDriverWithAdditionalTextAndProviderAsync(Project project, Action? configureGlobalOptions = null) - { - var razorSourceGenerator = new RazorSourceGenerator().AsSourceGenerator(); - var driver = (GeneratorDriver)CSharpGeneratorDriver.Create(new[] { razorSourceGenerator }, parseOptions: (CSharpParseOptions)project.ParseOptions!, driverOptions: new GeneratorDriverOptions(IncrementalGeneratorOutputKind.None, true)); - - var optionsProvider = new TestAnalyzerConfigOptionsProvider(); - optionsProvider.TestGlobalOptions["build_property.RazorConfiguration"] = "Default"; - optionsProvider.TestGlobalOptions["build_property.RootNamespace"] = "MyApp"; - optionsProvider.TestGlobalOptions["build_property.RazorLangVersion"] = "Latest"; - optionsProvider.TestGlobalOptions["build_property.GenerateRazorMetadataSourceChecksumAttributes"] = "false"; - - configureGlobalOptions?.Invoke(optionsProvider); - - var additionalTexts = ImmutableArray.Empty; - - foreach (var document in project.AdditionalDocuments) - { - var additionalText = new TestAdditionalText(document.Name, await document.GetTextAsync()); - additionalTexts = additionalTexts.Add(additionalText); - - var additionalTextOptions = new TestAnalyzerConfigOptions - { - ["build_metadata.AdditionalFiles.TargetPath"] = Convert.ToBase64String(Encoding.UTF8.GetBytes(additionalText.Path)), - }; - - optionsProvider.AdditionalTextOptions[additionalText.Path] = additionalTextOptions; - } - - driver = driver - .AddAdditionalTexts(additionalTexts) - .WithUpdatedAnalyzerConfigOptions(optionsProvider); - - return (driver, additionalTexts, optionsProvider); - } - - private static GeneratorRunResult RunGenerator(Compilation compilation, ref GeneratorDriver driver) - { - driver = driver.RunGenerators(compilation); - - var result = driver.GetRunResult(); - return result.Results[0]; - } - - private static Project CreateTestProject( - Dictionary additonalSources, - Dictionary? sources = null) - { - var project = _baseProject; - - if (sources is not null) - { - foreach (var (name, source) in sources) - { - project = project.AddDocument(name, source).Project; - } - } - - foreach (var (name, source) in additonalSources) - { - project = project.AddAdditionalDocument(name, source).Project; - } - - return project; - } - - private class AppLocalResolver : ICompilationAssemblyResolver - { - public bool TryResolveAssemblyPaths(CompilationLibrary library, List? assemblies) - { - foreach (var assembly in library.Assemblies) - { - var dll = Path.Combine(Directory.GetCurrentDirectory(), "refs", Path.GetFileName(assembly)); - if (File.Exists(dll)) - { - assemblies!.Add(dll); - return true; - } - - dll = Path.Combine(Directory.GetCurrentDirectory(), Path.GetFileName(assembly)); - if (File.Exists(dll)) - { - assemblies!.Add(dll); - return true; - } - } - - return false; - } - } - - private static Project CreateBaseProject() - { - var projectId = ProjectId.CreateNewId(debugName: "TestProject"); - - var solution = new AdhocWorkspace() - .CurrentSolution - .AddProject(projectId, "TestProject", "TestProject", LanguageNames.CSharp); - - var project = solution.Projects.Single() - .WithCompilationOptions(new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary) - .WithNullableContextOptions(NullableContextOptions.Enable)); - - project = project.WithParseOptions(((CSharpParseOptions)project.ParseOptions!).WithLanguageVersion(LanguageVersion.Preview)); - - - foreach (var defaultCompileLibrary in DependencyContext.Load(typeof(RazorSourceGeneratorTests).Assembly)!.CompileLibraries) - { - foreach (var resolveReferencePath in defaultCompileLibrary.ResolveReferencePaths(new AppLocalResolver())) - { - project = project.AddMetadataReference(MetadataReference.CreateFromFile(resolveReferencePath)); - } - } - - // The deps file in the project is incorrect and does not contain "compile" nodes for some references. - // However these binaries are always present in the bin output. As a "temporary" workaround, we'll add - // every dll file that's present in the test's build output as a metadatareference. - foreach (var assembly in Directory.EnumerateFiles(AppContext.BaseDirectory, "*.dll")) - { - if (!project.MetadataReferences.Any(c => string.Equals(Path.GetFileNameWithoutExtension(c.Display), Path.GetFileNameWithoutExtension(assembly), StringComparison.OrdinalIgnoreCase))) - { - project = project.AddMetadataReference(MetadataReference.CreateFromFile(assembly)); - } - } - - return project; - } - - private class TestAnalyzerConfigOptionsProvider : AnalyzerConfigOptionsProvider - { - public override AnalyzerConfigOptions GlobalOptions => TestGlobalOptions; - - public TestAnalyzerConfigOptions TestGlobalOptions { get; } = new TestAnalyzerConfigOptions(); - - public override AnalyzerConfigOptions GetOptions(SyntaxTree tree) => throw new NotImplementedException(); - - public Dictionary AdditionalTextOptions { get; } = new(); - - public override AnalyzerConfigOptions GetOptions(AdditionalText textFile) - { - return AdditionalTextOptions.TryGetValue(textFile.Path, out var options) ? options : new TestAnalyzerConfigOptions(); - } - - public TestAnalyzerConfigOptionsProvider Clone() - { - var provider = new TestAnalyzerConfigOptionsProvider(); - foreach (var option in this.TestGlobalOptions.Options) - { - provider.TestGlobalOptions[option.Key] = option.Value; - } - foreach (var option in this.AdditionalTextOptions) - { - TestAnalyzerConfigOptions newOptions = new TestAnalyzerConfigOptions(); - foreach (var subOption in option.Value.Options) - { - newOptions[subOption.Key] = subOption.Value; - } - provider.AdditionalTextOptions[option.Key] = newOptions; - - } - return provider; - } - } - - private class TestAnalyzerConfigOptions : AnalyzerConfigOptions - { - public Dictionary Options { get; } = new(); - - public string this[string name] - { - get => Options[name]; - set => Options[name] = value; - } - - public override bool TryGetValue(string key, [NotNullWhen(true)] out string? value) - => Options.TryGetValue(key, out value); - } - } - - internal static class Extensions - { - public static GeneratorRunResult VerifyPageOutput(this GeneratorRunResult result, params string[] expectedOutput) - { - if (expectedOutput.Length == 1 && string.IsNullOrWhiteSpace(expectedOutput[0])) - { - GenerateExpectedOutput(result); - } - else - { - Assert.Equal(expectedOutput.Length, result.GeneratedSources.Length); - for (int i = 0; i < result.GeneratedSources.Length; i++) - { - var text = TrimChecksum(result.GeneratedSources[i].SourceText.ToString()); - Assert.Equal(text, TrimChecksum(expectedOutput[i]), ignoreWhiteSpaceDifferences: true); - } - } - - return result; - } - - private static void GenerateExpectedOutput(GeneratorRunResult result) - { - StringBuilder sb = new StringBuilder("Generated Output:").AppendLine().AppendLine(); - for (int i = 0; i < result.GeneratedSources.Length; i++) - { - if (i > 0) - { - sb.AppendLine(","); - } - sb.Append("@\"").Append(result.GeneratedSources[i].SourceText.ToString().Replace("\"", "\"\"")).Append('"'); - } - Assert.True(false, sb.ToString()); - } - - public static GeneratorRunResult VerifyOutputsMatch(this GeneratorRunResult actual, GeneratorRunResult expected, params (int index, string replacement)[] diffs) - { - Assert.Equal(actual.GeneratedSources.Length, expected.GeneratedSources.Length); - for (int i = 0; i < actual.GeneratedSources.Length; i++) - { - var diff = diffs.FirstOrDefault(p => p.index == i).replacement; - if (diff is null) - { - var actualText = actual.GeneratedSources[i].SourceText.ToString(); - Assert.True(expected.GeneratedSources[i].SourceText.ToString() == actualText, $"No diff supplied. But index {i} was:\r\n\r\n{actualText.Replace("\"", "\"\"")}"); - } - else - { - Assert.Equal(TrimChecksum(diff), TrimChecksum(actual.GeneratedSources[i].SourceText.ToString())); - } - } - - return actual; - } - - private static string TrimChecksum(string text) - { - var trimmed = text.Trim('\r', '\n') // start and end - .Replace("\r\n", "\r").Replace('\n', '\r').Replace('\r', '\n') // regular new-lines - .Replace("\\r\\n", "\\n"); // embedded new-lines - Assert.StartsWith("#pragma", trimmed); - return trimmed.Substring(trimmed.IndexOf('\n') + 1); - } - } - -} diff --git a/src/Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/SourceGeneratorProjectItemTest.cs b/src/Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/SourceGeneratorProjectItemTest.cs deleted file mode 100644 index e4b51c2bca12..000000000000 --- a/src/Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/SourceGeneratorProjectItemTest.cs +++ /dev/null @@ -1,121 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using Xunit; -using Moq; -using Microsoft.AspNetCore.Razor.Language; -using Microsoft.CodeAnalysis; - -namespace Microsoft.NET.Sdk.Razor.SourceGenerators -{ - public class SourceGeneratorProjectItemTest - { - [Fact] - public void PhysicalPath_ReturnsSourceTextPath() - { - // Arrange - var emptyBasePath = "/"; - var path = "/foo/bar.cshtml"; - var projectItem = new SourceGeneratorProjectItem( - filePath: path, - basePath: emptyBasePath, - relativePhysicalPath: "/foo", - fileKind: FileKinds.Legacy, - additionalText: new TestAdditionalText(string.Empty), - cssScope: null); - - // Act - var physicalPath = projectItem.PhysicalPath; - - // Assert - Assert.Equal("dummy", physicalPath); - } - - [Theory] - [InlineData("/Home/Index")] - [InlineData("EditUser")] - public void Extension_ReturnsNullIfFileDoesNotHaveExtension(string path) - { - // Arrange - var projectItem = new SourceGeneratorProjectItem( - filePath: path, - basePath: "/views", - relativePhysicalPath: "/foo", - fileKind: FileKinds.Legacy, - additionalText: new TestAdditionalText(string.Empty), - cssScope: null); - - // Act - var extension = projectItem.Extension; - - // Assert - Assert.Null(extension); - } - - [Theory] - [InlineData("/Home/Index.cshtml", ".cshtml")] - [InlineData("/Home/Index.en-gb.cshtml", ".cshtml")] - [InlineData("EditUser.razor", ".razor")] - public void Extension_ReturnsFileExtension(string path, string expected) - { - // Arrange - var projectItem = new SourceGeneratorProjectItem( - filePath: path, - basePath: "/views", - relativePhysicalPath: "/foo", - fileKind: FileKinds.Legacy, - additionalText: new TestAdditionalText(string.Empty), - cssScope: null); - - // Act - var extension = projectItem.Extension; - - // Assert - Assert.Equal(expected, extension); - } - - [Theory] - [InlineData("Home/Index.cshtml", "Index.cshtml")] - [InlineData("/Accounts/Customers/Manage-en-us.razor", "Manage-en-us.razor")] - public void FileName_ReturnsFileNameWithExtension(string path, string expected) - { - // Arrange - var projectItem = new SourceGeneratorProjectItem( - filePath: path, - basePath: "/", - relativePhysicalPath: "/foo", - fileKind: FileKinds.Legacy, - additionalText: new TestAdditionalText(string.Empty), - cssScope: null); - - // Act - var fileName = projectItem.FileName; - - // Assert - Assert.Equal(expected, fileName); - } - - [Theory] - [InlineData("Home/Index", "Home/Index")] - [InlineData("Home/Index.cshtml", "Home/Index")] - [InlineData("/Accounts/Customers/Manage.en-us.razor", "/Accounts/Customers/Manage.en-us")] - [InlineData("/Accounts/Customers/Manage-en-us.razor", "/Accounts/Customers/Manage-en-us")] - public void PathWithoutExtension_ExcludesExtension(string path, string expected) - { - // Arrange - var projectItem = new SourceGeneratorProjectItem( - filePath: path, - basePath: "/", - relativePhysicalPath: "/foo", - fileKind: FileKinds.Legacy, - additionalText: new TestAdditionalText(string.Empty), - cssScope: null); - - // Act - var fileName = projectItem.FilePathWithoutExtension; - - // Assert - Assert.Equal(expected, fileName); - } - } -} diff --git a/src/Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/SourceTextSourceLineCollectionTest.cs b/src/Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/SourceTextSourceLineCollectionTest.cs deleted file mode 100644 index f34eac372792..000000000000 --- a/src/Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/SourceTextSourceLineCollectionTest.cs +++ /dev/null @@ -1,136 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System; -using System.Runtime.InteropServices; -using Xunit; -using Microsoft.AspNetCore.Razor.Language; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Text; - -namespace Microsoft.NET.Sdk.Razor.SourceGenerators -{ - public class SourceTextSourceLineCollectionTest - { - [Fact] - public void GetLocation_Negative() - { - // Arrange - var content = @"@addTagHelper, * Stuff -@* A comment *@"; - var sourceText = SourceText.From(content); - var collection = new SourceTextSourceLineCollection("dummy", sourceText.Lines); - - // Act & Assert - Assert.Throws(() => collection.GetLocation(-1)); - } - - [Fact] - public void GetLocation_TooBig() - { - // Arrange - var content = @"addTagHelper, * Stuff -@* A comment *@"; - var sourceText = SourceText.From(content); - var collection = new SourceTextSourceLineCollection("dummy", sourceText.Lines); - - // Act & Assert - Assert.Throws(() => collection.GetLocation(40)); - } - - [Fact] - public void GetLocation_AtStart() - { - // Arrange - var content = @"@addTaghelper, * Stuff -@* A comment *@"; - var sourceText = SourceText.From(content); - var collection = new SourceTextSourceLineCollection("dummy", sourceText.Lines); - - // Act - var location = collection.GetLocation(0); - - // Assert - var expected = new SourceLocation("dummy", 0, 0, 0); - Assert.Equal(expected, location); - } - - [Fact] - public void GetLocation_AtEnd() - { - // Arrange - var content = @"@addTagHelper, * Stuff -@* A comment *@"; - var sourceText = SourceText.From(content); - var collection = new SourceTextSourceLineCollection("dummy", sourceText.Lines); - var length = content.Length; - - // Act - var location = collection.GetLocation(length); - - // Assert - var expected = new SourceLocation("dummy", length, 1, 15); - Assert.Equal(expected, location); - } - - [Fact] - public void GetLineLength_Negative() - { - // Arrange - var content = @"@addTagHelper, * Stuff -@* A comment *@"; - var sourceText = SourceText.From(content); - var collection = new SourceTextSourceLineCollection("dummy", sourceText.Lines); - - // Act & Assert - Assert.Throws(() => collection.GetLineLength(-1)); - } - - [Fact] - public void GetLineLength_Bigger() - { - // Arrange - var content = @"@addTagHelper, * Stuff -@* A comment *@"; - var sourceText = SourceText.From(content); - var collection = new SourceTextSourceLineCollection("dummy", sourceText.Lines); - - // Act & Assert - Assert.Throws(() => collection.GetLineLength(40)); - } - - [Fact] - public void GetLineLength_AtStart() - { - // Arrange - var content = @"@addTagHelper, * Stuff -@* A comment *@"; - var sourceText = SourceText.From(content); - var collection = new SourceTextSourceLineCollection("dummy", sourceText.Lines); - - // Act - var lineLength = collection.GetLineLength(0); - - // Assert - var expectedLineLength = 22 + Environment.NewLine.Length; - Assert.Equal(expectedLineLength, lineLength); - } - - [Fact] - public void GetLineLength_AtEnd() - { - // Arrange - var content = @"@addTagHelper, * Stuff -@* A comment *@"; - var sourceText = SourceText.From(content); - var collection = new SourceTextSourceLineCollection("dummy", sourceText.Lines); - - // Act - var lineLength = collection.GetLineLength(1); - - // Assert - var expectedLineLength = 15; - Assert.Equal(expectedLineLength, lineLength); - } - } -} diff --git a/src/Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/TestAdditionalText.cs b/src/Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/TestAdditionalText.cs deleted file mode 100644 index 06ef7cafff69..000000000000 --- a/src/Tests/Microsoft.NET.Sdk.Razor.SourceGenerators.Tests/TestAdditionalText.cs +++ /dev/null @@ -1,30 +0,0 @@ -// Copyright (c) .NET Foundation. All rights reserved. -// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. - -using System.Text; -using System.Threading; -using Microsoft.CodeAnalysis; -using Microsoft.CodeAnalysis.Text; - -namespace Microsoft.NET.Sdk.Razor.SourceGenerators -{ - public sealed class TestAdditionalText : AdditionalText - { - private readonly SourceText _text; - - public TestAdditionalText(string path, SourceText text) - { - Path = path; - _text = text; - } - - public TestAdditionalText(string text = "", Encoding encoding = null, string path = "dummy") - : this(path, SourceText.From(text, encoding)) - { - } - - public override string Path { get; } - - public override SourceText GetText(CancellationToken cancellationToken = default) => _text; - } -}