Skip to content

Commit

Permalink
Calculate SuppressAddComponentParameter in tooling (#10763)
Browse files Browse the repository at this point in the history
Fixes #10736

Chris did a good breakdown of what this value is used for #10736 (comment)
  • Loading branch information
ryzngard committed Sep 20, 2024
1 parent 3b87086 commit 6aa9aee
Show file tree
Hide file tree
Showing 21 changed files with 134 additions and 80 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.

using System.Collections.Generic;
using System.Linq;

namespace Microsoft.CodeAnalysis.Razor.Compiler.CSharp;

internal static class CompilationExtensions
{
public static bool HasAddComponentParameter(this Compilation compilation)
{
return compilation.GetTypesByMetadataName("Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder")
.Any(static t =>
t.DeclaredAccessibility == Accessibility.Public &&
t.GetMembers("AddComponentParameter")
.Any(static m => m.DeclaredAccessibility == Accessibility.Public));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,10 @@ public RazorCodeGenerationOptionsBuilder(RazorConfiguration configuration)
ArgHelper.ThrowIfNull(configuration);

Configuration = configuration;
if (configuration.SuppressAddComponentParameter)
{
_flags.SetFlag(RazorCodeGenerationOptionsFlags.SuppressAddComponentParameter);
}
}

public RazorCodeGenerationOptionsBuilder(RazorCodeGenerationOptionsFlags flags)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,20 +11,23 @@ public sealed record class RazorConfiguration(
RazorLanguageVersion LanguageVersion,
string ConfigurationName,
ImmutableArray<RazorExtension> Extensions,
LanguageServerFlags? LanguageServerFlags = null,
bool UseConsolidatedMvcViews = true)
bool UseConsolidatedMvcViews = true,
bool SuppressAddComponentParameter = false,
LanguageServerFlags? LanguageServerFlags = null)
{
public static readonly RazorConfiguration Default = new(
RazorLanguageVersion.Latest,
ConfigurationName: "unnamed",
Extensions: [],
LanguageServerFlags: null,
UseConsolidatedMvcViews: true);
UseConsolidatedMvcViews: true,
SuppressAddComponentParameter: false,
LanguageServerFlags: null);

public bool Equals(RazorConfiguration? other)
=> other is not null &&
LanguageVersion == other.LanguageVersion &&
ConfigurationName == other.ConfigurationName &&
SuppressAddComponentParameter == other.SuppressAddComponentParameter &&
LanguageServerFlags == other.LanguageServerFlags &&
UseConsolidatedMvcViews == other.UseConsolidatedMvcViews &&
Extensions.SequenceEqual(other.Extensions);
Expand All @@ -35,6 +38,7 @@ public override int GetHashCode()
hash.Add(LanguageVersion);
hash.Add(ConfigurationName);
hash.Add(Extensions);
hash.Add(SuppressAddComponentParameter);
hash.Add(UseConsolidatedMvcViews);
hash.Add(LanguageServerFlags);
return hash;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,8 +87,7 @@ private static StaticCompilationTagHelperFeature GetStaticTagHelperFeature(Compi
private static SourceGeneratorProjectEngine GetGenerationProjectEngine(
SourceGeneratorProjectItem item,
IEnumerable<SourceGeneratorProjectItem> imports,
RazorSourceGenerationOptions razorSourceGeneratorOptions,
bool isAddComponentParameterAvailable)
RazorSourceGenerationOptions razorSourceGeneratorOptions)
{
var fileSystem = new VirtualRazorProjectFileSystem();
fileSystem.Add(item);
Expand All @@ -107,7 +106,7 @@ private static SourceGeneratorProjectEngine GetGenerationProjectEngine(
options.SuppressMetadataSourceChecksumAttributes = !razorSourceGeneratorOptions.GenerateMetadataSourceChecksumAttributes;
options.SupportLocalizedComponentNames = razorSourceGeneratorOptions.SupportLocalizedComponentNames;
options.SuppressUniqueIds = razorSourceGeneratorOptions.TestSuppressUniqueIds;
options.SuppressAddComponentParameter = !isAddComponentParameterAvailable;
options.SuppressAddComponentParameter = razorSourceGeneratorOptions.Configuration.SuppressAddComponentParameter;
}));
CompilerFeatures.Register(b);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,21 +2,24 @@
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.

