-
Notifications
You must be signed in to change notification settings - Fork 176
Expand file tree
/
Copy pathSerializerGenerator.cs
More file actions
619 lines (556 loc) · 29.7 KB
/
Copy pathSerializerGenerator.cs
File metadata and controls
619 lines (556 loc) · 29.7 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
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
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
#region -- License Terms --
//
// MessagePack for CLI
//
// Copyright (C) 2010-2017 FUJIWARA, Yusuke and contributors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Contributors:
// Samuel Cragg
//
#endregion -- License Terms --
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using MsgPack.Serialization.AbstractSerializers;
using MsgPack.Serialization.CodeDomSerializers;
#if !NETSTANDARD2_0
using System.CodeDom;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Reflection;
using System.Reflection.Emit;
using MsgPack.Serialization.EmittingSerializers;
#endif // !NETSTANDARD2_0
namespace MsgPack.Serialization
{
/// <summary>
/// Provides pre-compiled serialier assembly generation.
/// </summary>
/// <remarks>
/// Currently, generated assembly has some restrictions:
/// <list type="bullet">
/// <item>
/// The type name cannot be customize. It always to be <c>MsgPack.Serialization.EmittingSerializers.Generated.<ESCAPED_TARGET_NAME>Serializer</c>.
/// Note that the <c>ESCAPED_TARGET_NAME</c> is the string generated by replacing type delimiters with undersecore ('_').
/// </item>
/// <item>
/// The assembly cannot be used on WinRT because
/// </item>
/// </list>
/// <note>
/// You should <strong>NOT</strong> assume at all like class hierarchy of generated type, its implementing interfaces, custom attributes, or dependencies.
/// They subject to be changed in the future.
/// If you want to get such fine grained control for them, you should implement own hand made serializers.
/// </note>
/// </remarks>
public
#if NETSTANDARD2_0
static
#endif // NETSTANDARD2_0
class SerializerGenerator
{
#if !NETSTANDARD2_0
/// <summary>
/// Gets the type of the root object which will be serialized/deserialized.
/// </summary>
/// <value>
/// The first entry of <see cref="TargetTypes"/>.
/// This value will be <c>null</c> when the <see cref="TargetTypes"/> is empty.
/// </value>
[Obsolete( "Use TargetTypes instead." )]
public Type RootType
{
get { return this._targetTypes.FirstOrDefault(); }
}
private readonly HashSet<Type> _targetTypes;
/// <summary>
/// Gets target types will be generated dedicated serializers.
/// </summary>
/// <value>
/// A collection which stores target types will be generated dedicated serializers.
/// </value>
[Obsolete( "Use static methods instead." )]
public ICollection<Type> TargetTypes
{
get { return this._targetTypes; }
}
private readonly AssemblyName _assemblyName;
/// <summary>
/// Gets the name of the assembly to be generated.
/// </summary>
/// <value>
/// The name of the assembly to be generated.
/// </value>
[Obsolete( "Use static methods instead." )]
public AssemblyName AssemblyName
{
get { return this._assemblyName; }
}
private SerializationMethod _method;
/// <summary>
/// Gets or sets the <see cref="SerializationMethod"/> which indicates serialization method to be used.
/// </summary>
/// <value>
/// The <see cref="SerializationMethod"/> which indicates serialization method to be used.
/// </value>
[Obsolete( "Use static methods instead." )]
public SerializationMethod Method
{
get { return this._method; }
set
{
if ( value != SerializationMethod.Array && value != SerializationMethod.Map )
{
throw new ArgumentOutOfRangeException( "value" );
}
this._method = value;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="SerializerGenerator"/> class.
/// </summary>
/// <param name="assemblyName">Name of the assembly to be generated.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="assemblyName"/> is <c>null</c>.
/// </exception>
[Obsolete( "Use static methods instead." )]
public SerializerGenerator( AssemblyName assemblyName )
{
if ( assemblyName == null )
{
throw new ArgumentNullException( "assemblyName" );
}
Contract.EndContractBlock();
this._assemblyName = assemblyName;
this._targetTypes = new HashSet<Type>();
this._method = SerializationMethod.Array;
}
/// <summary>
/// Initializes a new instance of the <see cref="SerializerGenerator"/> class.
/// </summary>
/// <param name="rootType">Type of the root object which will be serialized/deserialized.</param>
/// <param name="assemblyName">Name of the assembly to be generated.</param>
/// <exception cref="ArgumentNullException">
/// <paramref name="rootType"/> is <c>null</c>.
/// Or <paramref name="assemblyName"/> is <c>null</c>.
/// </exception>
[Obsolete( "Use static methods instead." )]
public SerializerGenerator( Type rootType, AssemblyName assemblyName )
: this( assemblyName )
{
if ( rootType == null )
{
throw new ArgumentNullException( "rootType" );
}
Contract.EndContractBlock();
this._targetTypes.Add( rootType );
}
/// <summary>
/// Generates the serializer assembly and save it to current directory.
/// </summary>
/// <returns>The path of generated files.</returns>
/// <exception cref="IOException">Some I/O error is occurred on saving assembly file.</exception>
[Obsolete( "Use static GenerateAssembly method instead." )]
public void GenerateAssemblyFile()
{
this.GenerateAssemblyFile( Path.GetFullPath( "." ) );
}
/// <summary>
/// Generates the serializer assembly and save it to specified directory.
/// </summary>
/// <param name="directory">The path of directory where newly generated assembly file will be located. If the directory does not exist, then it will be created.</param>
/// <returns>The path of generated files.</returns>
/// <exception cref="ArgumentNullException"><paramref name="directory"/> is <c>null</c>.</exception>
/// <exception cref="ArgumentException"><paramref name="directory"/> is not valid.</exception>
/// <exception cref="PathTooLongException"><paramref name="directory"/> is too long.</exception>
/// <exception cref="DirectoryNotFoundException"><paramref name="directory"/> is existent file.</exception>
/// <exception cref="UnauthorizedAccessException">Cannot create specified directory for access control of file system.</exception>
/// <exception cref="IOException">Some I/O error is occurred on creating directory or saving assembly file.</exception>
[Obsolete( "Use static GenerateAssembly method instead." )]
public void GenerateAssemblyFile( string directory )
{
if ( !Directory.Exists( directory ) )
{
Directory.CreateDirectory( directory );
}
GenerateAssembly(
new SerializerAssemblyGenerationConfiguration
{
AssemblyName = this._assemblyName,
OutputDirectory = directory,
SerializationMethod = this._method
},
this._targetTypes
);
}
/// <summary>
/// Generates an assembly which contains auto-generated serializer types for specified types.
/// </summary>
/// <param name="configuration">The <see cref="SerializerAssemblyGenerationConfiguration"/> which holds required <see cref="SerializerAssemblyGenerationConfiguration.AssemblyName"/> and optional settings.</param>
/// <param name="targetTypes">The target types where serializer types to be generated.</param>
/// <returns>The file path for generated single module assembly file.</returns>
/// <exception cref="ArgumentNullException"><paramref name="configuration"/> is <c>null</c>. Or, <paramref name="targetTypes"/> is <c>null</c>.</exception>
/// <exception cref="InvalidOperationException"><see cref="SerializerAssemblyGenerationConfiguration.AssemblyName"/> of <paramref name="configuration"/> is not set correctly.</exception>
/// <exception cref="System.Runtime.Serialization.SerializationException">Failed to generate a serializer because of <paramref name="targetTypes"/>.</exception>
/// <remarks>
/// Serializer types for dependent types which are refered from specified <paramref name="targetTypes"/> are automatically generated.
/// </remarks>
public static string GenerateAssembly( SerializerAssemblyGenerationConfiguration configuration, params Type[] targetTypes )
{
return GenerateAssembly( configuration, targetTypes as IEnumerable<Type> );
}
/// <summary>
/// Generates an assembly which contains auto-generated serializer types for specified types.
/// </summary>
/// <param name="configuration">The <see cref="SerializerAssemblyGenerationConfiguration"/> which holds required <see cref="SerializerAssemblyGenerationConfiguration.AssemblyName"/> and optional settings.</param>
/// <param name="targetTypes">The target types where serializer types to be generated.</param>
/// <returns>The file path for generated single module assembly file.</returns>
/// <exception cref="ArgumentNullException"><paramref name="configuration"/> is <c>null</c>. Or, <paramref name="targetTypes"/> is <c>null</c>.</exception>
/// <exception cref="InvalidOperationException"><see cref="SerializerAssemblyGenerationConfiguration.AssemblyName"/> of <paramref name="configuration"/> is not set correctly.</exception>
/// <exception cref="System.Runtime.Serialization.SerializationException">Failed to generate a serializer because of <paramref name="targetTypes"/>.</exception>
/// <remarks>
/// Serializer types for dependent types which are refered from specified <paramref name="targetTypes"/> are automatically generated.
/// </remarks>
public static string GenerateAssembly( SerializerAssemblyGenerationConfiguration configuration, IEnumerable<Type> targetTypes )
{
var firstEntry = GenerateSerializerCodeAssembly( configuration, targetTypes ).FirstOrDefault();
return firstEntry == null ? null : firstEntry.FilePath;
}
/// <summary>
/// Generates an assembly which contains auto-generated serializer types for specified types.
/// </summary>
/// <param name="configuration">The <see cref="SerializerAssemblyGenerationConfiguration"/> which holds required <see cref="SerializerAssemblyGenerationConfiguration.AssemblyName"/> and optional settings.</param>
/// <param name="targetTypes">The target types where serializer types to be generated.</param>
/// <returns>
/// A <see cref="SerializerCodeGenerationResult"/> collection which correspond to codes generated to <paramref name="targetTypes"/>.
/// All <see cref="SerializerCodeGenerationResult.FilePath"/> properties of items will be same and will point to generated DLL file.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="configuration"/> is <c>null</c>. Or, <paramref name="targetTypes"/> is <c>null</c>.</exception>
/// <exception cref="InvalidOperationException"><see cref="SerializerAssemblyGenerationConfiguration.AssemblyName"/> of <paramref name="configuration"/> is not set correctly.</exception>
/// <exception cref="System.Runtime.Serialization.SerializationException">Failed to generate a serializer because of <paramref name="targetTypes"/>.</exception>
/// <remarks>
/// Serializer types for dependent types which are refered from specified <paramref name="targetTypes"/> are automatically generated.
/// </remarks>
public static IEnumerable<SerializerCodeGenerationResult> GenerateSerializerCodeAssembly( SerializerAssemblyGenerationConfiguration configuration, params Type[] targetTypes )
{
return GenerateSerializerCodeAssembly( configuration, targetTypes as IEnumerable<Type> );
}
/// <summary>
/// Generates an assembly which contains auto-generated serializer types for specified types.
/// </summary>
/// <param name="configuration">The <see cref="SerializerAssemblyGenerationConfiguration"/> which holds required <see cref="SerializerAssemblyGenerationConfiguration.AssemblyName"/> and optional settings.</param>
/// <param name="targetTypes">The target types where serializer types to be generated.</param>
/// <returns>
/// A <see cref="SerializerCodeGenerationResult"/> collection which correspond to codes generated to <paramref name="targetTypes"/>.
/// All <see cref="SerializerCodeGenerationResult.FilePath"/> properties of items will be same and will point to generated DLL file.
/// </returns>
/// <exception cref="ArgumentNullException"><paramref name="configuration"/> is <c>null</c>. Or, <paramref name="targetTypes"/> is <c>null</c>.</exception>
/// <exception cref="InvalidOperationException"><see cref="SerializerAssemblyGenerationConfiguration.AssemblyName"/> of <paramref name="configuration"/> is not set correctly.</exception>
/// <exception cref="System.Runtime.Serialization.SerializationException">Failed to generate a serializer because of <paramref name="targetTypes"/>.</exception>
/// <remarks>
/// Serializer types for dependent types which are refered from specified <paramref name="targetTypes"/> are automatically generated.
/// </remarks>
public static IEnumerable<SerializerCodeGenerationResult> GenerateSerializerCodeAssembly( SerializerAssemblyGenerationConfiguration configuration, IEnumerable<Type> targetTypes )
{
return new SerializerAssemblyGenerationLogic().Generate( targetTypes, configuration );
}
#endif // !NETSTANDARD2_0
/// <summary>
/// Generates source codes which implement auto-generated serializer types for specified types with default configuration.
/// </summary>
/// <param name="targetTypes">The target types where serializer types to be generated.</param>
/// <returns>A file path collection which correspond to codes generated to <paramref name="targetTypes"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="targetTypes"/> is <c>null</c>.</exception>
/// <exception cref="System.Runtime.Serialization.SerializationException">Failed to generate a serializer because of <paramref name="targetTypes"/>.</exception>
/// <remarks>
/// Serializer types for dependent types which are refered from specified <paramref name="targetTypes"/> are NOT generated.
/// This method just generate serializer types for specified types.
/// </remarks>
public static IEnumerable<string> GenerateCode( params Type[] targetTypes )
{
return GenerateCode( null, targetTypes as IEnumerable<Type> );
}
/// <summary>
/// Generates source codes which implement auto-generated serializer types for specified types with default configuration.
/// </summary>
/// <param name="targetTypes">The target types where serializer types to be generated.</param>
/// <returns>A file path collection which correspond to codes generated to <paramref name="targetTypes"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="targetTypes"/> is <c>null</c>.</exception>
/// <exception cref="System.Runtime.Serialization.SerializationException">Failed to generate a serializer because of <paramref name="targetTypes"/>.</exception>
/// <remarks>
/// Serializer types for dependent types which are refered from specified <paramref name="targetTypes"/> are NOT generated.
/// This method just generate serializer types for specified types.
/// </remarks>
public static IEnumerable<string> GenerateCode( IEnumerable<Type> targetTypes )
{
return GenerateCode( null, targetTypes );
}
/// <summary>
/// Generates source codes which implement auto-generated serializer types for specified types with specified configuration.
/// </summary>
/// <param name="configuration">The <see cref="SerializerCodeGenerationConfiguration"/> which holds optional settings. Specifying <c>null</c> means using default settings.</param>
/// <param name="targetTypes">The target types where serializer types to be generated.</param>
/// <returns>A file path collection which correspond to codes generated to <paramref name="targetTypes"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="targetTypes"/> is <c>null</c>.</exception>
/// <exception cref="System.Runtime.Serialization.SerializationException">Failed to generate a serializer because of <paramref name="targetTypes"/>.</exception>
/// <remarks>
/// Serializer types for dependent types which are refered from specified <paramref name="targetTypes"/> are NOT generated.
/// This method just generate serializer types for specified types.
/// </remarks>
public static IEnumerable<string> GenerateCode( SerializerCodeGenerationConfiguration configuration, params Type[] targetTypes )
{
return GenerateSerializerSourceCodes( configuration, targetTypes ).Select( r => r.FilePath );
}
/// <summary>
/// Generates source codes which implement auto-generated serializer types for specified types with specified configuration.
/// </summary>
/// <param name="configuration">The <see cref="SerializerCodeGenerationConfiguration"/> which holds optional settings. Specifying <c>null</c> means using default settings.</param>
/// <param name="targetTypes">The target types where serializer types to be generated.</param>
/// <returns>A file path collection which correspond to codes generated to <paramref name="targetTypes"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="targetTypes"/> is <c>null</c>.</exception>
/// <exception cref="System.Runtime.Serialization.SerializationException">Failed to generate a serializer because of <paramref name="targetTypes"/>.</exception>
/// <remarks>
/// Serializer types for dependent types which are refered from specified <paramref name="targetTypes"/> are NOT generated.
/// This method just generate serializer types for specified types.
/// </remarks>
public static IEnumerable<string> GenerateCode( SerializerCodeGenerationConfiguration configuration, IEnumerable<Type> targetTypes )
{
return GenerateSerializerSourceCodes( configuration, targetTypes ).Select( r => r.FilePath );
}
/// <summary>
/// Generates source codes which implement auto-generated serializer types for specified types with default configuration.
/// </summary>
/// <param name="targetTypes">The target types where serializer types to be generated.</param>
/// <returns>A <see cref="SerializerCodeGenerationResult"/> collection which correspond to codes generated to <paramref name="targetTypes"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="targetTypes"/> is <c>null</c>.</exception>
/// <exception cref="System.Runtime.Serialization.SerializationException">Failed to generate a serializer because of <paramref name="targetTypes"/>.</exception>
/// <remarks>
/// Serializer types for dependent types which are refered from specified <paramref name="targetTypes"/> are NOT generated.
/// This method just generate serializer types for specified types.
/// </remarks>
public static IEnumerable<SerializerCodeGenerationResult> GenerateSerializerSourceCodes( params Type[] targetTypes )
{
return GenerateSerializerSourceCodes( null, targetTypes as IEnumerable<Type> );
}
/// <summary>
/// Generates source codes which implement auto-generated serializer types for specified types with default configuration.
/// </summary>
/// <param name="targetTypes">The target types where serializer types to be generated.</param>
/// <returns>A <see cref="SerializerCodeGenerationResult"/> collection which correspond to codes generated to <paramref name="targetTypes"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="targetTypes"/> is <c>null</c>.</exception>
/// <exception cref="System.Runtime.Serialization.SerializationException">Failed to generate a serializer because of <paramref name="targetTypes"/>.</exception>
/// <remarks>
/// Serializer types for dependent types which are refered from specified <paramref name="targetTypes"/> are NOT generated.
/// This method just generate serializer types for specified types.
/// </remarks>
public static IEnumerable<SerializerCodeGenerationResult> GenerateSerializerSourceCodes( IEnumerable<Type> targetTypes )
{
return GenerateSerializerSourceCodes( null, targetTypes );
}
/// <summary>
/// Generates source codes which implement auto-generated serializer types for specified types with specified configuration.
/// </summary>
/// <param name="configuration">The <see cref="SerializerCodeGenerationConfiguration"/> which holds optional settings. Specifying <c>null</c> means using default settings.</param>
/// <param name="targetTypes">The target types where serializer types to be generated.</param>
/// <returns>A <see cref="SerializerCodeGenerationResult"/> collection which correspond to codes generated to <paramref name="targetTypes"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="targetTypes"/> is <c>null</c>.</exception>
/// <exception cref="System.Runtime.Serialization.SerializationException">Failed to generate a serializer because of <paramref name="targetTypes"/>.</exception>
/// <remarks>
/// Serializer types for dependent types which are refered from specified <paramref name="targetTypes"/> are NOT generated.
/// This method just generate serializer types for specified types.
/// </remarks>
public static IEnumerable<SerializerCodeGenerationResult> GenerateSerializerSourceCodes( SerializerCodeGenerationConfiguration configuration, params Type[] targetTypes )
{
return GenerateSerializerSourceCodes( configuration, targetTypes as IEnumerable<Type> );
}
/// <summary>
/// Generates source codes which implement auto-generated serializer types for specified types with specified configuration.
/// </summary>
/// <param name="configuration">The <see cref="SerializerCodeGenerationConfiguration"/> which holds optional settings. Specifying <c>null</c> means using default settings.</param>
/// <param name="targetTypes">The target types where serializer types to be generated.</param>
/// <returns>A <see cref="SerializerCodeGenerationResult"/> collection which correspond to codes generated to <paramref name="targetTypes"/>.</returns>
/// <exception cref="ArgumentNullException"><paramref name="targetTypes"/> is <c>null</c>.</exception>
/// <exception cref="System.Runtime.Serialization.SerializationException">Failed to generate a serializer because of <paramref name="targetTypes"/>.</exception>
/// <remarks>
/// Serializer types for dependent types which are refered from specified <paramref name="targetTypes"/> are NOT generated.
/// This method just generate serializer types for specified types.
/// </remarks>
public static IEnumerable<SerializerCodeGenerationResult> GenerateSerializerSourceCodes( SerializerCodeGenerationConfiguration configuration, IEnumerable<Type> targetTypes )
{
return new SerializerCodesGenerationLogic().Generate( targetTypes, configuration ?? new SerializerCodeGenerationConfiguration() );
}
private abstract class SerializerGenerationLogic<TConfig>
where TConfig : class, ISerializerGeneratorConfiguration
{
protected abstract EmitterFlavor EmitterFlavor { get; }
public IEnumerable<SerializerCodeGenerationResult> Generate( IEnumerable<Type> targetTypes, TConfig configuration )
{
if ( targetTypes == null )
{
throw new ArgumentNullException( "targetTypes" );
}
if ( configuration == null )
{
throw new ArgumentNullException( "configuration" );
}
configuration.Validate();
var context =
new SerializationContext
{
SerializationMethod = configuration.SerializationMethod,
SerializerOptions =
{
#if FEATURE_TAP
WithAsync = configuration.WithAsync,
#endif // FEATURE_TAP
GeneratorOption = SerializationMethodGeneratorOption.CanDump,
EmitterFlavor = this.EmitterFlavor
},
EnumSerializationOptions =
{
SerializationMethod = configuration.EnumSerializationMethod
},
CompatibilityOptions =
{
AllowNonCollectionEnumerableTypes = configuration.CompatibilityOptions.AllowNonCollectionEnumerableTypes,
IgnorePackabilityForCollection = configuration.CompatibilityOptions.IgnorePackabilityForCollection,
OneBoundDataMemberOrder = configuration.CompatibilityOptions.OneBoundDataMemberOrder,
PackerCompatibilityOptions = configuration.CompatibilityOptions.PackerCompatibilityOptions
}
};
IEnumerable<Type> realTargetTypes;
if ( configuration.IsRecursive )
{
realTargetTypes =
targetTypes
.SelectMany( t => ExtractElementTypes( context, configuration, t ) );
}
else
{
realTargetTypes =
targetTypes
.Where( t => !SerializationTarget.BuiltInSerializerExists( configuration, t, t.GetCollectionTraits( CollectionTraitOptions.None, context.CompatibilityOptions.AllowNonCollectionEnumerableTypes ) ) );
}
var generationContext = this.CreateGenerationContext( context, configuration );
var generatorFactory = this.CreateGeneratorFactory( context );
foreach ( var targetType in realTargetTypes.Distinct() )
{
var generator = generatorFactory( targetType );
var concreteType = default( Type );
if ( targetType.GetIsInterface() || targetType.GetIsAbstract() )
{
concreteType = context.DefaultCollectionTypes.GetConcreteType( targetType );
}
generator.BuildSerializerCode( generationContext, concreteType, null );
}
Directory.CreateDirectory( configuration.OutputDirectory );
return generationContext.Generate();
}
private static IEnumerable<Type> ExtractElementTypes( SerializationContext context, ISerializerGeneratorConfiguration configuration, Type type )
{
var traits = type.GetCollectionTraits( CollectionTraitOptions.None, context.CompatibilityOptions.AllowNonCollectionEnumerableTypes );
if ( !SerializationTarget.BuiltInSerializerExists( configuration, type, traits ) )
{
yield return type;
// Search dependents recursively if the type is NOT enum nand NOT collection.
if ( !type.GetIsEnum() && traits.CollectionType == CollectionKind.NotCollection )
{
foreach (
var dependentType in
SerializationTarget.Prepare( context, type )
.Members.Where( m => m.Member != null ).SelectMany( m => ExtractElementTypes( context, configuration, m.Member.GetMemberValueType() ) )
)
{
yield return dependentType;
}
}
}
var elementTypes = new List<Type>();
if ( traits.ElementType != null )
{
elementTypes.Add( traits.ElementType );
}
else if ( type.IsGenericType )
{
// Search generic arguments recursively.
elementTypes.AddRange( type.GetGenericArguments().SelectMany( g => ExtractElementTypes( context, configuration, g ) ) );
}
foreach ( var elementType in elementTypes )
{
if ( !SerializationTarget.BuiltInSerializerExists( configuration, elementType, elementType.GetCollectionTraits( CollectionTraitOptions.None, allowNonCollectionEnumerableTypes: false ) ) )
{
foreach ( var descendant in ExtractElementTypes( context, configuration, elementType ) )
{
yield return descendant;
}
yield return elementType;
}
}
if ( configuration.WithNullableSerializers && type.GetIsValueType() && Nullable.GetUnderlyingType( type ) == null )
{
// Retrun nullable companion even if they always have built-in serializers.
yield return typeof( Nullable<> ).MakeGenericType( type );
}
}
protected abstract ISerializerCodeGenerationContext CreateGenerationContext( SerializationContext context, TConfig configuration );
protected abstract Func<Type, ISerializerCodeGenerator> CreateGeneratorFactory( SerializationContext context );
}
#if !NETSTANDARD2_0
private sealed class SerializerAssemblyGenerationLogic : SerializerGenerationLogic<SerializerAssemblyGenerationConfiguration>
{
protected override EmitterFlavor EmitterFlavor
{
get { return EmitterFlavor.FieldBased; }
}
public SerializerAssemblyGenerationLogic() { }
[System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1062:ValidateArgumentsOfPublicMethods", MessageId = "1", Justification = "Validated internally" )]
protected override ISerializerCodeGenerationContext CreateGenerationContext( SerializationContext context, SerializerAssemblyGenerationConfiguration configuration )
{
return
new AssemblyBuilderCodeGenerationContext(
context,
AppDomain.CurrentDomain.DefineDynamicAssembly(
configuration.AssemblyName,
AssemblyBuilderAccess.RunAndSave,
configuration.OutputDirectory
),
configuration
);
}
protected override Func<Type, ISerializerCodeGenerator> CreateGeneratorFactory( SerializationContext context )
{
return type => new AssemblyBuilderSerializerBuilder( type, type.GetCollectionTraits( CollectionTraitOptions.Full, context.CompatibilityOptions.AllowNonCollectionEnumerableTypes ) );
}
}
#endif // !NETSTANDARD2_0
private sealed class SerializerCodesGenerationLogic : SerializerGenerationLogic<SerializerCodeGenerationConfiguration>
{
protected override EmitterFlavor EmitterFlavor
{
get { return EmitterFlavor.CodeDomBased; }
}
public SerializerCodesGenerationLogic() { }
protected override ISerializerCodeGenerationContext CreateGenerationContext( SerializationContext context, SerializerCodeGenerationConfiguration configuration )
{
return new CodeDomContext( context, configuration );
}
protected override Func<Type, ISerializerCodeGenerator> CreateGeneratorFactory( SerializationContext context )
{
return type => new CodeDomSerializerBuilder( type, type.GetCollectionTraits( CollectionTraitOptions.Full, context.CompatibilityOptions.AllowNonCollectionEnumerableTypes ) );
}
}
}
}