Thanks to visit codestin.com
Credit goes to github.com

Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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,76 @@
// Copyright (c) All contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Collections.Immutable;
using MessagePack.SourceGenerator.Transforms;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static MessagePack.SourceGenerator.Constants;

namespace MessagePack.SourceGenerator;

[Generator]
public class CompositeResolverGenerator : ISourceGenerator
{
public void Initialize(GeneratorInitializationContext context)
{
context.RegisterForSyntaxNotifications(() => new SyntaxReceiver());
}

public void Execute(GeneratorExecutionContext context)
{
if (context.SyntaxReceiver is not SyntaxReceiver { ClassDeclarationSyntaxes: { Count: > 0 } } receiver)
{
return;
}

// Search for a resolver generator attribute, which may be applied to any type in the compilation.
AnalyzerOptions? options = new() { IsGeneratingSource = true };
foreach (var classDeclByDocument in receiver.ClassDeclarationSyntaxes.GroupBy(td => td.SyntaxTree))
{
SemanticModel semanticModel = context.Compilation.GetSemanticModel(classDeclByDocument.Key, ignoreAccessibility: true);
foreach (TypeDeclarationSyntax typeDecl in classDeclByDocument)
{
if (semanticModel.GetDeclaredSymbol(typeDecl, context.CancellationToken) is INamedTypeSymbol typeSymbol)
{
if (ParseCompositeResolverAttribute(typeSymbol.GetAttributes()) is { } resolverTypes)
{
CompositeResolverTemplate generator = new()
{
ResolverName = typeSymbol.Name,
ResolverNamespace = typeSymbol.ContainingNamespace.Name,
ResolverInstanceExpressions = AnalyzerUtilities.ResolverSymbolToInstanceExpression(semanticModel, resolverTypes).ToArray(),
};
context.AddSource(generator.FileName, generator.TransformText());
}
}
}
}
}

private static INamedTypeSymbol?[]? ParseCompositeResolverAttribute(ImmutableArray<AttributeData> attributes)
{
AttributeData? attribute = attributes.SingleOrDefault(ad =>
ad.AttributeClass?.Name == CompositeResolverAttributeName &&
ad.AttributeClass?.ContainingNamespace.Name == AttributeNamespace);
if (attribute?.ConstructorArguments.Length > 0 && attribute.ConstructorArguments[0].Kind == TypedConstantKind.Array)
{
return attribute.ConstructorArguments[0].Values.Select(tc => tc.Value as INamedTypeSymbol).ToArray();
}

return null;
}

private class SyntaxReceiver : ISyntaxReceiver
{
internal List<ClassDeclarationSyntax> ClassDeclarationSyntaxes { get; } = new();

public void OnVisitSyntaxNode(SyntaxNode syntaxNode)
{
if (syntaxNode is ClassDeclarationSyntax { AttributeLists.Count: > 0 } classDecl)
{
this.ClassDeclarationSyntaxes.Add(classDecl);
}
}
}
}
57 changes: 57 additions & 0 deletions src/MessagePack.SourceGenerator/CompositeResolverGenerator.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
// Copyright (c) All contributors. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using MessagePack.SourceGenerator.Transforms;
using Microsoft.CodeAnalysis;
using static MessagePack.SourceGenerator.Constants;

namespace MessagePack.SourceGenerator;

[Generator(LanguageNames.CSharp)]
public class CompositeResolverGenerator : IIncrementalGenerator
{
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var attributeData = context.SyntaxProvider.ForAttributeWithMetadataName(
$"{AttributeNamespace}.{CompositeResolverAttributeName}",
predicate: static (node, ct) => true,
transform: static (context, ct) => (
ResolverNamespace: context.TargetSymbol.ContainingNamespace.Name,
ResolverName: context.TargetSymbol.Name,
Attribute: context.Attributes.Single()));

var resolvers = attributeData.Combine(context.CompilationProvider).Select((leftRight, cancellationToken) =>
{
var source = leftRight.Left;
var compilation = leftRight.Right;

if (source.Attribute.ConstructorArguments.Length > 0 && source.Attribute.ConstructorArguments[0].Kind == TypedConstantKind.Array)
{
// Get the semantic model we'll use for accessibility checks.
// We'll be accessing these members from a new source file, so it doesn't matter
// which existing syntax tree's semantic model we use to test for accessibility.
SemanticModel semanticModel = compilation.GetSemanticModel(compilation.SyntaxTrees.First());
string[] creationExpressions = AnalyzerUtilities.ResolverSymbolToInstanceExpression(
semanticModel,
source.Attribute.ConstructorArguments[0].Values.Select(tc => tc.Value as INamedTypeSymbol)).ToArray();

return (source.ResolverName, source.ResolverNamespace, CreationExpressions: creationExpressions);
}
else
{
return (source.ResolverName, source.ResolverNamespace, CreationExpressions: Array.Empty<string>());
}
});

context.RegisterSourceOutput(resolvers, (context, source) =>
{
CompositeResolverTemplate generator = new()
{
ResolverName = source.ResolverName,
ResolverNamespace = source.ResolverNamespace,
ResolverInstanceExpressions = source.CreationExpressions,
};
context.AddSource(generator.FileName, generator.TransformText());
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,11 @@
<Compile Include="..\MessagePack.UnityClient\Assets\Scripts\MessagePack\Internal\AutomataKeyGen.cs" LinkBase="MessagePack\Internal" />
<Compile Include="..\MessagePack.UnityClient\Assets\Scripts\MessagePack\SafeBitConverter.cs" LinkBase="MessagePack" />
<Compile Include="..\MessagePack.UnityClient\Assets\Scripts\MessagePack\MessagePackSerializationException.cs" LinkBase="MessagePack" />
<Compile Update="Transforms\CompositeResolverTemplate.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>CompositeResolverTemplate.tt</DependentUpon>
</Compile>
<Compile Update="Transforms\EnumTemplate.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
Expand Down Expand Up @@ -54,6 +59,10 @@
</ItemGroup>

<ItemGroup>
<None Update="Transforms\CompositeResolverTemplate.tt">
<Generator>TextTemplatingFilePreprocessor</Generator>
<LastGenOutput>CompositeResolverTemplate.cs</LastGenOutput>
</None>
<None Update="Transforms\EnumTemplate.tt">
<LastGenOutput>EnumTemplate.cs</LastGenOutput>
<Generator>TextTemplatingFilePreprocessor</Generator>
Expand Down
Loading