Skip to content

Commit

Permalink
Better performance Source Generator (#172)
Browse files Browse the repository at this point in the history
  • Loading branch information
thomhurst authored May 16, 2024
1 parent cfe1c4d commit 6e02dbe
Show file tree
Hide file tree
Showing 3 changed files with 7 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.SourceGenerators.Testing.XUnit" Version="1.1.1" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.0.1" />
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Workspaces" Version="4.3.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.2.0" />
<PackageReference Include="xunit" Version="2.4.1" />
<PackageReference Include="xunit.runner.visualstudio" Version="2.4.5">
Expand Down
2 changes: 1 addition & 1 deletion OneOf.SourceGenerator/OneOf.SourceGenerator.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.0.1">
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="4.3.1">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
Expand Down
9 changes: 5 additions & 4 deletions OneOf.SourceGenerator/OneOfGenerator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ public void Initialize(IncrementalGeneratorInitializationContext context)
context.RegisterPostInitializationOutput(ctx => ctx.AddSource($"{AttributeName}.g.cs", _attributeText));

var oneOfClasses = context.SyntaxProvider
.CreateSyntaxProvider(
.ForAttributeWithMetadataName(
fullyQualifiedMetadataName: $"{AttributeNamespace}.{AttributeName}",
predicate: static (s, _) => IsSyntaxTargetForGeneration(s),
transform: static (ctx, _) => GetSemanticTargetForGeneration(ctx))
.Where(static m => m is not null)
Expand All @@ -44,13 +45,13 @@ public void Initialize(IncrementalGeneratorInitializationContext context)

static bool IsSyntaxTargetForGeneration(SyntaxNode node)
{
return node is ClassDeclarationSyntax {AttributeLists: {Count: > 0}} classDeclarationSyntax
return node is ClassDeclarationSyntax classDeclarationSyntax
&& classDeclarationSyntax.Modifiers.Any(SyntaxKind.PartialKeyword);
}

static INamedTypeSymbol? GetSemanticTargetForGeneration(GeneratorSyntaxContext context)
static INamedTypeSymbol? GetSemanticTargetForGeneration(GeneratorAttributeSyntaxContext context)
{
var symbol = context.SemanticModel.GetDeclaredSymbol(context.Node);
var symbol = context.TargetSymbol;

if (symbol is not INamedTypeSymbol namedTypeSymbol)
{
Expand Down

0 comments on commit 6e02dbe

Please sign in to comment.