Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Calculate SuppressAddComponentParameter in tooling #10763

Merged
merged 30 commits into from
Sep 20, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
30 commits
Select commit Hold shift + click to select a range
c92386f
Add boolean
ryzngard Aug 19, 2024
45334b8
Calculate the value and plumb it through
ryzngard Aug 19, 2024
7fc2352
Bump serialization version
ryzngard Aug 19, 2024
6794130
Add missing property write for json
ryzngard Aug 19, 2024
e685ca5
PR feedback
ryzngard Aug 20, 2024
5cca44c
Missed some
ryzngard Aug 20, 2024
017a513
Space and bump json version
ryzngard Aug 20, 2024
c77bce3
Fix test
ryzngard Aug 20, 2024
a3bab60
Fix test data and bug in message pack formatter
ryzngard Aug 20, 2024
cc8f604
No need to update this...
ryzngard Aug 21, 2024
d3647a9
Remove existing configurable code generation option and just use it f…
chsienki Aug 26, 2024
eca23cb
Merge branch 'main' into SuppressAddComponentParameter
ryzngard Aug 29, 2024
1f23c67
Remove unused member
ryzngard Aug 29, 2024
353e217
PR feedback
ryzngard Aug 29, 2024
dcc4fe8
Update src/Shared/Microsoft.AspNetCore.Razor.Serialization.Json/Objec…
ryzngard Sep 3, 2024
3d2f246
Undo unrelated changes
ryzngard Sep 3, 2024
b108d41
Fix compilation issue and add debug assert
ryzngard Sep 3, 2024
4750b83
Merge branch 'main' into SuppressAddComponentParameter
ryzngard Sep 5, 2024
66c1790
Update src/Razor/src/Microsoft.AspNetCore.Razor.ProjectEngineHost/Uti…
ryzngard Sep 5, 2024
73cfa13
Update src/Razor/src/Microsoft.CodeAnalysis.Remote.Razor/ProjectSyste…
ryzngard Sep 5, 2024
41f69f9
Merge branch 'SuppressAddComponentParameter' of https://github.com/ry…
ryzngard Sep 5, 2024
4cf5339
Merge branch 'main' into SuppressAddComponentParameter
ryzngard Sep 10, 2024
4347cc3
Serialize UseConsolidatedMvcViews
ryzngard Sep 10, 2024
1e2b4b0
Fix compilation. Move server flags to end since they are much more in…
ryzngard Sep 10, 2024
5681389
Update RemoteProjectSnapshot.cs
ryzngard Sep 10, 2024
b28e503
Merge branch 'main' into SuppressAddComponentParameter
ryzngard Sep 18, 2024
15e1635
Set flag based on configuration
ryzngard Sep 18, 2024
72d5e84
Set options builder
ryzngard Sep 18, 2024
2205c2e
PR feedback. Reduce references for compilation
ryzngard Sep 18, 2024
4117df5
Fix tests
ryzngard Sep 18, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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;
ryzngard marked this conversation as resolved.
Show resolved Hide resolved
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)
ryzngard marked this conversation as resolved.
Show resolved Hide resolved
{
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();
Comment on lines +48 to +54
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💭 Since this is the source generator, would it make sense to avoid the extra allocation and array copy caused by ToImmutableArray()? Something like this would effectively be allocation free until its known that there are any referenecs.

Suggested change
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();
using var minimalReferences = new PooledArrayBuilder<MetadataReference>(capacity: references.Length);
foreach (var reference in references)
{
if (reference.Display is { } display &&
display.EndsWith("Microsoft.AspNetCore.Components.dll", StringComparison.Ordinal))
{
minimalReferences.Add(reference);
}
}
var isComponentParameterSupported = minimalReferences.Count > 0
? CSharpCompilation.Create("components", references: minimalReferences.DrainToImmutable()).HasAddComponentParameter();
: false;


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);
ryzngard marked this conversation as resolved.
Show resolved Hide resolved
}

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);
ryzngard marked this conversation as resolved.
Show resolved Hide resolved
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;
ryzngard marked this conversation as resolved.
Show resolved Hide resolved
}
Loading