-
Notifications
You must be signed in to change notification settings - Fork 177
Expand file tree
/
Copy pathRealmWeaver.cs
More file actions
1338 lines (1155 loc) · 67 KB
/
Copy pathRealmWeaver.cs
File metadata and controls
1338 lines (1155 loc) · 67 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
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 2020 Realm Inc.
//
// 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.Linq;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
using Realms;
// ReSharper disable InconsistentNaming
// ReSharper disable MemberCanBePrivate.Global
namespace RealmWeaver
{
/// <summary>
/// This weaver is used both by Fody and the Unity weaver, so make sure to only reference Mono.Cecil and nothing Fody or Unity specific.
/// </summary>
internal partial class Weaver
{
private const MethodAttributes DefaultMethodAttributes = MethodAttributes.Public | MethodAttributes.Final | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.NewSlot;
internal const string StringTypeName = "System.String";
internal const string ByteArrayTypeName = "System.Byte[]";
internal const string CharTypeName = "System.Char";
internal const string ByteTypeName = "System.Byte";
internal const string Int16TypeName = "System.Int16";
internal const string Int32TypeName = "System.Int32";
internal const string Int64TypeName = "System.Int64";
internal const string SingleTypeName = "System.Single";
internal const string DoubleTypeName = "System.Double";
internal const string BooleanTypeName = "System.Boolean";
internal const string DecimalTypeName = "System.Decimal";
internal const string Decimal128TypeName = "MongoDB.Bson.Decimal128";
internal const string ObjectIdTypeName = "MongoDB.Bson.ObjectId";
internal const string DateTimeOffsetTypeName = "System.DateTimeOffset";
internal const string GuidTypeName = "System.Guid";
internal const string RealmValueTypeName = "Realms.RealmValue";
internal const string NullableCharTypeName = "System.Nullable`1<System.Char>";
internal const string NullableByteTypeName = "System.Nullable`1<System.Byte>";
internal const string NullableInt16TypeName = "System.Nullable`1<System.Int16>";
internal const string NullableInt32TypeName = "System.Nullable`1<System.Int32>";
internal const string NullableInt64TypeName = "System.Nullable`1<System.Int64>";
internal const string NullableSingleTypeName = "System.Nullable`1<System.Single>";
internal const string NullableDoubleTypeName = "System.Nullable`1<System.Double>";
internal const string NullableBooleanTypeName = "System.Nullable`1<System.Boolean>";
internal const string NullableDecimalTypeName = "System.Nullable`1<System.Decimal>";
internal const string NullableDecimal128TypeName = "System.Nullable`1<MongoDB.Bson.Decimal128>";
internal const string NullableDateTimeOffsetTypeName = "System.Nullable`1<System.DateTimeOffset>";
internal const string NullableObjectIdTypeName = "System.Nullable`1<MongoDB.Bson.ObjectId>";
internal const string NullableGuidTypeName = "System.Nullable`1<System.Guid>";
private static readonly HashSet<string> _realmValueTypes = new()
{
CharTypeName,
SingleTypeName,
DoubleTypeName,
BooleanTypeName,
DecimalTypeName,
Decimal128TypeName,
ObjectIdTypeName,
DateTimeOffsetTypeName,
GuidTypeName,
NullableCharTypeName,
NullableSingleTypeName,
NullableDoubleTypeName,
NullableBooleanTypeName,
NullableDateTimeOffsetTypeName,
NullableDecimalTypeName,
NullableDecimal128TypeName,
NullableObjectIdTypeName,
NullableGuidTypeName,
ByteTypeName,
Int16TypeName,
Int32TypeName,
Int64TypeName,
NullableByteTypeName,
NullableInt16TypeName,
NullableInt32TypeName,
NullableInt64TypeName,
$"Realms.RealmInteger`1<{ByteTypeName}>",
$"Realms.RealmInteger`1<{Int16TypeName}>",
$"Realms.RealmInteger`1<{Int32TypeName}>",
$"Realms.RealmInteger`1<{Int64TypeName}>",
$"System.Nullable`1<Realms.RealmInteger`1<{ByteTypeName}>>",
$"System.Nullable`1<Realms.RealmInteger`1<{Int16TypeName}>>",
$"System.Nullable`1<Realms.RealmInteger`1<{Int32TypeName}>>",
$"System.Nullable`1<Realms.RealmInteger`1<{Int64TypeName}>>",
ByteArrayTypeName,
StringTypeName,
RealmValueTypeName,
};
private static readonly IEnumerable<string> _primaryKeyTypes = new[]
{
StringTypeName,
CharTypeName,
ByteTypeName,
Int16TypeName,
Int32TypeName,
Int64TypeName,
ObjectIdTypeName,
GuidTypeName,
NullableCharTypeName,
NullableByteTypeName,
NullableInt16TypeName,
NullableInt32TypeName,
NullableInt64TypeName,
NullableObjectIdTypeName,
NullableGuidTypeName
};
private static readonly HashSet<string> RealmPropertyAttributes = new()
{
"PrimaryKeyAttribute",
"IndexedAttribute",
"MapToAttribute",
};
private readonly Lazy<MethodReference> _propertyChanged_DoNotNotify_Ctor;
private readonly ImportedReferences _references;
private readonly ModuleDefinition _moduleDefinition;
private readonly ILogger _logger;
private IEnumerable<MatchingType> GetMatchingTypes()
{
foreach (var type in _moduleDefinition.GetTypes())
{
if (type.CustomAttributes.Any(a => a.AttributeType.Name == "IgnoredAttribute"))
{
continue;
}
if (type.IsRealmObjectDescendant(_references))
{
// Classic types
if (type.IsValidRealmObjectBaseInheritor(_references))
{
yield return new MatchingType(type, false);
}
else
{
_logger.Error($"The type {type.FullName} indirectly inherits from RealmObject which is not supported.", type.GetConstructors().FirstOrDefault()?.DebugInformation?.SequencePoints?.FirstOrDefault());
}
}
else if (type.CustomAttributes.Any(a => a.AttributeType.Name == "GeneratedAttribute"))
{
// Generated types
yield return new MatchingType(type, true);
}
}
}
public Weaver(ModuleDefinition module, ILogger logger, string framework)
{
//// UNCOMMENT THIS DEBUGGER LAUNCH TO BE ABLE TO RUN A SEPARATE VS INSTANCE TO DEBUG WEAVING WHILST BUILDING
//// System.Diagnostics.Debugger.Launch();
_moduleDefinition = module;
_logger = logger;
_references = ImportedReferences.Create(_moduleDefinition, framework);
_propertyChanged_DoNotNotify_Ctor = new Lazy<MethodReference>(GetOrAddPropertyChanged_DoNotNotify);
}
public WeaveModuleResult Execute(Analytics.Config analyticsConfig)
{
var analytics = new Analytics(analyticsConfig, _references, _logger, _moduleDefinition);
var result = ExecuteInternal(out var weaveResults);
analytics.AnalyzeRealmClassProperties(weaveResults);
// Don't wait for submission
_ = analytics.SubmitAnalytics();
return result;
}
private WeaveModuleResult ExecuteInternal(out WeaveTypeResult[] weaveResults)
{
_logger.Debug("Weaving file: " + _moduleDefinition.FileName);
// This is necessary because some frameworks, e.g. xamarin, have the models in one assembly and the platform
// specific code in another assembly, but we still want to report what target the user is building for
if (_references.Realm == null)
{
weaveResults = Array.Empty<WeaveTypeResult>();
return WeaveModuleResult.Skipped($"Not weaving assembly '{_moduleDefinition.Assembly.Name}' because it doesn't reference Realm.");
}
var isWoven = _moduleDefinition.Assembly.CustomAttributes.Any(a => a.AttributeType.IsSameAs(_references.WovenAssemblyAttribute));
if (isWoven)
{
weaveResults = Array.Empty<WeaveTypeResult>();
return WeaveModuleResult.Skipped($"Not weaving assembly '{_moduleDefinition.Assembly.Name}' because it has already been processed.");
}
var matchingTypes = GetMatchingTypes().ToArray();
weaveResults = matchingTypes.Select(matchingType =>
{
var type = matchingType.Type;
var isGenerated = matchingType.IsGenerated;
try
{
return isGenerated ? WeaveGeneratedType(type) : WeaveType(type);
}
catch (Exception e)
{
_logger.Error($"An unexpected error occurred while weaving '{type.Name}': {e.Message}.\r\nCallstack:\r\n{e.StackTrace}");
return WeaveTypeResult.Error(type.Name);
}
}).ToArray();
WeaveSchema(matchingTypes.Select(t => t.Type).ToArray());
var wovenAssemblyAttribute = new CustomAttribute(_references.WovenAssemblyAttribute_Constructor);
_moduleDefinition.Assembly.CustomAttributes.Add(wovenAssemblyAttribute);
var failedResults = weaveResults.Where(r => !r.IsSuccessful).ToArray();
if (failedResults.Any())
{
return WeaveModuleResult.Error($"The following types had errors when woven: {string.Join(", ", failedResults.Select(f => f.Type))}");
}
return WeaveModuleResult.Success(weaveResults);
}
private static void RemoveBackingFields(TypeDefinition type, HashSet<MetadataToken> backingFields)
{
for (var i = type.Fields.Count - 1; i >= 0; i--)
{
var field = type.Fields[i];
if (backingFields.Contains(field.MetadataToken))
{
type.Fields.RemoveAt(i);
}
}
// Iterates through all constructors' instructions from the end to start.
foreach (var constructor in type.GetConstructors())
{
// Index of the most recent "Stfld <backing_field>" instruction
var backingFieldInstructionsEnd = -1;
for (var i = constructor.Body.Instructions.Count - 1; i >= 0; i--)
{
var instruction = constructor.Body.Instructions[i];
// If it comes across "Stfld <backing_field>"
// it considers this the end index of backing field initialization instructions.
if (instruction.OpCode == OpCodes.Stfld && instruction.Operand is FieldReference field)
{
if (backingFields.Contains(field.MetadataToken))
{
backingFieldInstructionsEnd = i;
}
}
// If it comes across "Ldarg 0",
// it considers this the start index of backing field initialization instructions
// and removes all backing field instructions from end to start.
else if (instruction.OpCode == OpCodes.Ldarg_0)
{
for (var j = backingFieldInstructionsEnd; j >= i; j--)
{
constructor.Body.Instructions.RemoveAt(j);
}
}
}
}
}
private WeaveTypeResult WeaveGeneratedType(TypeDefinition type)
{
_logger.Debug("Weaving generated " + type.Name);
// The forward slash is used to indicate a nested class
var interfaceType = _moduleDefinition.GetType($"{type.FullName}/I{type.Name}Accessor");
var persistedProperties = new List<WeavePropertyResult>();
var backingFields = new HashSet<MetadataToken>();
// We need to weave all (and only) the properties in the accessor interface
foreach (var interfaceProperty in interfaceType.Properties)
{
var prop = type.Properties.First(p => p.Name == interfaceProperty.Name);
try
{
// Stash and remove the backing field before weaving as it depends on get method.
var backingField = prop.GetBackingField();
if (backingField != null)
{
backingFields.Add(backingField.MetadataToken);
}
var weaveResult = WeaveGeneratedClassProperty(type, prop, interfaceType);
persistedProperties.Add(weaveResult);
}
catch (Exception e)
{
var sequencePoint = prop.GetSequencePoint();
_logger.Error(
$"Unexpected error caught weaving property '{type.Name}.{prop.Name}': {e.Message}.\r\nCallstack:\r\n{e.StackTrace}",
sequencePoint);
return WeaveTypeResult.Error(type.Name, isGenerated: true);
}
}
RemoveBackingFields(type, backingFields);
return WeaveTypeResult.Success(type.Name, persistedProperties, isGenerated: true);
}
private WeavePropertyResult WeaveGeneratedClassProperty(TypeDefinition type, PropertyDefinition prop, TypeDefinition interfaceType)
{
var accessorGetter = new MethodReference("get_Accessor", interfaceType, type) { HasThis = true };
ReplaceGeneratedClassGetter(prop, interfaceType, accessorGetter);
if (prop.SetMethod != null)
{
ReplaceGeneratedClassSetter(prop, interfaceType, accessorGetter);
}
return WeavePropertyResult.Success(prop);
}
private static void ReplaceGeneratedClassGetter(PropertyDefinition prop, TypeDefinition interfaceType, MethodReference accessorGetter)
{
//// A synthesized property getter looks like this:
//// 0: ldarg.0
//// 1: ldfld <backingField>
//// 2: ret
//// We want to change it so it looks like this:
//// 0: ldarg.0
//// 1: ldfld _accessor
//// 2: call property getter on accessor
//// 3: ret
////
//// This is equivalent to:
//// get => Accessor.Property;
var il = prop.GetMethod.Body.GetILProcessor();
prop.GetMethod.Body.Instructions.Clear();
prop.GetMethod.Body.Variables.Clear();
var propertyGetterOnAccessorReference = new MethodReference($"get_{prop.Name}", prop.PropertyType, interfaceType) { HasThis = true };
il.Append(il.Create(OpCodes.Ldarg_0));
il.Append(il.Create(OpCodes.Call, accessorGetter));
il.Append(il.Create(OpCodes.Callvirt, propertyGetterOnAccessorReference));
il.Append(il.Create(OpCodes.Ret));
}
private void ReplaceGeneratedClassSetter(PropertyDefinition prop, TypeDefinition interfaceType, MethodReference accessorGetter)
{
//// A synthesized property setter looks like this:
//// 0: ldarg.0
//// 1: ldarg.1
//// 2: stfld <backingField>
//// 3: ret
////
//// We want to change it so it looks like this:
//// 0: ldarg.0
//// 1: ldfld _accessor
//// 2: ldarg.1
//// 4: call property setter on accessor
//// 5: ret
////
//// This is equivalent to:
//// set => Accessor.Property = value;
// Whilst we're only targeting auto-properties here, someone like PropertyChanged.Fody
// may have already come in and rewritten our IL. Lets clear everything and start from scratch.
var il = prop.SetMethod.Body.GetILProcessor();
prop.SetMethod.Body.Instructions.Clear();
prop.SetMethod.Body.Variables.Clear();
// While we can tidy up PropertyChanged.Fody IL if we're ran after it, we can't do a heck of a lot
// if they're the last one in. To combat this, we'll add our own version of [DoNotNotify] which
// PropertyChanged.Fody will respect.
prop.CustomAttributes.Add(new CustomAttribute(_propertyChanged_DoNotNotify_Ctor.Value));
var propertySetterOnAccessorReference = new MethodReference($"set_{prop.Name}", _references.Types.Void, interfaceType) { HasThis = true };
propertySetterOnAccessorReference.Parameters.Add(new ParameterDefinition(prop.PropertyType));
il.Append(il.Create(OpCodes.Ldarg_0));
il.Append(il.Create(OpCodes.Call, accessorGetter));
il.Append(il.Create(OpCodes.Ldarg_1));
il.Append(il.Create(OpCodes.Callvirt, propertySetterOnAccessorReference));
il.Append(il.Create(OpCodes.Ret));
}
private WeaveTypeResult WeaveType(TypeDefinition type)
{
_logger.Debug("Weaving " + type.Name);
var didSucceed = true;
var persistedProperties = new List<WeavePropertyResult>();
foreach (var prop in type.Properties.Where(x => x.HasThis && x.CustomAttributes.All(a => a.AttributeType.Name != "IgnoredAttribute")))
{
try
{
var weaveResult = WeaveProperty(prop, type);
if (weaveResult.Woven)
{
persistedProperties.Add(weaveResult);
}
else
{
var sequencePoint = prop.GetSequencePoint();
if (!weaveResult.ErrorMessage.IsNullOrEmpty())
{
// We only want one error point, so even though there may be more problems, we only log the first one.
_logger.Error(weaveResult.ErrorMessage, sequencePoint);
// We set didSucceed to false, but we want to continue weaving so that if there are multiple problems, they'll all be reported.
didSucceed = false;
}
else
{
if (!weaveResult.WarningMessage.IsNullOrEmpty())
{
_logger.Warning(weaveResult.WarningMessage, sequencePoint);
}
var realmAttributeNames = prop.CustomAttributes
.Select(a => a.AttributeType.Name)
.Intersect(RealmPropertyAttributes)
.OrderBy(a => a)
.Select(a => $"[{a.Replace("Attribute", string.Empty)}]")
.ToArray();
if (realmAttributeNames.Any())
{
_logger.Warning($"{type.Name}.{prop.Name} has {string.Join(", ", realmAttributeNames)} applied, but it's not persisted, so these attributes will be ignored. Skip reason: {weaveResult.SkipReason}", sequencePoint);
}
}
}
}
catch (Exception e)
{
var sequencePoint = prop.GetSequencePoint();
_logger.Error(
$"Unexpected error caught weaving property '{type.Name}.{prop.Name}': {e.Message}.\r\nCallstack:\r\n{e.StackTrace}",
sequencePoint);
return WeaveTypeResult.Error(type.Name);
}
}
if (!persistedProperties.Any())
{
_logger.Error($"Class {type.Name} is a RealmObject but has no persisted properties.", type.GetSequencePoint());
return WeaveTypeResult.Error(type.Name);
}
var pkProperty = persistedProperties.FirstOrDefault(p => p.IsPrimaryKey);
if (type.IsEmbeddedObjectInheritor(_references) && pkProperty != null)
{
_logger.Error($"Class {type.Name} is an EmbeddedObject but has a primary key {pkProperty.Property!.Name} defined.", type.GetSequencePoint());
return WeaveTypeResult.Error(type.Name);
}
if (persistedProperties.Count(p => p.IsPrimaryKey) > 1)
{
_logger.Error($"Class {type.Name} has more than one property marked with [PrimaryKey].", type.GetSequencePoint());
return WeaveTypeResult.Error(type.Name);
}
var objectConstructor = type.GetConstructors()
.SingleOrDefault(c => c.Parameters.Count == 0 && !c.IsStatic);
if (objectConstructor == null)
{
var nonDefaultConstructor = type.GetConstructors().First();
var sequencePoint = nonDefaultConstructor.DebugInformation.SequencePoints.FirstOrDefault();
_logger.Error($"Class {type.Name} must have a public constructor that takes no parameters.", sequencePoint);
return WeaveTypeResult.Error(type.Name);
}
var preserveAttribute = new CustomAttribute(_references.PreserveAttribute_Constructor);
objectConstructor.CustomAttributes.Add(preserveAttribute);
preserveAttribute = new CustomAttribute(_references.PreserveAttribute_ConstructorWithParams); // recreate so has new instance
preserveAttribute.ConstructorArguments.Add(new CustomAttributeArgument(_moduleDefinition.TypeSystem.Boolean, true)); // AllMembers
preserveAttribute.ConstructorArguments.Add(new CustomAttributeArgument(_moduleDefinition.TypeSystem.Boolean, false)); // Conditional
type.CustomAttributes.Add(preserveAttribute);
_logger.Debug($"Added [Preserve] to {type.Name} and its constructor.");
var wovenAttribute = new CustomAttribute(_references.WovenAttribute_Constructor);
TypeReference helperType = WeaveRealmObjectHelper(type, objectConstructor, persistedProperties);
wovenAttribute.ConstructorArguments.Add(new CustomAttributeArgument(_references.System_Type, helperType));
type.CustomAttributes.Add(wovenAttribute);
return didSucceed ? WeaveTypeResult.Success(type.Name, persistedProperties) : WeaveTypeResult.Error(type.Name);
}
private WeavePropertyResult WeaveProperty(PropertyDefinition prop, TypeDefinition type)
{
var columnName = prop.Name;
var mapToAttribute = prop.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == "MapToAttribute");
if (mapToAttribute != null)
{
columnName = (string)mapToAttribute.ConstructorArguments[0].Value;
}
if (prop.GetMethod == null)
{
return WeavePropertyResult.Skipped("Property has no getter");
}
var indexedAttribute = prop.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == "IndexedAttribute");
if (indexedAttribute != null)
{
if (!prop.IsIndexable(_references))
{
return WeavePropertyResult.Error($"{type.Name}.{prop.Name} is marked as [Indexed] which is only allowed on integral types as well as string, bool, DateTimeOffset, ObjectId, and Guid not on {prop.PropertyType.FullName}.");
}
if (indexedAttribute.ConstructorArguments.Count > 0)
{
var mode = (IndexType)(int)indexedAttribute.ConstructorArguments[0].Value;
switch (mode)
{
case IndexType.None:
return WeavePropertyResult.Error($"{type.Name}.{prop.Name} is marked as [Indexed(IndexType.None)] which is not allowed. If you don't wish to index the property, remove the IndexedAttribute.");
case IndexType.FullText when prop.PropertyType.FullName != StringTypeName:
return WeavePropertyResult.Error($"{type.Name}.{prop.Name} is marked as [Indexed(IndexType.FullText)] which is only allowed on string properties, not on {prop.PropertyType.FullName}.");
}
}
}
var isPrimaryKey = prop.IsPrimaryKey(_references);
if (isPrimaryKey && !_primaryKeyTypes.Contains(prop.PropertyType.FullName))
{
return WeavePropertyResult.Error($"{type.Name}.{prop.Name} is marked as [PrimaryKey] which is only allowed on byte, char, short, int, long, string, ObjectId, and Guid, not on {prop.PropertyType.FullName}.");
}
var isRequired = prop.IsRequired(_references);
if (isRequired &&
!prop.IsCollection(typeof(string)) &&
!prop.IsCollection(typeof(byte[])) &&
!prop.IsNullable() &&
prop.PropertyType.FullName != StringTypeName &&
prop.PropertyType.FullName != ByteArrayTypeName)
{
return WeavePropertyResult.Error($"{type.Name}.{prop.Name} is marked as [Required] which is only allowed on string or byte[] properties, not on {prop.PropertyType.FullName}.");
}
if (!prop.IsAutomatic())
{
if (prop.ContainsRealmObject(_references) || prop.ContainsEmbeddedObject(_references))
{
return WeavePropertyResult.Warning($"{type.Name}.{prop.Name} is not an automatic property but its type is a RealmObject/EmbeddedObject which normally indicates a relationship.");
}
if (prop.ContainsAsymmetricObject(_references))
{
return WeavePropertyResult.Warning($"{type.Name}.{prop.Name} is not an automatic property but its type is a AsymmetricObject. This usually indicates a relationship but AsymmetricObjects are not allowed to be the receiving end of any relationships.");
}
return WeavePropertyResult.Skipped("Property is not autoimplemented");
}
var backlinkAttribute = prop.CustomAttributes.FirstOrDefault(a => a.AttributeType.Name == "BacklinkAttribute");
if (backlinkAttribute != null && !prop.IsIQueryable())
{
return WeavePropertyResult.Error($"{type.Name}.{prop.Name} has [Backlink] applied, but is not IQueryable.");
}
var backingField = prop.GetBackingField();
if (backingField == null)
{
return WeavePropertyResult.Warning($"{type.Name}.{prop.Name} is an automatic property without a backing field.");
}
if (_realmValueTypes.Contains(prop.PropertyType.FullName))
{
if (prop.SetMethod == null)
{
return WeavePropertyResult.Skipped("Property has no setter");
}
var setter = isPrimaryKey ? _references.RealmObject_SetValueUnique : _references.RealmObject_SetValue;
ReplaceGetter(prop, columnName, _references.RealmObject_GetValue);
ReplaceSetter(prop, backingField, columnName, setter);
}
else if (prop.IsCollection(out var collectionType))
{
var genericArguments = ((GenericInstanceType)prop.PropertyType).GenericArguments;
var elementType = genericArguments.Last();
if (!elementType.Resolve().IsValidRealmObjectBaseInheritor(_references))
{
if (elementType.IsRealmInteger(out _, out _))
{
return WeavePropertyResult.Error($"{type.Name}.{prop.Name} is an {collectionType}<RealmInteger> which is not supported.");
}
if (!_realmValueTypes.Contains(elementType.FullName))
{
return WeavePropertyResult.Error($"{type.Name}.{prop.Name} is an {collectionType} but its generic type is {elementType.Name} which is not supported by Realm.");
}
}
else if (elementType.IsAsymmetricObjectDescendant(_references))
{
return WeavePropertyResult.Error($"{type.Name}.{prop.Name} is an {collectionType}<AsymmetricObject>, but AsymmetricObjects aren't allowed to be contained in any RealmObject inheritor.");
}
if (prop.SetMethod != null)
{
return WeavePropertyResult.Error($"{type.Name}.{prop.Name} has a setter but its type is a {collectionType} which only supports getters.");
}
switch (collectionType)
{
case RealmCollectionType.IList:
ReplaceCollectionGetter(prop, backingField, columnName,
new GenericInstanceMethod(_references.RealmObject_GetListValue) { GenericArguments = { elementType } });
break;
case RealmCollectionType.ISet:
if (elementType.Resolve().IsEmbeddedObjectInheritor(_references))
{
return WeavePropertyResult.Error($"{type.Name}.{prop.Name} is a Set<EmbeddedObject> which is not supported. Embedded objects are always unique which is why List<EmbeddedObject> already has Set semantics.");
}
ReplaceCollectionGetter(prop, backingField, columnName,
new GenericInstanceMethod(_references.RealmObject_GetSetValue) { GenericArguments = { elementType } });
break;
case RealmCollectionType.IDictionary:
var keyType = genericArguments.First();
if (keyType != _references.Types.String)
{
return WeavePropertyResult.Error($"{type.Name}.{prop.Name} is a Dictionary<{keyType.Name}, {elementType.Name}> but only string keys are currently supported by Realm.");
}
ReplaceCollectionGetter(prop, backingField, columnName,
new GenericInstanceMethod(_references.RealmObject_GetDictionaryValue) { GenericArguments = { elementType } });
break;
}
}
else if (prop.ContainsAsymmetricObject(_references))
{
return WeavePropertyResult.Error($"{type.Name}.{prop.Name} is of type AsymmetricObject, but AsymmetricObjects aren't allowed to be the receiving end of any relationship.");
}
else if (prop.ContainsRealmObject(_references) || prop.ContainsEmbeddedObject(_references))
{
if (prop.SetMethod == null)
{
return WeavePropertyResult.Warning($"{type.Name}.{prop.Name} does not have a setter but its type is a RealmObject/EmbeddedObject which normally indicates a relationship.");
}
// with casting in the _realmObject methods, should just work
ReplaceGetter(prop, columnName, _references.RealmObject_GetValue);
ReplaceSetter(prop, backingField, columnName, _references.RealmObject_SetValue);
}
else if (prop.IsIQueryable())
{
if (backlinkAttribute == null)
{
return WeavePropertyResult.Error($"{type.Name}.{prop.Name} is IQueryable, but doesn't have [Backlink] applied.");
}
if (prop.SetMethod != null)
{
return WeavePropertyResult.Error($"{type.Name}.{prop.Name} has a setter but also has [Backlink] applied, which only supports getters.");
}
if (type.IsAsymmetricObjectDescendant(_references))
{
return WeavePropertyResult.Error($"{type.Name}.{prop.Name} has [Backlink] applied which is not allowed on AsymmetricObject.");
}
var elementType = ((GenericInstanceType)prop.PropertyType).GenericArguments.Single();
var inversePropertyName = (string)backlinkAttribute.ConstructorArguments[0].Value;
var inverseProperty = elementType.Resolve().Properties.SingleOrDefault(p => p.Name == inversePropertyName);
if (inverseProperty == null || (!inverseProperty.PropertyType.IsSameAs(type) && !inverseProperty.IsCollection(type)))
{
return WeavePropertyResult.Error($"The property '{elementType.Name}.{inversePropertyName}' does not constitute a link to '{type.Name}' as described by '{type.Name}.{prop.Name}'.");
}
if (backingField is FieldDefinition backingDef)
{
// without a set; auto property has this flag we must clear
backingDef.Attributes &= ~FieldAttributes.InitOnly;
}
ReplaceBacklinksGetter(prop, backingField, columnName, elementType);
}
else if (prop.PropertyType.GetElementType().FullName == "System.Collections.Generic.List`1")
{
var genericType = ((GenericInstanceType)prop.PropertyType).GenericArguments.Single().Name;
return WeavePropertyResult.Error($"{type.Name}.{prop.Name} is declared as List<{genericType}> which is not the correct way to declare to-many relationships in Realm. If you want to persist the collection, use the interface IList<{genericType}>, otherwise annotate the property with the [Ignored] attribute.");
}
else if (prop.SetMethod == null)
{
return WeavePropertyResult.Skipped("Property has no setter");
}
else if (prop.PropertyType.FullName == "System.DateTime")
{
return WeavePropertyResult.Error($"{type.Name}.{prop.Name} is a DateTime which is not supported - use DateTimeOffset instead.");
}
else if (prop.PropertyType.FullName == "System.Nullable`1<System.DateTime>")
{
return WeavePropertyResult.Error($"{type.Name}.{prop.Name} is a DateTime? which is not supported - use DateTimeOffset? instead.");
}
else
{
return WeavePropertyResult.Error($"{type.Name}.{prop.Name} is a '{prop.PropertyType}' which is not yet supported. If that is supposed to be a model class, make sure it inherits from RealmObject/EmbeddedObject/AsymmetricObject.");
}
var preserveAttribute = new CustomAttribute(_references.PreserveAttribute_Constructor);
prop.CustomAttributes.Add(preserveAttribute);
var wovenPropertyAttribute = new CustomAttribute(_references.WovenPropertyAttribute_Constructor);
prop.CustomAttributes.Add(wovenPropertyAttribute);
var primaryKeyMsg = isPrimaryKey ? "[PrimaryKey]" : string.Empty;
var isIndexed = indexedAttribute != null;
var indexedMsg = isIndexed ? "[Indexed]" : string.Empty;
_logger.Debug($"Woven {type.Name}.{prop.Name} as a {prop.PropertyType.FullName} {primaryKeyMsg} {indexedMsg}.");
return WeavePropertyResult.Success(prop, backingField, isPrimaryKey, isIndexed);
}
private void ReplaceGetter(PropertyDefinition prop, string columnName, MethodReference getValueReference)
{
//// A synthesized property getter looks like this:
//// 0: ldarg.0
//// 1: ldfld <backingField>
//// 2: ret
//// We want to change it so it looks like this:
//// 0: ldarg.0
//// 1: call Realms.RealmObject.get_IsManaged
//// 2: brfalse.s 7
//// 3: ldarg.0
//// 4: ldstr <columnName>
//// 5: call Realms.RealmObject.GetValue
//// 6: call op_explicit prop.PropertyType
//// 7: ret
//// 8: ldarg.0
//// 9: ldfld <backingField>
//// 10: ret
//// This is roughly equivalent to:
//// if (!base.IsManaged) return this.<backingField>;
//// return base.GetValue(<columnName>);
////
//// For RealmObject targets, there's no implicit conversion from RealmValue to
//// prop.PropertyType, so we convert implicitly to RealmObjectBase, then cast.
//// This is roughly equivalent to:
//// if (!base.IsManaged) return this.<backingField>;
//// return (TargetType)*(RealmObjectBase)*base.GetValue(<columnName>);
var start = prop.GetMethod.Body.Instructions.First();
var il = prop.GetMethod.Body.GetILProcessor();
il.InsertBefore(start, il.Create(OpCodes.Ldarg_0)); // this for call
il.InsertBefore(start, il.Create(OpCodes.Call, _references.RealmObject_get_IsManaged));
il.InsertBefore(start, il.Create(OpCodes.Brfalse_S, start));
il.InsertBefore(start, il.Create(OpCodes.Ldarg_0)); // this for call
il.InsertBefore(start, il.Create(OpCodes.Ldstr, columnName)); // [stack = this | name ]
il.InsertBefore(start, il.Create(OpCodes.Call, getValueReference));
var convertType = prop.PropertyType;
if (prop.ContainsRealmObject(_references) || prop.ContainsEmbeddedObject(_references))
{
convertType = _references.RealmObjectBase;
}
if (!prop.IsRealmValue())
{
var convertMethod = new MethodReference("op_Explicit", convertType, _references.RealmValue)
{
Parameters = { new ParameterDefinition(_references.RealmValue) },
HasThis = false
};
il.InsertBefore(start, il.Create(OpCodes.Call, convertMethod));
}
// This only happens when we have a relationship - explicitly cast.
if (convertType != prop.PropertyType)
{
il.InsertBefore(start, il.Create(OpCodes.Castclass, prop.PropertyType));
}
il.InsertBefore(start, il.Create(OpCodes.Ret));
}
private static void ReplaceCollectionGetter(PropertyDefinition prop, FieldReference backingField, string columnName, MethodReference getCollectionValueReference)
{
if (backingField is FieldDefinition backingFieldDef)
{
backingFieldDef.Attributes &= ~FieldAttributes.InitOnly; // without a set; auto property has this flag we must clear
}
//// A synthesized property getter looks like this:
//// 0: ldarg.0 // load the this pointer
//// 1: ldfld <backingField>
//// 2: ret
//// We want to change it so it looks somewhat like this, in C#
////
//// if (<backingField> == null)
//// {
//// <backingField> = GetCollectionValue<T>(<columnName>);
//// }
//// // original auto-generated getter starts here
//// return <backingField>; // supplied by the generated getter
var start = prop.GetMethod.Body.Instructions.First(); // this is a label for return <backingField>;
var il = prop.GetMethod.Body.GetILProcessor();
// if (<backingField>) goto start
il.InsertBefore(start, il.Create(OpCodes.Ldarg_0));
il.InsertBefore(start, il.Create(OpCodes.Ldfld, backingField));
il.InsertBefore(start, il.Create(OpCodes.Brtrue_S, start));
// <backingField> is null -> <backingField> = GetCollectionValue<T>(<columnName>)
il.InsertBefore(start, il.Create(OpCodes.Ldarg_0));
il.InsertBefore(start, il.Create(OpCodes.Ldarg_0));
il.InsertBefore(start, il.Create(OpCodes.Ldstr, columnName));
il.InsertBefore(start, il.Create(OpCodes.Call, getCollectionValueReference));
il.InsertBefore(start, il.Create(OpCodes.Stfld, backingField));
// note that we do NOT insert a ret, unlike other weavers, as usual path branches and
// FALL THROUGH to return the backing field.
}
// WARNING
// This code setting the backing field only works if the field is settable after init
// if you don't have an automatic set; on the property, it shows in the debugger with
// Attributes Private | InitOnly Mono.Cecil.FieldAttributes
private void ReplaceBacklinksGetter(PropertyDefinition prop, FieldReference backingField, string columnName, TypeReference elementType)
{
//// A synthesized property getter looks like this:
//// 0: ldarg.0 // load the this pointer
//// 1: ldfld <backingField>
//// 2: ret
//// We want to change it so it looks somewhat like this, in C#
////
//// if (<backingField> == null)
//// {
//// if (IsManaged)
//// <backingField> = GetBacklinks<T>(<columnName>);
//// else
//// <backingField> = new Enumerable.Empty<T>.AsQueryable();
//// }
//// // original auto-generated getter starts here
//// return <backingField>; // supplied by the generated getter OR RealmObject._CopyDataFromBackingFields
var start = prop.GetMethod.Body.Instructions.First(); // this is a label for return <backingField>;
var il = prop.GetMethod.Body.GetILProcessor();
il.InsertBefore(start, il.Create(OpCodes.Ldarg_0)); // this for field ref [ -> this]
il.InsertBefore(start, il.Create(OpCodes.Ldfld, backingField)); // [ this -> field]
il.InsertBefore(start, il.Create(OpCodes.Brtrue_S, start)); // []
il.InsertBefore(start, il.Create(OpCodes.Ldarg_0)); // this for stfld in both branches [ -> this ]
il.InsertBefore(start, il.Create(OpCodes.Ldarg_0)); // this for call [ this -> this, this]
il.InsertBefore(start, il.Create(OpCodes.Call, _references.RealmObject_get_IsManaged)); // [ this, this -> this, isManaged ]
// push in the label then go relative to that - so we can forward-ref the label insert if/else blocks backwards
var labelElse = il.Create(OpCodes.Nop); // [this]
il.InsertBefore(start, labelElse); // else
il.InsertBefore(start, il.Create(OpCodes.Call, new GenericInstanceMethod(_references.System_Linq_Enumerable_Empty) { GenericArguments = { elementType } })); // [this, enumerable]
il.InsertBefore(start, il.Create(OpCodes.Call, new GenericInstanceMethod(_references.System_Linq_Queryable_AsQueryable) { GenericArguments = { elementType } })); // [this, queryable]
il.InsertBefore(start, il.Create(OpCodes.Stfld, backingField)); // [this, queryable -> ]
// fall through to start to read it back from backing field and return
// if block before else now gets inserted
il.InsertBefore(labelElse, il.Create(OpCodes.Brfalse_S, labelElse)); // [this, isManaged -> this]
il.InsertBefore(labelElse, il.Create(OpCodes.Ldarg_0)); // this for call [ this -> this, this ]
il.InsertBefore(labelElse, il.Create(OpCodes.Ldstr, columnName)); // [this, this -> this, this, name ]
il.InsertBefore(labelElse, il.Create(OpCodes.Call, new GenericInstanceMethod(_references.RealmObject_GetBacklinks) { GenericArguments = { elementType } })); // [this, this, name -> this, queryable ]
il.InsertBefore(labelElse, il.Create(OpCodes.Stfld, backingField)); // [this, queryable -> ]
il.InsertBefore(labelElse, il.Create(OpCodes.Br_S, start));
// note that we do NOT insert a ret, unlike other weavers, as usual path branches and
// FALL THROUGH to return the backing field.
}
private void ReplaceSetter(PropertyDefinition prop, FieldReference backingField, string columnName, MethodReference setValueReference)
{
//// A synthesized property setter looks like this:
//// 0: ldarg.0
//// 1: ldarg.1
//// 2: stfld <backingField>
//// 3: ret
////
//// We want to change it so it looks like this:
//// 0: ldarg.0
//// 1: call Realms.RealmObject.get_IsManaged
//// 2: brfalse.s 8
//// 3: ldarg.0
//// 4: ldstr <columnName>
//// 5: ldarg.1
//// 6: call Realms.RealmObject.SetValue<T>
//// 7: ret
//// 8: ldarg.0
//// 9: ldarg.1
//// 10: stfld <backingField>
//// 11: ret
////
//// This is roughly equivalent to:
//// if (!base.IsManaged)
//// {
//// this.<backingField> = value;
//// RaisePropertyChanged(propertyName);
//// }
//// else base.SetValue<T>(<columnName>, value);
if (setValueReference == null)
{
throw new ArgumentNullException(nameof(setValueReference));
}
// Whilst we're only targeting auto-properties here, someone like PropertyChanged.Fody
// may have already come in and rewritten our IL. Lets clear everything and start from scratch.
var il = prop.SetMethod.Body.GetILProcessor();
prop.SetMethod.Body.Instructions.Clear();
prop.SetMethod.Body.Variables.Clear();
// While we can tidy up PropertyChanged.Fody IL if we're ran after it, we can't do a heck of a lot
// if they're the last one in. To combat this, we'll add our own version of [DoNotNotify] which
// PropertyChanged.Fody will respect.
prop.CustomAttributes.Add(new CustomAttribute(_propertyChanged_DoNotNotify_Ctor.Value));
var managedSetStart = il.Create(OpCodes.Ldarg_0);
il.Append(il.Create(OpCodes.Ldarg_0));
il.Append(il.Create(OpCodes.Call, _references.RealmObject_get_IsManaged));
il.Append(il.Create(OpCodes.Brtrue_S, managedSetStart));
il.Append(il.Create(OpCodes.Ldarg_0));
il.Append(il.Create(OpCodes.Ldarg_1));
il.Append(il.Create(OpCodes.Stfld, backingField));
il.Append(il.Create(OpCodes.Ldarg_0));
il.Append(il.Create(OpCodes.Ldstr, prop.Name));
il.Append(il.Create(OpCodes.Call, _references.RealmObject_RaisePropertyChanged));
il.Append(il.Create(OpCodes.Ret));
il.Append(managedSetStart);
il.Append(il.Create(OpCodes.Ldstr, columnName));
il.Append(il.Create(OpCodes.Ldarg_1));
if (!prop.IsRealmValue())
{
var convertType = prop.PropertyType;
if (prop.ContainsRealmObject(_references) || prop.ContainsEmbeddedObject(_references))
{
convertType = _references.RealmObjectBase;
}
il.Append(il.Create(OpCodes.Call, _references.RealmValue_op_Implicit(convertType)));
}
il.Append(il.Create(OpCodes.Call, setValueReference));
il.Append(il.Create(OpCodes.Ret));
}
private TypeDefinition WeaveRealmObjectHelper(TypeDefinition realmObjectType, MethodDefinition objectConstructor, List<WeavePropertyResult> properties)
{
var helperType = new TypeDefinition(null, "RealmHelper",
TypeAttributes.Class | TypeAttributes.NestedPrivate | TypeAttributes.BeforeFieldInit,
_moduleDefinition.TypeSystem.Object);
helperType.Interfaces.Add(new InterfaceImplementation(_references.IRealmObjectHelper));
var createInstance = new MethodDefinition("CreateInstance", DefaultMethodAttributes, _references.IRealmObjectBase);
{
var il = createInstance.Body.GetILProcessor();
il.Emit(OpCodes.Newobj, objectConstructor);
il.Emit(OpCodes.Ret);
}
helperType.Methods.Add(createInstance);
var createAccessor = new MethodDefinition("CreateAccessor", DefaultMethodAttributes, _references.ManagedAccessor);
{
var il = createAccessor.Body.GetILProcessor();
il.Emit(OpCodes.Ldnull);
il.Emit(OpCodes.Ret);