-
Notifications
You must be signed in to change notification settings - Fork 9
/
LukeMapper.cs
1661 lines (1330 loc) · 65 KB
/
LukeMapper.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
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
Copyright 2013 Leland M. Richardson
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.
*/
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Threading;
using Lucene.Net.Analysis;
using Lucene.Net.Documents;
using Lucene.Net.Index;
using Lucene.Net.Search;
using System.Collections.Concurrent;
namespace LukeMapper
{
public static class LukeMapper
{
#region Constants + Defaults
internal const Store DefaultStore = Store.YES;
internal const Index DefaultIndex = Index.NOT_ANALYZED_NO_NORMS;
private static readonly List<string> SupportedTypes = new List<string>
{
"System.String",
"System.Int32",
"System.Int64",
"System.Boolean",
"System.DateTime",
"System.Char"
};
#endregion
#region Cached Reflection References
//Cached references to useful mappings
private static readonly MethodInfo GetFieldValue = typeof(Document).GetMethod("Get", BindingFlags.Instance | BindingFlags.Public);
private static readonly MethodInfo IntTryParse = typeof(Int32).GetMethod("TryParse", new[] { typeof(string), typeof(int).MakeByRefType() });
private static readonly MethodInfo IntParse = typeof(Int32).GetMethod("Parse", new[] { typeof(string)});
private static readonly MethodInfo LongTryParse = typeof(Int64).GetMethod("TryParse", new[] { typeof(string), typeof(long).MakeByRefType() });
private static readonly MethodInfo IsNullOrEmpty = typeof(String).GetMethod("IsNullOrEmpty", new[] { typeof(string) });
private static readonly MethodInfo LukeMapperGetDateTime = typeof(LukeMapper).GetMethod("GetDateTime");
private static readonly MethodInfo LukeMapperGetBoolean = typeof(LukeMapper).GetMethod("GetBoolean");
private static readonly MethodInfo StringGetChars = typeof(String).GetMethod("get_Chars");
private static readonly MethodInfo StringSplit = typeof(string).GetMethod("Split", new[] { typeof(string[]), typeof(StringSplitOptions) });
//Cached references useful for writes
private static readonly Type DocumentType = typeof(Document);
private static readonly ConstructorInfo DocumentCtor = typeof(Document).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
private static readonly ConstructorInfo FieldCtor = typeof(Field).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new[] { typeof(string), typeof(string), typeof(Field.Store), typeof(Field.Index) }, null);
private static readonly MethodInfo IntToString = typeof(Int32).GetMethod("ToString", Type.EmptyTypes);
private static readonly MethodInfo ObjectToString = typeof(Object).GetMethod("ToString", Type.EmptyTypes);
private static readonly MethodInfo LongToString = typeof(Int64).GetMethod("ToString", Type.EmptyTypes);
private static readonly MethodInfo DocumentAddField = typeof(Document).GetMethod("Add", new[] { typeof(Fieldable) });
private static readonly MethodInfo LukeMapperToDateString = typeof(LukeMapper).GetMethod("ToDateString");
private static readonly MethodInfo StringGenericJoin = typeof (string)
.GetMethods()
.Where(m => m.Name == "Join")
.Select(m => new
{
Method = m,
Params = m.GetParameters(),
Args = m.GetGenericArguments()
})
.Where(x => x.Params.Length == 2
&& x.Args.Length == 1)
.Select(x => x.Method)
.First();
#endregion
#region Query and Write Caching
/// <summary>
/// Called if the query cache is purged via PurgeQueryCache
/// </summary>
public static event EventHandler QueryCachePurged;
private static void OnQueryCachePurged()
{
var handler = QueryCachePurged;
if (handler != null) handler(null, EventArgs.Empty);
}
static readonly ConcurrentDictionary<Identity, DeserializerCacheInfo> _queryCache = new ConcurrentDictionary<Identity, DeserializerCacheInfo>();
static readonly ConcurrentDictionary<Identity, object> _writeCache = new ConcurrentDictionary<Identity, object>();
private static void SetQueryCache(Identity key, DeserializerCacheInfo value)
{
if (Interlocked.Increment(ref collect) == COLLECT_PER_ITEMS)
{
CollectCacheGarbage();
}
_queryCache[key] = value;
}
private static void SetWriteCache<T>(Identity key, SerializerCacheInfo<T> value)
{
if (Interlocked.Increment(ref collect) == COLLECT_PER_ITEMS)
{
CollectCacheGarbage();
}
_writeCache[key] = value;
}
private static void CollectCacheGarbage()
{
//TODO: add write cache here
try
{
foreach (var pair in _queryCache)
{
if (pair.Value.GetHitCount() <= COLLECT_HIT_COUNT_MIN)
{
DeserializerCacheInfo cache;
_queryCache.TryRemove(pair.Key, out cache);
}
}
}
finally
{
Interlocked.Exchange(ref collect, 0);
}
}
private const int COLLECT_PER_ITEMS = 1000, COLLECT_HIT_COUNT_MIN = 0;
private static int collect;
private static bool TryGetQueryCache(Identity key, out DeserializerCacheInfo value)
{
if (_queryCache.TryGetValue(key, out value))
{
value.RecordHit();
return true;
}
value = null;
return false;
}
private static bool TryGetWriteCache<T>(Identity key, out SerializerCacheInfo<T> value)
{
object uncasted;
if (_writeCache.TryGetValue(key, out uncasted))
{
value = (SerializerCacheInfo<T>)uncasted;
value.RecordHit();
return true;
}
value = null;
return false;
}
/// <summary>
/// Purge the query cache
/// </summary>
public static void PurgeQueryCache()
{
//TODO: do for write cache as well
_queryCache.Clear();
OnQueryCachePurged();
}
class DeserializerCacheInfo
{
public Func<Document, object> Deserializer { get; set; }
private int hitCount;
public int GetHitCount() { return Interlocked.CompareExchange(ref hitCount, 0, 0); }
public void RecordHit() { Interlocked.Increment(ref hitCount); }
}
class SerializerCacheInfo<T>
{
public Func<T, Document> Serializer { get; set; }
private int hitCount;
public int GetHitCount() { return Interlocked.CompareExchange(ref hitCount, 0, 0); }
public void RecordHit() { Interlocked.Increment(ref hitCount); }
}
private static DeserializerCacheInfo GetDeserializerCacheInfo(Identity identity)
{
DeserializerCacheInfo info;
if (!TryGetQueryCache(identity, out info))
{
info = new DeserializerCacheInfo();
SetQueryCache(identity, info);
}
return info;
}
private static SerializerCacheInfo<T> GetSerializerCacheInfo<T>(Identity identity)
{
SerializerCacheInfo<T> info;
if (!TryGetWriteCache(identity, out info))
{
info = new SerializerCacheInfo<T>();
SetWriteCache(identity, info);
}
return info;
}
#endregion
#region Deserialization
private static Func<Document, object> GetDeserializer(Type type, IndexSearcher searcher)
{
// dynamic is passed in as Object ... by c# design
if (type == typeof(object) || type == typeof(FastExpando))
{
return GetDynamicDeserializer(searcher);
}
return GetTypeDeserializer(type, searcher);
//return GetStructDeserializer(type, underlyingType ?? type, startBound);
}
/// <summary>
/// This deserializes into a dynamic object (essentially a dictionary)
/// This is much less useful than in the equivalent dynamic object for RDBMS querying,
/// since Lucene stores everything as strings.
///
/// I've simply kept this here as an API since I think it has a convenient and clean syntax
/// over Lucene's document.Get("") etc.
/// </summary>
private static Func<Document, object> GetDynamicDeserializer(IndexSearcher searcher)
{
var names = searcher.GetIndexReader().GetFieldNames(IndexReader.FieldOption.ALL).ToList();
var fieldCount = names.Count;
return
d =>
{
IDictionary<string, object> row = new Dictionary<string, object>(fieldCount);
foreach (var name in names)
{
var tmp = d.Get(name);
if(!string.IsNullOrEmpty(tmp))
{
row[name] = tmp;
}
}
//we know this is an object so it will not box
return FastExpando.Attach(row);
};
}
/// <summary>
/// Here is where most of the magic happens.
///
/// Given an IndexSearcher and a Type to map the index to, it will create and return a
/// function mapping a document to the specified Type
/// </summary>
/// <param name="type">Type to return</param>
/// <param name="searcher">IndexSearcher containing the serialized data</param>
/// <returns></returns>
private static Func<Document, object> GetTypeDeserializer(Type type, IndexSearcher searcher)
{
//debug only
//var assemblyName = new AssemblyName("SomeName");
//var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
//var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, assemblyName.Name + ".dll");
//TypeBuilder builder = moduleBuilder.DefineType("Test", TypeAttributes.Public);
//var dm = builder.DefineMethod(string.Format("Deserialize{0}", Guid.NewGuid()), MethodAttributes.Public, typeof(object), new[] { typeof(Document) });
//debug only
var dm = new DynamicMethod(string.Format("Deserialize{0}", Guid.NewGuid()), type, new[] { typeof(Document) }, true);
var il = dm.GetILGenerator();
var classAttr = type.GetCustomAttributes(typeof(LukeMapperAttribute), true).FirstOrDefault() as LukeMapperAttribute ??
new LukeMapperAttribute();
var properties = GetSettableProps(type);
var fields = GetSettableFields(type);
var names = searcher.GetIndexReader().GetFieldNames(IndexReader.FieldOption.ALL);
var ctor = type.GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, Type.EmptyTypes, null);
if (ctor == null)
{
throw new InvalidOperationException("A parameterless default constructor is required to allow for LukeMapper materialization");
}
il.DeclareLocal(type);
il.Emit(OpCodes.Newobj, ctor);
il.Emit(OpCodes.Stloc_0);
var deserializers =
type.GetMethods()
.Select(method => new
{
Method = method,
DeserializerAttribute = (LukeDeserializerAttribute)method.GetCustomAttributes(typeof(LukeDeserializerAttribute), true).FirstOrDefault()
})
.Where(s => s.DeserializerAttribute != null)
.ToList();
foreach (var property in properties)
{
var lukeAttr =
property.PropertyInfo.GetCustomAttributes(typeof(LukeAttribute), true).FirstOrDefault() as LukeAttribute;
string luceneFieldName = null;
if (lukeAttr != null && lukeAttr.FieldName != null)
{
luceneFieldName = lukeAttr.FieldName;
}
else
{
luceneFieldName = names.FirstOrDefault(s => s.Equals(property.Name, StringComparison.Ordinal)) ??
names.FirstOrDefault(s => s.Equals(property.Name, StringComparison.OrdinalIgnoreCase));
}
if (luceneFieldName == null)
{
continue; // field does not exist in lucene index
}
var customSerializer = deserializers.FirstOrDefault(ser => ser.DeserializerAttribute.FieldName == property.Name);
if (customSerializer != null)
{
EmitCustomDeserializedTypeProp(il, property, customSerializer.Method, classAttr);
}
else
{
var memberType = property.Type;
var nullableType = Nullable.GetUnderlyingType(memberType);
if (nullableType != null)
{
var localString = il.DeclareLocal(typeof(string));
var breakoutLabel = il.DefineLabel();
il.Emit(OpCodes.Ldarg_0); // [document]
il.Emit(OpCodes.Ldstr, luceneFieldName); // [document] [field name]
il.Emit(OpCodes.Callvirt, GetFieldValue); // get field value. //stack is now [value]
il.Emit(OpCodes.Stloc, localString);
il.Emit(OpCodes.Ldloc, localString);
il.Emit(OpCodes.Call, IsNullOrEmpty); // value is not set if true
il.Emit(OpCodes.Brtrue_S, breakoutLabel);
EmitNullType(il, nullableType, localString, breakoutLabel);
var nullCtor = memberType.GetConstructor(new[] { nullableType });
il.Emit(OpCodes.Newobj, nullCtor);
il.Emit(OpCodes.Callvirt, property.Setter);
il.MarkLabel(breakoutLabel);
}
else
{
EmitProp(il, luceneFieldName, property);
}
}
}
foreach (var field in fields)
{
var lukeAttr =
field.GetCustomAttributes(typeof(LukeAttribute), true).FirstOrDefault() as LukeAttribute;
string luceneFieldName = null;
if (lukeAttr != null && lukeAttr.FieldName != null)
{
luceneFieldName = lukeAttr.FieldName;
}
else
{
luceneFieldName = names.FirstOrDefault(s => s.Equals(field.Name, StringComparison.Ordinal)) ??
names.FirstOrDefault(s => s.Equals(field.Name, StringComparison.OrdinalIgnoreCase));
}
if (luceneFieldName == null)
{
continue; // field does not exist in lucene index
}
var memberType = field.FieldType;
var nullableType = Nullable.GetUnderlyingType(memberType);
if (nullableType != null)
{
var localString = il.DeclareLocal(typeof(string));
var breakoutLabel = il.DefineLabel();
il.Emit(OpCodes.Ldarg_0); // [document]
il.Emit(OpCodes.Ldstr, luceneFieldName); // [document] [field name]
il.Emit(OpCodes.Callvirt, GetFieldValue); // get field value. //stack is now [value]
il.Emit(OpCodes.Stloc, localString);
il.Emit(OpCodes.Ldloc, localString);
il.Emit(OpCodes.Call, IsNullOrEmpty); // value is not set if true
il.Emit(OpCodes.Brtrue_S, breakoutLabel);
EmitNullType(il, nullableType, localString, breakoutLabel);
var nullCtor = memberType.GetConstructor(new[] { nullableType });
il.Emit(OpCodes.Newobj, nullCtor);
il.Emit(OpCodes.Stfld, field);
il.MarkLabel(breakoutLabel);
}
else
{
EmitField(il, luceneFieldName, field);
}
}
il.Emit(OpCodes.Ldloc_0); // stack is [rval]
il.Emit(OpCodes.Ret);
//debug only
//var t = builder.CreateType();
//assemblyBuilder.Save(assemblyName.Name + ".dll");
//debug only
return (Func<Document, object>)dm.CreateDelegate(typeof(Func<Document, object>));
//return null;
}
private static void EmitDelimitedPropOrField(ILGenerator il, LukeDelimitedAttribute delimitedAttr, LukeMapperAttribute classAttr, PropInfo prop = null, System.Reflection.FieldInfo field = null)
{
#region Validate Arguments
var type = prop != null ? prop.PropertyInfo.PropertyType : field != null ? field.FieldType : null;
if (type == null)
{
// no prop OR null specified
throw new Exception("argument 'prop' or 'field' is missing");
}
var enumerableType = type.GetInterfaces()
.Where(t => t.IsGenericType)
.FirstOrDefault(t => t.GetGenericTypeDefinition() == typeof(IEnumerable<>));
if (enumerableType == null)
{
// needs to implement IEnumerable<T>;
throw new Exception("The `LukeDelimited` attribute must be applied to a field or property which implements `IEnumerable<T>`");
}
var innerType = enumerableType.GetGenericArguments()[0];
if (!SupportedTypes.Contains(innerType.FullName))
{
// innerType is not an allowed
throw new Exception(string.Format("The type `{0}` is not supported for Delimited lists. please use a `CustomDeserializer` method instead.", innerType.FullName));
}
//get LukeAttribute
LukeAttribute lukeAttr;
if (prop != null)
{
lukeAttr =
prop.PropertyInfo.GetCustomAttributes(typeof(LukeAttribute), true).FirstOrDefault() as
LukeAttribute;
}
else
{
lukeAttr =
field.GetCustomAttributes(typeof(LukeAttribute), true).FirstOrDefault() as
LukeAttribute;
}
if ((lukeAttr != null && lukeAttr.Ignore) || (classAttr.IgnoreByDefault && lukeAttr == null))
{
// field/prop should be ignored
return;
}
#endregion
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, lukeAttr != null && lukeAttr.FieldName != null ? lukeAttr.FieldName : prop.Name);
il.Emit(OpCodes.Callvirt, GetFieldValue);
var local = il.DeclareLocal(typeof (string[]));
il.Emit(OpCodes.Ldc_I4_1);
il.Emit(OpCodes.Newarr, typeof (string));
il.Emit(OpCodes.Stloc_S, local);
il.Emit(OpCodes.Ldloc_S, local);
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Ldstr, delimitedAttr.Delimeter);
il.Emit(OpCodes.Stelem_Ref);
il.Emit(OpCodes.Ldloc_S, local);
il.Emit(OpCodes.Ldc_I4_0); // this is StringSplitOptions.None i believe
il.Emit(OpCodes.Callvirt, StringSplit);
il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Ldftn, IntParse);
var ctor =
typeof (Func<,>)
.MakeGenericType(new[] { typeof (string), innerType })
.GetConstructor(new[] { typeof(object), typeof(IntPtr) });
if (ctor == null)
{
throw new Exception("Cannot find the proper constructor");
}
il.Emit(OpCodes.Newobj, ctor);
var selectMethod = typeof (Enumerable)
.GetMethods()
.First(m => m.Name == "Select")
.MakeGenericMethod(new[] {typeof (string), innerType}); // select method.. string[] -> innerType[]
//TODO: call tolist etc...
if (prop != null)
{
il.Emit(OpCodes.Callvirt, prop.Setter);
}
else
{
il.Emit(OpCodes.Stfld, field);
}
}
/// <summary>
/// Emits an Nullable type T?
/// </summary>
/// <param name="il">IL Generator</param>
/// <param name="type">The Non-Nullable type to wrap with the Nullable interface</param>
/// <param name="stringValue">The serialized string value</param>
/// <param name="breakoutLabel"></param>
private static void EmitNullType(ILGenerator il, Type type, LocalBuilder stringValue, Label breakoutLabel)
{
switch (type.FullName)
{
case "System.DateTime":
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldloc_S, stringValue);
il.Emit(OpCodes.Call, LukeMapperGetDateTime);
break;
case "System.Int32":
var lb = il.DeclareLocal(typeof(int)); // temp int
il.Emit(OpCodes.Ldloc_S, stringValue);
il.Emit(OpCodes.Ldloca_S, lb);
il.Emit(OpCodes.Call, IntTryParse);
il.Emit(OpCodes.Brfalse_S, breakoutLabel);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldloc_S, lb);
break;
case "System.Int64":
var lb64 = il.DeclareLocal(typeof(long)); // temp int
il.Emit(OpCodes.Ldloc_S, stringValue);
il.Emit(OpCodes.Ldloca_S, lb64);
il.Emit(OpCodes.Call, LongTryParse);
il.Emit(OpCodes.Brfalse_S, breakoutLabel);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldloc_S, lb64);
break;
case "System.Boolean":
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldloc_S, stringValue);
il.Emit(OpCodes.Call, LukeMapperGetBoolean);
break;
case "System.Char":
//TODO:
break;
}
//stack to be returned: [0] [underlying nullable type]
//next IL called will be the Nullable<T> constructor.
}
private static void EmitCustomDeserializedTypeProp(ILGenerator il, PropInfo prop, MethodInfo deserializer, LukeMapperAttribute classAttr)
{
var lukeAttr = prop.PropertyInfo.GetCustomAttributes(typeof(LukeAttribute), true).FirstOrDefault() as LukeAttribute;
if ((lukeAttr != null && lukeAttr.Ignore) || (classAttr.IgnoreByDefault && lukeAttr == null))
{
return;
}
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, lukeAttr != null && lukeAttr.FieldName != null ? lukeAttr.FieldName : prop.Name);
il.Emit(OpCodes.Callvirt, GetFieldValue);
il.Emit(OpCodes.Call, deserializer);
il.Emit(OpCodes.Callvirt, prop.Setter);
}
private static void EmitField(ILGenerator il, string name, System.Reflection.FieldInfo field)
{
switch (field.FieldType.FullName)
{
case "System.String":
il.Emit(OpCodes.Ldloc_0);// [target]
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, name); // [target] [string]
il.Emit(OpCodes.Callvirt, GetFieldValue);
il.Emit(OpCodes.Stfld, field);
break;
case "System.Int32":
//int.TryParse
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, name); // [target] [string]
il.Emit(OpCodes.Callvirt, GetFieldValue);
il.Emit(OpCodes.Ldloc_0); // [target]
il.Emit(OpCodes.Ldflda, field);
il.Emit(OpCodes.Call, IntTryParse);
il.Emit(OpCodes.Pop);
break;
case "System.Int64":
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, name); // [target] [string]
il.Emit(OpCodes.Callvirt, GetFieldValue);
il.Emit(OpCodes.Ldloc_0); // [target]
il.Emit(OpCodes.Ldflda, field);
il.Emit(OpCodes.Call, LongTryParse);
il.Emit(OpCodes.Pop);
break;
case "System.Boolean":
il.Emit(OpCodes.Ldloc_0);// [target]
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, name); // [target] [string]
il.Emit(OpCodes.Callvirt, GetFieldValue);
il.Emit(OpCodes.Call, LukeMapperGetBoolean);
il.Emit(OpCodes.Stfld, field);
break;
case "System.DateTime":
il.Emit(OpCodes.Ldloc_0);// [target]
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, name); // [target] [string]
il.Emit(OpCodes.Callvirt, GetFieldValue);
il.Emit(OpCodes.Call, LukeMapperGetDateTime);
il.Emit(OpCodes.Stfld, field);
break;
case "System.Char":
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, name);
il.Emit(OpCodes.Callvirt, GetFieldValue);
var s = il.DeclareLocal(typeof (string));
il.Emit(OpCodes.Stloc, s);
il.Emit(OpCodes.Ldloc, s);//
il.Emit(OpCodes.Call,IsNullOrEmpty);
var next = il.DefineLabel();
il.Emit(OpCodes.Brtrue_S, next);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldloc, s);//
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Call, StringGetChars);
il.Emit(OpCodes.Stfld, field);
il.MarkLabel(next);
break;
default:
return;
}
}
private static void EmitProp(ILGenerator il, string name, PropInfo prop)
{
switch (prop.Type.FullName)
{
case "System.String":
il.Emit(OpCodes.Ldloc_0);// [target]
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, name); // [target] [string]
il.Emit(OpCodes.Callvirt, GetFieldValue);
il.Emit(OpCodes.Callvirt, prop.Setter);
break;
case "System.Int32":
var lb = il.DeclareLocal(typeof (int));
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, prop.Name);
il.Emit(OpCodes.Callvirt, GetFieldValue);
il.Emit(OpCodes.Ldloca_S, lb);
il.Emit(OpCodes.Call, IntTryParse);
il.Emit(OpCodes.Pop);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldloc_S, lb);
il.Emit(OpCodes.Callvirt, prop.Setter);
break;
case "System.Int64":
var lb64 = il.DeclareLocal(typeof (long));
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, prop.Name);
il.Emit(OpCodes.Callvirt, GetFieldValue);
il.Emit(OpCodes.Ldloca_S, lb64);
il.Emit(OpCodes.Call, LongTryParse);
il.Emit(OpCodes.Pop);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldloc_S, lb64);
il.Emit(OpCodes.Callvirt, prop.Setter);
break;
case "System.Boolean":
il.Emit(OpCodes.Ldloc_0);// [target]
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, name); // [target] [string]
il.Emit(OpCodes.Callvirt, GetFieldValue);
il.Emit(OpCodes.Call, LukeMapperGetBoolean);
il.Emit(OpCodes.Callvirt, prop.Setter);
break;
case "System.DateTime":
il.Emit(OpCodes.Ldloc_0);// [target]
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, name); // [target] [string]
il.Emit(OpCodes.Callvirt, GetFieldValue);
il.Emit(OpCodes.Call, LukeMapperGetDateTime);
il.Emit(OpCodes.Callvirt, prop.Setter);
break;
case "System.Char":
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Ldstr, name);
il.Emit(OpCodes.Callvirt, GetFieldValue);
var s = il.DeclareLocal(typeof(string));
il.Emit(OpCodes.Stloc, s);
il.Emit(OpCodes.Ldloc, s);//
il.Emit(OpCodes.Call, IsNullOrEmpty);
var next = il.DefineLabel();
il.Emit(OpCodes.Brtrue_S, next);
il.Emit(OpCodes.Ldloc_0);
il.Emit(OpCodes.Ldloc, s);//
il.Emit(OpCodes.Ldc_I4_0);
il.Emit(OpCodes.Call, StringGetChars);
il.Emit(OpCodes.Callvirt, prop.Setter);
il.MarkLabel(next);
break;
default:
return;
}
}
#endregion
#region Serialization
private static Func<T, Document> GetSerializer<T>(Type type)
{
return GetTypeSerializer<T>(type);
//return GetStructDeserializer(type, underlyingType ?? type, startBound);
}
// make delegate
private static Func<T, Document> GetTypeSerializer<T>(Type type)
{
//debug only
//var assemblyName = new AssemblyName("SomeName");
//var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
//var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, assemblyName.Name + ".dll");
//TypeBuilder builder = moduleBuilder.DefineType("Test", TypeAttributes.Public);
//var dm = builder.DefineMethod(string.Format("Serialize{0}", Guid.NewGuid()), MethodAttributes.Public | MethodAttributes.Static, DocumentType, new[] { type });
//debug only
var dm = new DynamicMethod(
string.Format("Serialize{0}", Guid.NewGuid()),
DocumentType,
new[] { type },
true);
var il = dm.GetILGenerator();
var properties = GetSettableProps(type);
var fields = GetSettableFields(type);
var classAttr = type.GetCustomAttributes(typeof(LukeMapperAttribute), true).FirstOrDefault() as LukeMapperAttribute ??
new LukeMapperAttribute();
il.DeclareLocal(DocumentType);
il.Emit(OpCodes.Newobj, DocumentCtor);
il.Emit(OpCodes.Stloc_0); //stack is [document]
var serializers =
type.GetMethods()
.Select(method => new
{
Method = method,
SerializerAttribute = (LukeSerializerAttribute)method.GetCustomAttributes(typeof(LukeSerializerAttribute), true).FirstOrDefault()
})
.Where(s => s.SerializerAttribute != null)
.ToList();
foreach (var prop in properties)
{
var delimitedAttr =
(LukeDelimitedAttribute)prop.PropertyInfo.GetCustomAttributes(typeof (LukeDelimitedAttribute), true).FirstOrDefault();
if (delimitedAttr != null)
{
EmitDelimitedPropOrFieldToDocument(il, delimitedAttr, classAttr, prop: prop);
continue;
}
var customSerializer = serializers.FirstOrDefault(ser => ser.SerializerAttribute.FieldName == prop.Name);
if (customSerializer != null)
{
EmitCustomSerializedTypeProp(il, prop, customSerializer.Method, classAttr);
continue;
}
EmitPropToDocument(il, prop, classAttr);
}
foreach (var field in fields)
{
var delimitedAttr =
(LukeDelimitedAttribute)field.GetCustomAttributes(typeof(LukeDelimitedAttribute), true).FirstOrDefault();
if (delimitedAttr != null)
{
//TODO:
//EmitDelimitedPropOrFieldToDocument(il, delimitedAttr, classAttr, field: field);
continue;
}
var customSerializer = serializers.FirstOrDefault(ser => ser.SerializerAttribute.FieldName == field.Name);
if (customSerializer != null)
{
//TODO: custom prop
//EmitCustomSerializedTypeProp(il, prop, customSerializer.Method, classAttr);
continue;
}
EmitFieldToDocument(il, field, classAttr);
}
il.Emit(OpCodes.Ldloc_0); // stack is [document]
il.Emit(OpCodes.Ret);
//debug only
//var t = builder.CreateType();
//assemblyBuilder.Save(assemblyName.Name + ".dll");
//debug only
return (Func<T, Document>)dm.CreateDelegate(typeof(Func<T, Document>));
//return null;
}
// make assembly
private static Func<T, Document> xxGetTypeSerializer<T>(Type type)
{
//debug only
var assemblyName = new AssemblyName("SomeName");
var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.RunAndSave);
var moduleBuilder = assemblyBuilder.DefineDynamicModule(assemblyName.Name, assemblyName.Name + ".dll");
TypeBuilder builder = moduleBuilder.DefineType("Test", TypeAttributes.Public);
var dm = builder.DefineMethod(string.Format("Serialize{0}", Guid.NewGuid()), MethodAttributes.Public | MethodAttributes.Static, DocumentType, new[] { type });
//debug only
//var dm = new DynamicMethod(
// string.Format("Serialize{0}", Guid.NewGuid()),
// DocumentType,
// new[] { type },
// true);
var il = dm.GetILGenerator();
//TODO: maybe change to allow ALL properties?
var properties = GetSettableProps(type);
var fields = GetSettableFields(type);
var classAttr = type.GetCustomAttributes(typeof(LukeMapperAttribute), true).FirstOrDefault() as LukeMapperAttribute ??
new LukeMapperAttribute();
il.DeclareLocal(DocumentType);
il.Emit(OpCodes.Newobj, DocumentCtor);
il.Emit(OpCodes.Stloc_0); //stack is [document]
var serializers =
type.GetMethods()
.Select(method => new
{
Method = method,
SerializerAttribute = (LukeSerializerAttribute)method.GetCustomAttributes(typeof(LukeSerializerAttribute), true).FirstOrDefault()
})
.Where(s => s.SerializerAttribute != null)
.ToList();
foreach (var prop in properties)
{
var delimitedAttr =
(LukeDelimitedAttribute)prop.PropertyInfo.GetCustomAttributes(typeof(LukeDelimitedAttribute), true).FirstOrDefault();
if (delimitedAttr != null)
{
EmitDelimitedPropOrFieldToDocument(il, delimitedAttr, classAttr, prop: prop);
continue;
}
var customSerializer = serializers.FirstOrDefault(ser => ser.SerializerAttribute.FieldName == prop.Name);
if (customSerializer != null)
{
EmitCustomSerializedTypeProp(il, prop, customSerializer.Method, classAttr);
continue;
}
EmitPropToDocument(il, prop, classAttr);
}
foreach (var field in fields)
{
var delimitedAttr =
(LukeDelimitedAttribute)field.GetCustomAttributes(typeof(LukeDelimitedAttribute), true).FirstOrDefault();
if (delimitedAttr != null)
{
//TODO:
//EmitDelimitedPropOrFieldToDocument(il, delimitedAttr, classAttr, field: field);
continue;
}
var customSerializer = serializers.FirstOrDefault(ser => ser.SerializerAttribute.FieldName == field.Name);
if (customSerializer != null)
{
//TODO: custom prop
//EmitCustomSerializedTypeProp(il, prop, customSerializer.Method, classAttr);
continue;