-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathContentSerializerGenerator.cs
More file actions
337 lines (293 loc) · 12.5 KB
/
Copy pathContentSerializerGenerator.cs
File metadata and controls
337 lines (293 loc) · 12.5 KB
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
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Syntax;
namespace FEZRepacker.Core.SourceGen;
[Generator]
public sealed class ContentSerializerGenerator : IIncrementalGenerator
{
private const string XnbReaderTypeAttributeName = "FEZRepacker.Core.Definitions.Game.XnbReaderTypeAttribute";
private const string XnbPropertyAttributeName = "FEZRepacker.Core.Definitions.Game.XnbPropertyAttribute";
private struct XnbTypeInfo
{
public string TypeName;
public string TypeFullName;
public string QualifierString;
public List<string> GenericParameters;
public List<XnbPropertyInfo> Properties;
}
private struct XnbPropertyInfo
{
public string Name;
public string TypeFullName;
public bool IsNullable;
public bool IsReferenceType;
public int Order;
public bool UseConverter;
public bool Optional;
public bool SkipIdentifier;
}
public void Initialize(IncrementalGeneratorInitializationContext context)
{
var xnbTypeInfos = context.SyntaxProvider
.CreateSyntaxProvider((node, _) => node is TypeDeclarationSyntax { AttributeLists.Count: > 0 }, GetXnbType)
.Where(m => m != null);
context.RegisterSourceOutput(xnbTypeInfos, (ctx, xnbTypeInfo) =>
CreateSerializerSourceFile(ctx, xnbTypeInfo!.Value));
}
private static XnbTypeInfo? GetXnbType(GeneratorSyntaxContext ctx, CancellationToken ct)
{
if (ctx.SemanticModel.GetDeclaredSymbol(ctx.Node, ct) is not INamedTypeSymbol typeSymbol)
{
return null;
}
var xnbReaderTypeAttribute = typeSymbol.GetAttributes()
.FirstOrDefault(a => a.AttributeClass?.ToDisplayString() == XnbReaderTypeAttributeName);
if (xnbReaderTypeAttribute is not {ConstructorArguments.Length: > 0})
{
return null;
}
bool isPrivate = xnbReaderTypeAttribute.NamedArguments
.FirstOrDefault(x => x.Key == "IsPrivate").Value.Value is true;
if (isPrivate)
{
return null;
}
var qualifierString = xnbReaderTypeAttribute.ConstructorArguments[0].Value as string ?? string.Empty;
var genericParameters = typeSymbol.TypeParameters.Select(tp => tp.Name).ToList();
var properties = new List<XnbPropertyInfo>();
foreach (var member in typeSymbol.GetMembers().OfType<IPropertySymbol>())
{
ct.ThrowIfCancellationRequested();
var xnbPropertyAttribute = member.GetAttributes()
.FirstOrDefault(a => a.AttributeClass?.ToDisplayString() == XnbPropertyAttributeName);
if (xnbPropertyAttribute == null)
{
continue;
}
int order = (int?)(xnbPropertyAttribute.ConstructorArguments.FirstOrDefault()).Value ?? 0;
bool useConverter = xnbPropertyAttribute.NamedArguments
.FirstOrDefault(x => x.Key == "UseConverter").Value.Value is true;
bool optional = xnbPropertyAttribute.NamedArguments
.FirstOrDefault(x => x.Key == "Optional").Value.Value is true;
bool skipIdentifier = xnbPropertyAttribute.NamedArguments
.FirstOrDefault(x => x.Key == "SkipIdentifier").Value.Value is true;
ITypeSymbol underlyingPropertyType = member.Type;
bool propertyNullable = false;
if (member.Type is INamedTypeSymbol {ConstructedFrom.SpecialType: SpecialType.System_Nullable_T} namedType)
{
underlyingPropertyType = namedType.TypeArguments[0];
propertyNullable = true;
}
properties.Add(new XnbPropertyInfo
{
Name = member.Name,
TypeFullName = underlyingPropertyType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
IsNullable = propertyNullable,
IsReferenceType = !propertyNullable && member.Type.IsReferenceType,
Order = order,
UseConverter = useConverter,
Optional = optional,
SkipIdentifier = skipIdentifier
});
}
properties.Sort((a, b) => a.Order.CompareTo(b.Order));
return new XnbTypeInfo
{
TypeName = typeSymbol.Name,
TypeFullName = typeSymbol.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat),
QualifierString = qualifierString,
Properties = properties,
GenericParameters = genericParameters
};
}
private static void CreateSerializerSourceFile(SourceProductionContext ctx, XnbTypeInfo model)
{
var cb = new CodeStringBuilder();
EmitSerializer(cb, model);
ctx.AddSource($"{model.TypeName}ContentSerializer.g.cs", cb.ToString());
}
private static void EmitSerializer(CodeStringBuilder cb, XnbTypeInfo xnbTypeInfo)
{
cb.AppendLine("// <auto-generated/>");
cb.AppendLine("// FEZRepacker.Core.SourceGen output");
cb.AppendLine("#nullable enable");
cb.AppendLine();
cb.AppendLine("using FEZRepacker.Core;");
cb.AppendLine("using FEZRepacker.Core.Helpers;");
cb.AppendLine("using FEZRepacker.Core.XNB;");
cb.AppendLine();
cb.AppendLine("namespace FEZRepacker.Core.XNB.ContentSerialization;");
cb.AppendLine();
cb.Append($"internal sealed class {ConstructSerializerName(xnbTypeInfo)}");
cb.AppendLine($" : XnbContentSerializer<{xnbTypeInfo.TypeFullName}>");
cb.BeginCodeBlock();
{
EmitConstructor(cb, xnbTypeInfo);
cb.AppendLine();
EmitDeserialize(cb, xnbTypeInfo);
cb.AppendLine();
EmitSerialize(cb, xnbTypeInfo);
}
cb.EndCodeBlock();
}
private static string ConstructSerializerName(XnbTypeInfo xnbTypeInfo)
{
var name = $"{xnbTypeInfo.TypeName}ContentSerializer";
if (xnbTypeInfo.GenericParameters.Count > 0)
{
var genericParametersList = string.Join(", " , xnbTypeInfo.GenericParameters);
name += $"<{genericParametersList}>";
}
return name;
}
private static void EmitConstructor(CodeStringBuilder cb, XnbTypeInfo xnbTypeInfo)
{
if (xnbTypeInfo.GenericParameters.Count == 0)
{
cb.AppendLine($"public override XnbAssemblyQualifier Name => \"{xnbTypeInfo.QualifierString}\";");
return;
}
cb.AppendLine( "private readonly XnbAssemblyQualifier _name;");
cb.AppendLine();
cb.AppendLine("public override XnbAssemblyQualifier Name => _name;");
cb.Append("public override Type[] UnderlyingContentTypes => [");
cb.Append(string.Join(", ", xnbTypeInfo.GenericParameters.Select(type => $"typeof({type})")));
cb.AppendLine("];");
cb.AppendLine();
cb.AppendLine($"public {xnbTypeInfo.TypeName}ContentSerializer() : base ()");
cb.BeginCodeBlock();
{
cb.AppendLine($"var name = XnbAssemblyQualifier.TryGetFromXnbReaderType(typeof({xnbTypeInfo.TypeFullName}));");
cb.AppendLine("if (name.HasValue) _name = name.Value;");
}
cb.EndCodeBlock();
}
private static void EmitDeserialize(CodeStringBuilder cb, XnbTypeInfo model)
{
cb.AppendLine("public override object Deserialize(XnbContentReader reader)");
cb.BeginCodeBlock();
{
cb.AppendLine($"var content = new {model.TypeFullName}();");
foreach (var prop in model.Properties)
{
EmitPropertyDeserialize(cb, prop);
}
cb.AppendLine("return content;");
}
cb.EndCodeBlock();
}
private static void EmitPropertyDeserialize(CodeStringBuilder cb, XnbPropertyInfo prop)
{
if (prop.Optional)
{
cb.AppendLine($"if (reader.ReadBoolean())");
cb.BeginCodeBlock();
}
cb.Append($"content.{prop.Name} = ");
if (prop.UseConverter)
{
var castType = $"{prop.TypeFullName}{(prop.IsNullable ? "?" : "")}";
cb.Append($"({castType})reader.ReadContent(typeof({prop.TypeFullName}), ");
cb.Append($"{(prop.SkipIdentifier ? "true" : "false")}){(prop.IsNullable ? "" : "!")}");
}
else
{
cb.Append(prop.TypeFullName switch
{
"bool" => "reader.ReadBoolean()",
"int" => "reader.ReadInt32()",
"byte" => "reader.ReadByte()",
"short" => "reader.ReadInt16()",
"float" => "reader.ReadSingle()",
"char" => "reader.ReadChar()",
"string" => "reader.ReadString()",
"global::FEZRepacker.Core.Definitions.Game.XNA.Vector2" => "reader.ReadVector2()",
"global::FEZRepacker.Core.Definitions.Game.XNA.Vector3" => "reader.ReadVector3()",
"global::FEZRepacker.Core.Definitions.Game.XNA.Quaternion" => "reader.ReadQuaternion()",
"global::FEZRepacker.Core.Definitions.Game.XNA.Color" => "reader.ReadColor()",
"global::System.TimeSpan" => "new global::System.TimeSpan(reader.ReadInt64())",
_ => $"default! /* unsupported type: {prop.TypeFullName} */"
});
}
cb.AppendLine(";");
if (prop.Optional)
{
cb.EndCodeBlock();
}
}
private static void EmitSerialize(CodeStringBuilder cb, XnbTypeInfo model)
{
cb.AppendLine("public override void Serialize(object data, XnbContentWriter writer)");
cb.BeginCodeBlock();
{
cb.AppendLine($"var content = ({model.TypeFullName})data;");
foreach (var prop in model.Properties)
{
EmitPropertySerialize(cb, prop);
}
}
cb.EndCodeBlock();
}
private static void EmitPropertySerialize(CodeStringBuilder cb, XnbPropertyInfo prop)
{
var valueExpression = $"content.{prop.Name}";
var propertyType = $"typeof({prop.TypeFullName})";
if (prop.Optional)
{
if (prop.IsNullable)
{
cb.AppendLine($"if ({valueExpression}.HasValue)");
valueExpression += ".Value";
}
else if (prop.IsReferenceType)
{
cb.AppendLine($"if ({valueExpression} != null)");
}
else
{
cb.AppendLine($"// {prop.Name}");
}
cb.BeginCodeBlock();
cb.AppendLine("writer.Write(true);");
}
if (prop.UseConverter)
{
cb.Append($"writer.WriteContent({propertyType}, {valueExpression}, ");
cb.Append($"{(prop.SkipIdentifier ? "true" : "false")})");
}
else
{
cb.Append(prop.TypeFullName switch
{
"bool" => $"writer.Write({valueExpression})",
"int" => $"writer.Write({valueExpression})",
"byte" => $"writer.Write({valueExpression})",
"short" => $"writer.Write({valueExpression})",
"float" => $"writer.Write({valueExpression})",
"char" => $"writer.Write({valueExpression})",
"string" => $"writer.Write({valueExpression})",
"global::FEZRepacker.Core.Definitions.Game.XNA.Vector2" => $"writer.Write({valueExpression})",
"global::FEZRepacker.Core.Definitions.Game.XNA.Vector3" => $"writer.Write({valueExpression})",
"global::FEZRepacker.Core.Definitions.Game.XNA.Quaternion" => $"writer.Write({valueExpression})",
"global::FEZRepacker.Core.Definitions.Game.XNA.Color" => $"writer.Write({valueExpression})",
"global::System.TimeSpan" => $"writer.Write({valueExpression}.Ticks)",
_ => $"_ = {valueExpression} /* unsupported type: {prop.TypeFullName} */"
});
}
cb.AppendLine(";");
if (prop.Optional)
{
cb.EndCodeBlock();
if (prop.IsNullable || prop.IsReferenceType)
{
cb.AppendLine("else");
cb.BeginCodeBlock();
cb.AppendLine("writer.Write(false);");
cb.EndCodeBlock();
}
}
}
}