~ruther/NosSmooth

ref: 4e64d6b7bff7bb5d8d132e1ddbc3dc7f8002a79b NosSmooth/Core/NosSmooth.PacketSerializersGenerator/SourceGenerator.cs -rw-r--r-- 9.4 KiB
4e64d6b7 — František Boháček fix: iterate for to last parameter 3 years ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
//
//  SourceGenerator.cs
//
//  Copyright (c) František Boháček. All rights reserved.
//  Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.CodeDom.Compiler;
using System.Diagnostics;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using NosSmooth.PacketSerializersGenerator.AttributeGenerators;
using NosSmooth.PacketSerializersGenerator.Data;
using NosSmooth.PacketSerializersGenerator.Errors;
using NosSmooth.PacketSerializersGenerator.Extensions;

namespace NosSmooth.PacketSerializersGenerator;

/// <summary>
/// Generates ITypeGenerator for packets that are marked with NosSmooth.Packets.Attributes.GenerateSerializerAttribute.
/// </summary>
/// <remarks>
/// The packets to create serializer for have to be records that specify PacketIndices in the constructor.
/// </remarks>
[Generator]
public class SourceGenerator : ISourceGenerator
{
    /// <summary>
    /// Initializes a new instance of the <see cref="SourceGenerator"/> class.
    /// </summary>
    public SourceGenerator()
    {
        _generators = new List<IParameterGenerator>
        (
            new IParameterGenerator[]
            {
                new PacketIndexAttributeGenerator(),
                new PacketListIndexAttributeGenerator(),
                new PacketContextListAttributeGenerator(),
            }
        );
    }

    private readonly List<IParameterGenerator> _generators;

    /// <inheritdoc />
    public void Initialize(GeneratorInitializationContext context)
    {
    }

    private IEnumerable<RecordDeclarationSyntax> GetPacketRecords(Compilation compilation, SyntaxTree tree)
    {
        var semanticModel = compilation.GetSemanticModel(tree);
        var root = tree.GetRoot();

        return root
            .DescendantNodes()
            .OfType<RecordDeclarationSyntax>()
            .Where
            (
                x => x.AttributeLists.Any
                    (y => y.ContainsAttribute(semanticModel, Constants.GenerateSourceAttributeClass))
            );
    }

    /// <inheritdoc />
    public void Execute(GeneratorExecutionContext context)
    {
        var packetRecords = context.Compilation.SyntaxTrees
            .SelectMany(x => GetPacketRecords(context.Compilation, x));

        foreach (var packetRecord in packetRecords)
        {
            if (packetRecord is not null)
            {
                using var stringWriter = new StringWriter();
                using var writer = new IndentedTextWriter(stringWriter, "    ");
                var generatedResult = GeneratePacketSerializer(writer, context.Compilation, packetRecord);
                if (generatedResult is not null)
                {
                    if (generatedResult is DiagnosticError diagnosticError)
                    {
                        context.ReportDiagnostic
                        (
                            Diagnostic.Create
                            (
                                new DiagnosticDescriptor
                                (
                                    diagnosticError.Id,
                                    diagnosticError.Title,
                                    diagnosticError.MessageFormat,
                                    "Serialization",
                                    DiagnosticSeverity.Error,
                                    true
                                ),
                                Location.Create(diagnosticError.Tree, diagnosticError.Span),
                                diagnosticError.Parameters.ToArray()
                            )
                        );
                    }
                    else if (generatedResult is not null)
                    {
                        throw new Exception(generatedResult.Message);
                    }

                    continue;
                }

                context.AddSource
                (
                    $"{packetRecord.Identifier.NormalizeWhitespace().ToFullString()}Converter.g.cs",
                    stringWriter.GetStringBuilder().ToString()
                );
            }
        }
    }