using System;
using System.Collections.Immutable;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Razor.Compiler.CSharp;

namespace Microsoft.NET.Sdk.Razor.SourceGenerators
{
public partial class RazorSourceGenerator
{
private (RazorSourceGenerationOptions?, Diagnostic?) ComputeRazorSourceGeneratorOptions(((AnalyzerConfigOptionsProvider, ParseOptions), bool) pair, CancellationToken ct)
private (RazorSourceGenerationOptions?, Diagnostic?) ComputeRazorSourceGeneratorOptions((((AnalyzerConfigOptionsProvider, ParseOptions), ImmutableArray<MetadataReference>), bool) pair, CancellationToken ct)
{
var ((options, parseOptions), isSuppressed) = pair;
var (((options, parseOptions), references), isSuppressed) = pair;
var globalOptions = options.GlobalOptions;

if (isSuppressed)
Expand All @@ -42,7 +45,15 @@ public partial class RazorSourceGenerator
razorLanguageVersion = RazorLanguageVersion.Latest;
}

var razorConfiguration = new RazorConfiguration(razorLanguageVersion, configurationName ?? "default", Extensions: [], UseConsolidatedMvcViews: true);
var minimalReferences = references
.Where(r => r.Display is { } display && display.EndsWith("Microsoft.AspNetCore.Components.dll", StringComparison.Ordinal))
.ToImmutableArray();

var isComponentParameterSupported = minimalReferences.Length == 0
? false
: CSharpCompilation.Create("components", references: minimalReferences).HasAddComponentParameter();

var razorConfiguration = new RazorConfiguration(razorLanguageVersion, configurationName ?? "default", Extensions: [], UseConsolidatedMvcViews: true, SuppressAddComponentParameter: !isComponentParameterSupported);

var razorSourceGenerationOptions = new RazorSourceGenerationOptions()
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
using System.IO;
using System.Linq;
using Microsoft.AspNetCore.Razor.Language;
using Microsoft.AspNetCore.Razor.Language.Extensions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;

Expand Down Expand Up @@ -44,6 +43,7 @@ public void Initialize(IncrementalGeneratorInitializationContext context)

var razorSourceGeneratorOptions = analyzerConfigOptions
.Combine(parseOptions)
.Combine(metadataRefs.Collect())
.SuppressIfNeeded(isGeneratorSuppressed)
.Select(ComputeRazorSourceGeneratorOptions)
.ReportDiagnostics(context);
Expand Down Expand Up @@ -235,30 +235,16 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
var razorHostOutputsEnabled = analyzerConfigOptions.CheckGlobalFlagSet("EnableRazorHostOutputs");
var withOptionsDesignTime = withOptions.EmptyOrCachedWhen(razorHostOutputsEnabled, false);

var isAddComponentParameterAvailable = metadataRefs
.Where(r => r.Display is { } display && display.EndsWith("Microsoft.AspNetCore.Components.dll", StringComparison.Ordinal))
.Collect()
.Select((refs, _) =>
{
var compilation = CSharpCompilation.Create("components", references: refs);
return compilation.GetTypesByMetadataName("Microsoft.AspNetCore.Components.Rendering.RenderTreeBuilder")
.Any(static t =>
t.DeclaredAccessibility == Accessibility.Public &&
t.GetMembers("AddComponentParameter")
.Any(static m => m.DeclaredAccessibility == Accessibility.Public));
});

IncrementalValuesProvider<(string, SourceGeneratorRazorCodeDocument)> processed(bool designTime)
{
return (designTime ? withOptionsDesignTime : withOptions)
.Combine(isAddComponentParameterAvailable)
.Select((pair, _) =>
{
var (((sourceItem, imports), razorSourceGeneratorOptions), isAddComponentParameterAvailable) = pair;
var ((sourceItem, imports), razorSourceGeneratorOptions) = pair;
RazorSourceGeneratorEventSource.Log.ParseRazorDocumentStart(sourceItem.RelativePhysicalPath);
var projectEngine = GetGenerationProjectEngine(sourceItem, imports, razorSourceGeneratorOptions, isAddComponentParameterAvailable);
var projectEngine = GetGenerationProjectEngine(sourceItem, imports, razorSourceGeneratorOptions);
var document = projectEngine.ProcessInitialParse(sourceItem, designTime);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1160,6 +1160,7 @@ protected override void BuildRenderTree(global::Microsoft.AspNetCore.Components.
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),
Expand Down Expand Up @@ -3260,6 +3261,7 @@ public async Task IncrementalCompilation_OnlyCompilationRuns_When_MetadataRefere
// reference causes the compilation to change so we re-run tag helper discovery there
// but we didn't re-check the actual reference itself
Assert.Collection(eventListener.Events,
e => Assert.Equal("ComputeRazorSourceGeneratorOptions", e.EventName),
e => Assert.Equal("DiscoverTagHelpersFromCompilationStart", e.EventName),
e => Assert.Equal("DiscoverTagHelpersFromCompilationStop", e.EventName));
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"__Version": 5,
"__Version": 6,
"ProjectKey": "C:\\Users\\admin\\location\\Kendo.Mvc.Examples\\obj\\Debug\\net7.0\\",
"FilePath": "C:\\Users\\admin\\location\\Kendo.Mvc.Examples\\Kendo.Mvc.Examples.csproj",
"Configuration": {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
{
"__Version": 5,
"__Version": 6,
"ProjectKey": "C:\\Users\\admin\\location\\blazorserver\\obj\\Debug\\net7.0\\",
"FilePath": "C:\\Users\\admin\\location\\blazorserver\\blazorserver.csproj",
"Configuration": {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -279,7 +279,7 @@ private static async Task ProcessWorkCoreAsync(ImmutableArray<Work> work, Stream
private static async Task ReportUpdateProjectAsync(Stream stream, Project project, ILogger logger, CancellationToken cancellationToken)
{
logger.LogTrace("Serializing information for {projectId}", project.Id);
var projectInfo = await RazorProjectInfoFactory.ConvertAsync(project, logger, cancellationToken).ConfigureAwait(false);
var projectInfo = await RazorProjectInfoFactory.ConvertAsync(project, cancellationToken).ConfigureAwait(false);
if (projectInfo is null)
{
logger.LogTrace("Skipped writing data for {projectId}", project.Id);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,10 @@ public override RazorConfiguration Deserialize(ref MessagePackReader reader, Ser

var configurationName = CachedStringFormatter.Instance.Deserialize(ref reader, options) ?? string.Empty;
var languageVersionText = CachedStringFormatter.Instance.Deserialize(ref reader, options) ?? string.Empty;
var suppressAddComponentParameter = reader.ReadBoolean();
var useConsolidatedMvcViews = reader.ReadBoolean();

count -= 2;

if (reader.NextMessagePackType is MessagePackType.Boolean)
{
reader.ReadBoolean(); // forceRuntimeCodeGeneration
count -= 1;
}
count -= 4;

using var builder = new PooledArrayBuilder<RazorExtension>();

Expand All @@ -45,14 +41,19 @@ public override RazorConfiguration Deserialize(ref MessagePackReader reader, Ser
? version
: RazorLanguageVersion.Version_2_1;

return new(languageVersion, configurationName, extensions);
return new(
languageVersion,
configurationName,
extensions,
UseConsolidatedMvcViews: useConsolidatedMvcViews,
SuppressAddComponentParameter: suppressAddComponentParameter);
}

public override void Serialize(ref MessagePackWriter writer, RazorConfiguration value, SerializerCachingOptions options)
{
// Write 3 values + 1 value per extension.
// Write 4 values + 1 value per extension.
var extensions = value.Extensions;
var count = extensions.Length + 2;
var count = extensions.Length + 4;

writer.WriteArrayHeader(count);

Expand All @@ -67,7 +68,10 @@ public override void Serialize(ref MessagePackWriter writer, RazorConfiguration
CachedStringFormatter.Instance.Serialize(ref writer, value.LanguageVersion.ToString(), options);
}

count -= 2;
writer.Write(value.SuppressAddComponentParameter);
writer.Write(value.UseConsolidatedMvcViews);

count -= 4;

for (var i = 0; i < count; i++)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -9,5 +9,5 @@ internal static class SerializationFormat
// or any of the types that compose it changes. This includes: RazorConfiguration,
// ProjectWorkspaceState, TagHelperDescriptor, and DocumentSnapshotHandle.
// NOTE: If this version is changed, a coordinated insertion is required between Roslyn and Razor for the C# extension.
public const int Version = 5;
public const int Version = 6;
}
Loading

0 comments on commit 6aa9aee

Please sign in to comment.