Repository navigation
feat(discriminated-union): closed-DU source generator #115
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
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
77 changes: 77 additions & 0 deletions
77
src/ANcpLua.DiscriminatedUnion/ANcpLua.Analyzers.DiscriminatedUnion.csproj
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,77 @@ | ||
| <Project Sdk="Microsoft.NET.Sdk"> | ||
| <PropertyGroup> | ||
| <TargetFramework>netstandard2.0</TargetFramework> | ||
| <LangVersion>latest</LangVersion> | ||
| <Nullable>enable</Nullable> | ||
| <ImplicitUsings>disable</ImplicitUsings> | ||
| <RootNamespace>ANcpLua.Analyzers.DiscriminatedUnion</RootNamespace> | ||
| <Description>Roslyn incremental source generator that turns a [DiscriminatedUnion]-marked partial record + nested partial record cases into a closed F#-style discriminated union: private base constructor that locks inheritance to the nested cases, sealed case records, and exhaustive Match<TResult> / Switch dispatchers. The marker attribute is emitted into the consumer compilation via post-init, so a single PackageReference is enough.</Description> | ||
| <PackageTags>roslyn;source-generator;discriminated-union;closed-union;sum-type;adt;pattern-matching</PackageTags> | ||
|
|
||
| <!-- Analyzer package settings --> | ||
| <IncludeBuildOutput>false</IncludeBuildOutput> | ||
| <DevelopmentDependency>true</DevelopmentDependency> | ||
| <EnforceExtendedAnalyzerRules>true</EnforceExtendedAnalyzerRules> | ||
|
|
||
| <!-- Ensure dependencies are copied to output for bundling --> | ||
| <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies> | ||
|
|
||
| <!-- Suppress warnings: | ||
| RS1035: Banned symbols from shared Roslyn.Utilities sources | ||
| RS1025/RS1026/RS1041: Analyzer registration patterns - intentional design | ||
| RS0030: Banned APIs - polyfill source must reference the API it replaces | ||
| CS1591: XML docs - generator internals | ||
| CA1308: ToLowerInvariant - intentional for C# code generation --> | ||
| <NoWarn>$(NoWarn);RS1035;RS1025;RS1026;RS1041;RS0030;CS1591;CA1308</NoWarn> | ||
| </PropertyGroup> | ||
|
|
||
| <ItemGroup> | ||
| <Using Include="System"/> | ||
| <Using Include="System.Collections.Generic"/> | ||
| <Using Include="System.Linq"/> | ||
| <Using Include="System.Threading"/> | ||
| <Using Include="ANcpLua.Roslyn.Utilities"/> | ||
| <Using Include="ANcpLua.Roslyn.Utilities.Models"/> | ||
| <Using Include="Microsoft.CodeAnalysis"/> | ||
| <Using Include="Microsoft.CodeAnalysis.CSharp"/> | ||
| <Using Include="Microsoft.CodeAnalysis.CSharp.Syntax"/> | ||
| <Using Include="System.Collections.Immutable"/> | ||
| <Using Include="System.Diagnostics.CodeAnalysis"/> | ||
| <Using Include="System.Text"/> | ||
| </ItemGroup> | ||
|
|
||
| <!-- Polyfills from core Roslyn.Utilities (internal, must be linked per-project) --> | ||
| <ItemGroup> | ||
| <Compile Include="..\ANcpLua.Roslyn.Utilities\Polyfills\LanguageFeatures\IsExternalInit.cs" Link="Polyfills\IsExternalInit.cs"/> | ||
| <Compile Include="..\ANcpLua.Roslyn.Utilities\Polyfills\IndexRange\Index.cs" Link="Polyfills\Index.cs"/> | ||
| <Compile Include="..\ANcpLua.Roslyn.Utilities\Polyfills\IndexRange\Range.cs" Link="Polyfills\Range.cs"/> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <ProjectReference Include="..\ANcpLua.Roslyn.Utilities\ANcpLua.Roslyn.Utilities.csproj" PrivateAssets="all"/> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <PackageReference Include="Microsoft.CodeAnalysis.Analyzers" PrivateAssets="all"> | ||
| <IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets> | ||
| </PackageReference> | ||
| <PackageReference Include="Microsoft.CodeAnalysis.CSharp" PrivateAssets="all"/> | ||
| </ItemGroup> | ||
|
|
||
| <ItemGroup> | ||
| <AdditionalFiles Include="AnalyzerReleases.Shipped.md"/> | ||
| <AdditionalFiles Include="AnalyzerReleases.Unshipped.md"/> | ||
| </ItemGroup> | ||
|
|
||
| <!-- Pack analyzer DLLs into analyzers/dotnet/cs/ --> | ||
| <PropertyGroup> | ||
| <TargetsForTfmSpecificContentInPackage>$(TargetsForTfmSpecificContentInPackage);_AddDiscriminatedUnionAnalyzersToPackage</TargetsForTfmSpecificContentInPackage> | ||
| </PropertyGroup> | ||
|
|
||
| <Target Name="_AddDiscriminatedUnionAnalyzersToPackage"> | ||
| <ItemGroup> | ||
| <TfmSpecificPackageFile Include="$(OutputPath)ANcpLua.Analyzers.DiscriminatedUnion.dll" PackagePath="analyzers/dotnet/cs"/> | ||
| <TfmSpecificPackageFile Include="$(OutputPath)ANcpLua.Roslyn.Utilities.dll" PackagePath="analyzers/dotnet/cs"/> | ||
| </ItemGroup> | ||
| </Target> | ||
| </Project> |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,2 @@ | ||
| ; Shipped analyzer releases | ||
| ; https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md |
11 changes: 11 additions & 0 deletions
11
src/ANcpLua.DiscriminatedUnion/AnalyzerReleases.Unshipped.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,11 @@ | ||
| ; Unshipped analyzer release | ||
| ; https://github.com/dotnet/roslyn-analyzers/blob/main/src/Microsoft.CodeAnalysis.Analyzers/ReleaseTrackingAnalyzers.Help.md | ||
|
|
||
| ### New Rules | ||
|
|
||
| Rule ID | Category | Severity | Notes | ||
| ---------|----------|----------|---------------------------------------------------------------- | ||
| AL0300 | Usage | Error | DiscriminatedUnion root must be a partial record | ||
| AL0301 | Usage | Error | DiscriminatedUnion root must declare at least one nested partial record case | ||
| AL0302 | Usage | Error | DiscriminatedUnion case must be a partial record nested in the union root | ||
| AL0303 | Usage | Error | DiscriminatedUnion root must not declare primary-constructor parameters |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| namespace ANcpLua.Analyzers.DiscriminatedUnion; | ||
|
|
||
| internal static class DiagnosticDescriptors | ||
| { | ||
| public static readonly DiagnosticDescriptor RootMustBePartialRecord = new( | ||
| "AL0300", | ||
| "DiscriminatedUnion root must be a partial record", | ||
| "Type '{0}' must be declared as 'partial record' to use [DiscriminatedUnion]", | ||
| "Usage", | ||
| DiagnosticSeverity.Error, | ||
| true); | ||
|
|
||
| public static readonly DiagnosticDescriptor RootMustHaveCases = new( | ||
| "AL0301", | ||
| "DiscriminatedUnion root must declare at least one nested partial record case", | ||
| "Type '{0}' is marked [DiscriminatedUnion] but contains no nested partial record cases", | ||
| "Usage", | ||
| DiagnosticSeverity.Error, | ||
| true); | ||
|
|
||
| public static readonly DiagnosticDescriptor CaseMustBeNestedPartialRecord = new( | ||
| "AL0302", | ||
| "DiscriminatedUnion case must be a partial record nested in the union root", | ||
| "Member '{0}' inside [DiscriminatedUnion] root '{1}' must be declared as 'partial record' to participate as a case", | ||
| "Usage", | ||
| DiagnosticSeverity.Error, | ||
| true); | ||
|
|
||
| public static readonly DiagnosticDescriptor RootMustNotHavePrimaryCtor = new( | ||
| "AL0303", | ||
| "DiscriminatedUnion root must not declare primary-constructor parameters", | ||
| "Type '{0}' is marked [DiscriminatedUnion] and must not declare a primary constructor — the generator emits a private parameterless constructor that closes the hierarchy to nested cases", | ||
| "Usage", | ||
| DiagnosticSeverity.Error, | ||
| true); | ||
| } |
75 changes: 75 additions & 0 deletions
75
src/ANcpLua.DiscriminatedUnion/DiscriminatedUnionGenerator.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,75 @@ | ||
| using ANcpLua.Analyzers.DiscriminatedUnion.Extraction; | ||
| using ANcpLua.Analyzers.DiscriminatedUnion.Generation; | ||
|
|
||
| namespace ANcpLua.Analyzers.DiscriminatedUnion; | ||
|
|
||
| /// <summary> | ||
| /// Turns a <c>[DiscriminatedUnion]</c>-marked partial record root and its nested partial record | ||
| /// cases into a closed F#-style discriminated union: a <c>private</c> parameterless base | ||
| /// constructor (lock to nested cases), <c>sealed</c> case records derived from the root, and | ||
| /// exhaustive <c>Match<TResult></c> / <c>Switch</c> dispatchers that the compiler enforces | ||
| /// to handle every case. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// Usage: declare the union root as <c>partial record</c> with one or more nested | ||
| /// <c>partial record</c> cases and apply <c>[DiscriminatedUnion]</c>. The generator emits the | ||
| /// base constructor, sealed inheritance, and dispatchers into a separate partial declaration. | ||
| /// The marker attribute itself is emitted via | ||
| /// <see cref="IncrementalGeneratorPostInitializationContext.AddSource(string, string)" /> so | ||
| /// consumers do not need a separate attribute package. | ||
| /// </remarks> | ||
| [Generator] | ||
| public sealed class DiscriminatedUnionGenerator : IIncrementalGenerator | ||
| { | ||
| internal const string AttributeNamespace = "ANcpLua.Analyzers.DiscriminatedUnion"; | ||
| internal const string AttributeShortName = "DiscriminatedUnionAttribute"; | ||
| internal const string AttributeFullName = AttributeNamespace + "." + AttributeShortName; | ||
|
|
||
| private const string AttributeSource = """ | ||
| // <auto-generated/> | ||
| #nullable enable | ||
|
|
||
| namespace ANcpLua.Analyzers.DiscriminatedUnion; | ||
|
|
||
| /// <summary> | ||
| /// Marks a partial record as the root of a closed discriminated union. Each nested | ||
| /// <c>partial record</c> declared inside the marked type becomes a sealed case derived from | ||
| /// the root. The generator emits a private parameterless base constructor that locks | ||
| /// inheritance to the nested cases, plus exhaustive <c>Match<TResult></c> and | ||
| /// <c>Switch</c> dispatchers. | ||
| /// </summary> | ||
| /// <remarks> | ||
| /// The decorated type must be declared <c>partial record</c> and must not declare a primary | ||
| /// constructor. Cases must be declared as <c>partial record</c> directly nested inside the | ||
| /// root. | ||
| /// </remarks> | ||
| [global::System.AttributeUsage( | ||
| global::System.AttributeTargets.Class, | ||
| AllowMultiple = false, | ||
| Inherited = false)] | ||
| [global::System.Diagnostics.Conditional("ANCPLUA_DISCRIMINATED_UNION_USAGES")] | ||
| internal sealed class DiscriminatedUnionAttribute : global::System.Attribute | ||
| { | ||
| } | ||
|
|
||
| """; | ||
|
|
||
| public void Initialize(IncrementalGeneratorInitializationContext context) | ||
| { | ||
| context.RegisterPostInitializationOutput(static ctx => | ||
| ctx.AddSource("DiscriminatedUnionAttribute.g.cs", AttributeSource)); | ||
|
|
||
| var flows = context.SyntaxProvider.ForAttributeWithMetadataName( | ||
| AttributeFullName, | ||
| static (node, _) => node is RecordDeclarationSyntax, | ||
| static (ctx, ct) => UnionExtractor.Extract(ctx, ct)); | ||
|
|
||
| var models = flows.ReportAndStop(context); | ||
|
|
||
| var files = models | ||
| .Select(static (model, _) => UnionOutputGenerator.Generate(model)) | ||
| .CollectAsEquatableArray(); | ||
|
|
||
| files.AddSources(context); | ||
| } | ||
| } |
93 changes: 93 additions & 0 deletions
93
src/ANcpLua.DiscriminatedUnion/Extraction/UnionExtractor.cs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,93 @@ | ||
| using ANcpLua.Analyzers.DiscriminatedUnion.Models; | ||
|
|
||
| namespace ANcpLua.Analyzers.DiscriminatedUnion.Extraction; | ||
|
|
||
| internal static class UnionExtractor | ||
| { | ||
| public static DiagnosticFlow<UnionModel> Extract( | ||
| GeneratorAttributeSyntaxContext context, | ||
| CancellationToken cancellationToken) | ||
| { | ||
| cancellationToken.ThrowIfCancellationRequested(); | ||
|
|
||
| if (context.TargetSymbol is not INamedTypeSymbol root || | ||
| context.TargetNode is not RecordDeclarationSyntax rootSyntax) | ||
| return DiagnosticFlow.Fail<UnionModel>(DiagnosticInfo.Create( | ||
| DiagnosticDescriptors.RootMustBePartialRecord, | ||
| context.TargetNode, | ||
| context.TargetSymbol?.Name ?? "<unknown>")); | ||
|
|
||
| if (!rootSyntax.Modifiers.Any(SyntaxKind.PartialKeyword) || | ||
| rootSyntax.Kind() is not SyntaxKind.RecordDeclaration) | ||
| return DiagnosticFlow.Fail<UnionModel>(DiagnosticInfo.Create( | ||
| DiagnosticDescriptors.RootMustBePartialRecord, | ||
| rootSyntax, | ||
| root.Name)); | ||
|
|
||
| if (rootSyntax.ParameterList is { Parameters.Count: > 0 }) | ||
| return DiagnosticFlow.Fail<UnionModel>(DiagnosticInfo.Create( | ||
| DiagnosticDescriptors.RootMustNotHavePrimaryCtor, | ||
| rootSyntax, | ||
| root.Name)); | ||
|
|
||
| var nonRecordMembers = rootSyntax.Members | ||
| .OfType<TypeDeclarationSyntax>() | ||
| .Where(t => t is not RecordDeclarationSyntax recordMember || recordMember.Kind() is not SyntaxKind.RecordDeclaration) | ||
| .ToArray(); | ||
|
|
||
| foreach (var bad in nonRecordMembers) | ||
| return DiagnosticFlow.Fail<UnionModel>(DiagnosticInfo.Create( | ||
| DiagnosticDescriptors.CaseMustBeNestedPartialRecord, | ||
| bad, | ||
| bad.Identifier.Text, | ||
| root.Name)); | ||
|
|
||
| var caseSyntaxes = rootSyntax.Members | ||
| .OfType<RecordDeclarationSyntax>() | ||
| .Where(r => r.Kind() is SyntaxKind.RecordDeclaration) | ||
| .ToArray(); | ||
|
|
||
| if (caseSyntaxes.Length == 0) | ||
| return DiagnosticFlow.Fail<UnionModel>(DiagnosticInfo.Create( | ||
| DiagnosticDescriptors.RootMustHaveCases, | ||
| rootSyntax, | ||
| root.Name)); | ||
|
|
||
| foreach (var caseSyntax in caseSyntaxes) | ||
| if (!caseSyntax.Modifiers.Any(SyntaxKind.PartialKeyword)) | ||
| return DiagnosticFlow.Fail<UnionModel>(DiagnosticInfo.Create( | ||
| DiagnosticDescriptors.CaseMustBeNestedPartialRecord, | ||
| caseSyntax, | ||
| caseSyntax.Identifier.Text, | ||
| root.Name)); | ||
|
|
||
| var cases = caseSyntaxes | ||
| .Select(c => new UnionCase(c.Identifier.Text, ToCamelCase(c.Identifier.Text))) | ||
| .ToArray() | ||
| .ToEquatableArray(); | ||
|
|
||
| var ns = root.ContainingNamespace.IsGlobalNamespace | ||
| ? string.Empty | ||
| : root.ContainingNamespace.ToDisplayString(); | ||
|
|
||
| var typeParamList = rootSyntax.TypeParameterList?.ToString() ?? string.Empty; | ||
|
|
||
| return DiagnosticFlow.Ok(new UnionModel( | ||
| ns, | ||
| root.Name, | ||
| typeParamList, | ||
| root.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), | ||
| cases)); | ||
| } | ||
|
|
||
| private static string ToCamelCase(string name) | ||
| { | ||
| if (string.IsNullOrEmpty(name)) return name; | ||
| var first = char.ToLowerInvariant(name[0]); | ||
| var camel = first + name.Substring(1); | ||
| return SyntaxFacts.GetKeywordKind(camel) is SyntaxKind.None && | ||
| SyntaxFacts.GetContextualKeywordKind(camel) is SyntaxKind.None | ||
| ? camel | ||
| : "@" + camel; | ||
| } | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This extractor only reads
rootSyntax.Membersfrom the single declaration that carries[DiscriminatedUnion], so valid cases declared in anotherpartialpart of the same root are ignored. In that layout, the generator can emitAL0301(“no cases”) or generate incompleteMatch/Switchsignatures that omit real cases, which breaks otherwise-correct partial union definitions split across files.Useful? React with 👍 / 👎.