    private IError? GeneratePacketSerializer
        (IndentedTextWriter textWriter, Compilation compilation, RecordDeclarationSyntax packetClass)
    {
        var semanticModel = compilation.GetSemanticModel(packetClass.SyntaxTree);

        var name = packetClass.Identifier.NormalizeWhitespace().ToFullString();
        var @namespace = packetClass.GetPrefix();

        var constructor = (ParameterListSyntax?)packetClass.ChildNodes()
            .FirstOrDefault(x => x.IsKind(SyntaxKind.ParameterList));

        if (constructor is null)
        {
            return new DiagnosticError
            (
                "SG0001",
                "Packet without constructor",
                "The packet class {0} does not have any constructors to use for packet serializer.",
                packetClass.SyntaxTree,
                packetClass.FullSpan,
                new List<object?>
                (
                    new[]
                    {
                        packetClass.Identifier.NormalizeWhitespace().ToFullString()
                    }
                )
            );
        }

        var parameters = constructor.Parameters;
        var orderedParameters = new List<ParameterInfo>();
        int constructorIndex = 0;
        foreach (var parameter in parameters)
        {
            var createError = CreateParameterInfo
            (
                packetClass,
                parameter,
                semanticModel,
                constructorIndex,
                out var parameterInfo
            );

            if (createError is not null)
            {
                return createError;
            }

            if (parameterInfo is not null)
            {
                orderedParameters.Add(parameterInfo);
            }

            constructorIndex++;
        }

        orderedParameters = orderedParameters.OrderBy(x => x.PacketIndex).ToList();
        var packetInfo = new PacketInfo
        (
            compilation,
            packetClass,
            semanticModel,
            new Parameters(orderedParameters),
            @namespace,
            name
        );

        var generator = new PacketConverterGenerator(packetInfo, _generators);
        var generatorError = generator.Generate(textWriter);

        return generatorError;
    }

    private IError? CreateParameterInfo
    (
        RecordDeclarationSyntax packet,
        ParameterSyntax parameter,
        SemanticModel semanticModel,
        int constructorIndex,
        out ParameterInfo? parameterInfo
    )
    {
        var name = packet.Identifier.NormalizeWhitespace().ToFullString();

        parameterInfo = null;
        var attributes = parameter.AttributeLists
            .Where(x => x.ContainsAttribute(semanticModel, Constants.PacketAttributesClassRegex))
            .SelectMany
            (
                x
                    => x.Attributes.Where
                    (
                        y => Regex.IsMatch
                            (semanticModel.GetTypeInfo(y).Type?.ToString()!, Constants.PacketAttributesClassRegex)
                    )
            )
            .ToList();

        if (attributes.Count == 0)
        {
            return new DiagnosticError
            (
                "SG0003",
                "Packet constructor parameter without packet attribute",
                "Could not find PacketIndexAttribute on {0} parameter in class {1}. Parameters without PacketIndexAttribute aren't allowed.",
                parameter.SyntaxTree,
                parameter.FullSpan,
                new List<object?>
                (
                    new[]
                    {
                        parameter.Identifier.NormalizeWhitespace().ToFullString(),
                        name
                    }
                )
            );
        }

        var attribute = attributes.First();
        var index = ushort.Parse(attribute.ArgumentList!.Arguments[0].GetValue(semanticModel)!.ToString());

        List<AttributeInfo> attributeInfos = attributes
            .Select(x => CreateAttributeInfo(x, semanticModel))
            .ToList();

        parameterInfo = new ParameterInfo
        (
            parameter,
            semanticModel.GetTypeInfo(parameter.Type!).Type!,
            parameter.Type is NullableTypeSyntax,
            attributeInfos,
            parameter.Identifier.NormalizeWhitespace().ToFullString(),
            constructorIndex,
            index
        );
        return null;
    }

    private AttributeInfo CreateAttributeInfo(AttributeSyntax attribute, SemanticModel semanticModel)
    {
        var namedArguments = new Dictionary<string, object?>();
        var arguments = new List<object?>();

        foreach (var argument in attribute.ArgumentList!.Arguments)
        {
            var argumentName = argument.NameEquals?.Name.Identifier.NormalizeWhitespace().ToFullString();
            var value = argument.GetValue(semanticModel);

            if (argumentName is not null)
            {
                namedArguments.Add(argumentName, value);
            }
            else
            {
                arguments.Add(value);
            }
        }

        return new AttributeInfo
        (
            attribute,
            semanticModel.GetTypeInfo(attribute).Type?.ToString()!,
            arguments,
            namedArguments
        );
    }
}
Do not follow this link