forked from ch-robinson/dotnet-avro
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCodeGenerator.cs
407 lines (351 loc) · 14.4 KB
/
CodeGenerator.cs
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
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
using Chr.Avro.Abstract;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Formatting;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace Chr.Avro.Codegen
{
/// <summary>
/// Generates code to match Avro schemas.
/// </summary>
public interface ICodeGenerator
{
/// <summary>
/// Writes a compilation unit (intuitively, a single source code file) that contains types
/// that match the schema.
/// </summary>
/// <param name="schema">
/// The schema to generate code for.
/// </param>
/// <param name="stream">
/// A stream to write the resulting compilation unit to.
/// </param>
void WriteCompilationUnit(Schema schema, Stream stream);
/// <summary>
/// Writes a compilation unit (intuitively, a single source code file) that contains types
/// that match the schema.
/// </summary>
/// <param name="schema">
/// The schema to generate code for.
/// </param>
/// <returns>
/// The compilation unit as a string.
/// </returns>
string WriteCompilationUnit(Schema schema);
}
/// <summary>
/// Generates C# classes and enums that match Avro schemas.
/// </summary>
public class CSharpCodeGenerator : ICodeGenerator
{
/// <summary>
/// Generates a class declaration for a record schema.
/// </summary>
/// <param name="schema">
/// The schema to generate a class for.
/// </param>
/// <returns>
/// A class declaration with a property for each field of the record schema.
/// </returns>
/// <throws cref="UnsupportedSchemaException">
/// Thrown when a field schema is not recognized.
/// </throws>
public virtual ClassDeclarationSyntax GenerateClass(RecordSchema schema)
{
var declaration = SyntaxFactory.ClassDeclaration(schema.Name)
.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
.AddMembers(schema.Fields
.Select(field =>
{
var child = SyntaxFactory
.PropertyDeclaration(
GetPropertyType(field.Type),
field.Name
)
.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
.AddAccessorListAccessors(
SyntaxFactory.AccessorDeclaration(SyntaxKind.GetAccessorDeclaration)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken)),
SyntaxFactory.AccessorDeclaration(SyntaxKind.SetAccessorDeclaration)
.WithSemicolonToken(SyntaxFactory.Token(SyntaxKind.SemicolonToken))
);
if (!string.IsNullOrEmpty(field.Documentation))
{
child = AddSummaryComment(child, field.Documentation);
}
return child;
})
.Where(field => field != null)
.ToArray()
);
if (!string.IsNullOrEmpty(schema.Documentation))
{
declaration = AddSummaryComment(declaration, schema.Documentation);
}
return declaration;
}
/// <summary>
/// Generates an enum declaration for an enum schema.
/// </summary>
/// <param name="schema">
/// The schema to generate an enum for.
/// </param>
/// <returns>
/// An enum declaration with members that match the symbols of the enum schema.
/// </returns>
public virtual EnumDeclarationSyntax GenerateEnum(EnumSchema schema)
{
var declaration = SyntaxFactory.EnumDeclaration(schema.Name)
.AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword))
.AddMembers(schema.Symbols
.Select(symbol => SyntaxFactory.EnumMemberDeclaration(symbol))
.ToArray()
);
if (!string.IsNullOrEmpty(schema.Documentation))
{
declaration = AddSummaryComment(declaration, schema.Documentation);
}
return declaration;
}
/// <summary>
/// Generates a compilation unit (essentially a single .cs file) that contains types that
/// match the schema.
/// </summary>
/// <param name="schema">
/// The schema to generate code for. Code can only be generated for enum
/// and record schemas.
/// </param>
/// <returns>
/// A compilation unit containing types that match the schema.
/// </returns>
/// <throws cref="UnsupportedSchemaException">
/// Thrown when the schema is not an enum or record, or when a record
/// field schema is not recognized.
/// </throws>
public virtual CompilationUnitSyntax GenerateCompilationUnit(Schema schema)
{
var candidates = GetCandidateSchemas(schema)
.OrderBy(s => s.Name)
.GroupBy(s => s.Namespace)
.OrderBy(g => g.Key);
if (candidates.Count() < 1)
{
throw new UnsupportedSchemaException(schema, $"Code can only be generated for enums and records.");
}
var unit = SyntaxFactory.CompilationUnit();
foreach (var group in candidates)
{
var members = group
.Select(candidate =>
{
switch (candidate)
{
case EnumSchema e:
return GenerateEnum(e) as MemberDeclarationSyntax;
case RecordSchema r:
return GenerateClass(r) as MemberDeclarationSyntax;
default:
return null;
}
})
.Where(candidate => candidate != null)
.ToArray();
if (!string.IsNullOrEmpty(group.Key))
{
members = new[]
{
SyntaxFactory.NamespaceDeclaration(SyntaxFactory.ParseName(group.Key)).AddMembers(members)
};
}
unit = unit.AddMembers(members);
}
return unit.RewriteNamespaces();
}
/// <summary>
/// Writes a compilation unit (essentially a single .cs file) that contains types that
/// match the schema.
/// </summary>
/// <param name="schema">
/// The schema to generate code for.
/// </param>
/// <param name="stream">
/// A stream to write the resulting compilation unit to.
/// </param>
public void WriteCompilationUnit(Schema schema, Stream stream)
{
using (var workspace = new AdhocWorkspace())
using (var writer = new StreamWriter(stream))
{
var unit = GenerateCompilationUnit(schema) as SyntaxNode;
unit = Formatter.Format(unit, workspace);
unit.WriteTo(writer);
}
}
/// <summary>
/// Writes a compilation unit (essentially a single .cs file) that contains types that
/// match the schema.
/// </summary>
/// <param name="schema">
/// The schema to generate code for.
/// </param>
/// <returns>
/// The compilation unit as a string.
/// </returns>
public string WriteCompilationUnit(Schema schema)
{
var stream = new MemoryStream();
using (stream)
{
WriteCompilationUnit(schema, stream);
}
return Encoding.UTF8.GetString(stream.ToArray());
}
/// <summary>
/// Gets a matching type for a schema.
/// </summary>
/// <remarks>
/// Namespaces are prefixed with the global namespace alias. Names can be simplified later on.
/// </remarks>
/// <param name="schema">
/// The schema to match to a type.
/// </param>
/// <param name="nullable">
/// Whether the type should be nullable.
/// </param>
/// <returns>
/// A type that matches the schema.
/// </returns>
/// <throws cref="UnsupportedSchemaException">
/// Thrown when the schema is not recognized.
/// </throws>
protected virtual TypeSyntax GetPropertyType(Schema schema, bool nullable = false)
{
var type = SyntaxFactory.ParseTypeName("object");
var value = false;
switch (schema)
{
case BytesSchema b when b.LogicalType is DecimalLogicalType:
case FixedSchema f when f.LogicalType is DecimalLogicalType:
type = SyntaxFactory.ParseTypeName("decimal");
value = true;
break;
case FixedSchema f when f.LogicalType is DurationLogicalType:
type = SyntaxFactory.ParseTypeName("global::System.TimeSpan");
value = true;
break;
case LongSchema l when l.LogicalType is TimestampLogicalType t:
type = SyntaxFactory.ParseTypeName("global::System.DateTime");
value = true;
break;
case ArraySchema a:
type = SyntaxFactory.ParseTypeName($"global::System.Collections.Generic.IEnumerable<{GetPropertyType(a.Item)}>");
break;
case BooleanSchema b:
type = SyntaxFactory.ParseTypeName("bool");
value = true;
break;
case BytesSchema b:
case FixedSchema f:
type = SyntaxFactory.ParseTypeName("byte[]");
break;
case DoubleSchema d:
type = SyntaxFactory.ParseTypeName("double");
value = true;
break;
case EnumSchema e:
type = SyntaxFactory.ParseTypeName($"global::{e.FullName}");
break;
case FloatSchema f:
type = SyntaxFactory.ParseTypeName("float");
value = true;
break;
case IntSchema i:
type = SyntaxFactory.ParseTypeName("int");
value = true;
break;
case LongSchema l:
type = SyntaxFactory.ParseTypeName("long");
value = true;
break;
case MapSchema m:
type = SyntaxFactory.ParseTypeName($"global::System.Collections.Generic.IDictionary<string, {GetPropertyType(m.Value)}>");
break;
case NullSchema n:
return null;
case RecordSchema r:
type = SyntaxFactory.ParseTypeName($"global::{r.FullName}");
break;
case StringSchema s:
type = SyntaxFactory.ParseTypeName("string");
break;
case UnionSchema u:
var nulls = u.Schemas.OfType<NullSchema>();
var others = u.Schemas.Except(nulls);
try
{
return GetPropertyType(others.Single(), nulls.Count() > 0);
}
catch (InvalidOperationException exception)
{
throw new UnsupportedSchemaException(u, $"Could not generate a type for the union [{string.Join(", ", u.Schemas.Select(s => s.GetType().Name))}]", exception);
}
default:
throw new UnsupportedSchemaException(schema, $"{schema.GetType()} is not recognized by the code generator.");
}
if (nullable && value)
{
type = SyntaxFactory.NullableType(type);
}
return type;
}
private static TSyntax AddSummaryComment<TSyntax>(TSyntax node, string summary) where TSyntax : SyntaxNode
{
var components = new XmlNodeSyntax[]
{
SyntaxFactory.XmlSummaryElement(SyntaxFactory.XmlText(summary))
};
var trivia = node.GetLeadingTrivia().Add(
SyntaxFactory.Trivia(
SyntaxFactory.DocumentationCommentTrivia(SyntaxKind.MultiLineDocumentationCommentTrivia, SyntaxFactory.List(components))
.WithLeadingTrivia(SyntaxFactory.DocumentationCommentExterior("/// "))
.WithTrailingTrivia(SyntaxFactory.CarriageReturnLineFeed)
)
);
return node.WithLeadingTrivia(trivia);
}
private static IEnumerable<NamedSchema> GetCandidateSchemas(Schema schema, ISet<Schema> seen = null)
{
seen = seen ?? new HashSet<Schema>();
if (seen.Add(schema))
{
switch (schema)
{
case ArraySchema a:
GetCandidateSchemas(a.Item, seen);
break;
case MapSchema m:
GetCandidateSchemas(m.Value, seen);
break;
case RecordSchema r:
foreach (var field in r.Fields)
{
GetCandidateSchemas(field.Type, seen);
}
break;
case UnionSchema u:
foreach (var child in u.Schemas)
{
GetCandidateSchemas(child, seen);
}
break;
}
}
return seen.OfType<NamedSchema>();
}
}
}