/
SetPropertiesVisitor.cs
1724 lines (1481 loc) · 78.1 KB
/
SetPropertiesVisitor.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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Xml;
using Microsoft.Maui.Controls.Internals;
using Microsoft.Maui.Controls.Xaml;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;
using static Microsoft.Maui.Controls.Build.Tasks.BuildExceptionCode;
using static Mono.Cecil.Cil.Instruction;
using static Mono.Cecil.Cil.OpCodes;
namespace Microsoft.Maui.Controls.Build.Tasks
{
class SetPropertiesVisitor : IXamlNodeVisitor
{
static readonly IList<XmlName> skips = new List<XmlName>
{
XmlName.xKey,
XmlName.xTypeArguments,
XmlName.xArguments,
XmlName.xFactoryMethod,
XmlName.xName,
XmlName.xDataType
};
public SetPropertiesVisitor(ILContext context, bool stopOnResourceDictionary = false)
{
Context = context;
Module = context.Body.Method.Module;
StopOnResourceDictionary = stopOnResourceDictionary;
}
public ILContext Context { get; }
public bool StopOnResourceDictionary { get; }
public TreeVisitingMode VisitingMode => TreeVisitingMode.BottomUp;
public bool StopOnDataTemplate => true;
public bool VisitNodeOnDataTemplate => true;
public bool SkipChildren(INode node, INode parentNode) => false;
public bool IsResourceDictionary(ElementNode node)
{
var parentVar = Context.Variables[(IElementNode)node];
return parentVar.VariableType.FullName == "Microsoft.Maui.Controls.ResourceDictionary"
|| parentVar.VariableType.Resolve().BaseType?.FullName == "Microsoft.Maui.Controls.ResourceDictionary";
}
ModuleDefinition Module { get; }
public void Visit(ValueNode node, INode parentNode)
{
//TODO support Label text as element
XmlName propertyName;
if (!TryGetPropertyName(node, parentNode, out propertyName))
{
if (!IsCollectionItem(node, parentNode))
return;
string contentProperty;
if (!Context.Variables.ContainsKey((IElementNode)parentNode))
return;
var parentVar = Context.Variables[(IElementNode)parentNode];
if ((contentProperty = GetContentProperty(Context.Cache, parentVar.VariableType)) != null)
propertyName = new XmlName(((IElementNode)parentNode).NamespaceURI, contentProperty);
else
return;
}
if (TrySetRuntimeName(propertyName, Context.Variables[(IElementNode)parentNode], node))
return;
if (skips.Contains(propertyName))
return;
if (parentNode is IElementNode && ((IElementNode)parentNode).SkipProperties.Contains(propertyName))
return;
if (propertyName.Equals(XamlParser.McUri, "Ignorable"))
return;
Context.IL.Append(SetPropertyValue(Context.Variables[(IElementNode)parentNode], propertyName, node, Context, node));
}
public void Visit(MarkupNode node, INode parentNode)
{
}
public void Visit(ElementNode node, INode parentNode)
{
XmlName propertyName = XmlName.Empty;
//Simplify ListNodes with single elements
var pList = parentNode as ListNode;
if (pList != null && pList.CollectionItems.Count == 1)
{
propertyName = pList.XmlName;
parentNode = parentNode.Parent;
}
if ((propertyName != XmlName.Empty || TryGetPropertyName(node, parentNode, out propertyName)) && skips.Contains(propertyName))
return;
if (propertyName == XmlName._CreateContent)
{
SetDataTemplate((IElementNode)parentNode, node, Context, node);
return;
}
//if this node is an IMarkupExtension, invoke ProvideValue() and replace the variable
var vardef = Context.Variables[node];
var vardefref = new VariableDefinitionReference(vardef);
var localName = propertyName.LocalName;
TypeReference declaringTypeReference = null;
FieldReference bpRef = null;
var _ = false;
PropertyDefinition propertyRef = null;
if (parentNode is IElementNode && propertyName != XmlName.Empty)
{
bpRef = GetBindablePropertyReference(Context.Variables[(IElementNode)parentNode], propertyName.NamespaceURI, ref localName, out _, Context, node);
propertyRef = Context.Variables[(IElementNode)parentNode].VariableType.GetProperty(Context.Cache, pd => pd.Name == localName, out declaringTypeReference);
}
Context.IL.Append(ProvideValue(vardefref, Context, Module, node, bpRef: bpRef, propertyRef: propertyRef, propertyDeclaringTypeRef: declaringTypeReference));
if (vardef != vardefref.VariableDefinition)
{
vardef = vardefref.VariableDefinition;
Context.Body.Variables.Add(vardef);
Context.Variables[node] = vardef;
}
if (propertyName != XmlName.Empty)
{
if (skips.Contains(propertyName))
return;
if (parentNode is IElementNode && ((IElementNode)parentNode).SkipProperties.Contains(propertyName))
return;
Context.IL.Append(SetPropertyValue(Context.Variables[(IElementNode)parentNode], propertyName, node, Context, node));
}
else if (IsCollectionItem(node, parentNode) && parentNode is IElementNode)
{
var parentVar = Context.Variables[(IElementNode)parentNode];
string contentProperty;
if (CanAddToResourceDictionary(parentVar, parentVar.VariableType, node, node, Context))
{
Context.IL.Append(parentVar.LoadAs(Context.Cache, Module.GetTypeDefinition(Context.Cache, ("Microsoft.Maui.Controls", "Microsoft.Maui.Controls", "ResourceDictionary")), Module));
Context.IL.Append(AddToResourceDictionary(parentVar, node, node, Context));
}
else if ((contentProperty = GetContentProperty(Context.Cache, parentVar.VariableType)) != null)
{
var name = new XmlName(node.NamespaceURI, contentProperty);
if (skips.Contains(name))
return;
if (parentNode is IElementNode && ((IElementNode)parentNode).SkipProperties.Contains(propertyName))
return;
Context.IL.Append(SetPropertyValue(Context.Variables[(IElementNode)parentNode], name, node, Context, node));
}
// Collection element, implicit content, or implicit collection element.
else if (parentVar.VariableType.ImplementsInterface(Context.Cache, Module.ImportReference(Context.Cache, ("mscorlib", "System.Collections", "IEnumerable")))
&& parentVar.VariableType.GetMethods(Context.Cache, md => md.Name == "Add" && md.Parameters.Count == 1, Module).Any())
{
var elementType = parentVar.VariableType;
var adderTuple = elementType.GetMethods(Context.Cache, md => md.Name == "Add" && md.Parameters.Count == 1, Module).First();
var adderRef = Module.ImportReference(adderTuple.Item1);
adderRef = Module.ImportReference(adderRef.ResolveGenericParameters(adderTuple.Item2, Module));
Context.IL.Emit(Ldloc, parentVar);
Context.IL.Append(vardef.LoadAs(Context.Cache, adderRef.Parameters[0].ParameterType.ResolveGenericParameters(adderRef), Module));
Context.IL.Emit(Callvirt, adderRef);
if (adderRef.ReturnType.FullName != "System.Void")
Context.IL.Emit(Pop);
}
else
throw new BuildException(BuildExceptionCode.ContentPropertyAttributeMissing, node, null, ((IElementNode)parentNode).XmlType.Name);
}
else if (IsCollectionItem(node, parentNode) && parentNode is ListNode)
{
// IL_000d: ldloc.2
// IL_000e: callvirt instance class [mscorlib]System.Collections.Generic.IList`1<!0> class [Microsoft.Maui.Controls]Microsoft.Maui.Controls.Layout`1<class [Microsoft.Maui.Controls]Microsoft.Maui.Controls.View>::get_Children()
// IL_0013: ldloc.0
// IL_0014: callvirt instance void class [mscorlib]System.Collections.Generic.ICollection`1<class [Microsoft.Maui.Controls]Microsoft.Maui.Controls.View>::Add(!0)
var parentList = (ListNode)parentNode;
var parent = Context.Variables[((IElementNode)parentNode.Parent)];
if (skips.Contains(parentList.XmlName))
return;
if (parentNode is IElementNode && ((IElementNode)parentNode).SkipProperties.Contains(propertyName))
return;
var elementType = parent.VariableType;
var localname = parentList.XmlName.LocalName;
TypeReference propertyType;
Context.IL.Append(GetPropertyValue(parent, parentList.XmlName, Context, node, out propertyType));
if (CanAddToResourceDictionary(parent, propertyType, node, node, Context))
{
Context.IL.Append(AddToResourceDictionary(parent, node, node, Context));
return;
}
var adderTuple = propertyType.GetMethods(Context.Cache, md => md.Name == "Add" && md.Parameters.Count == 1, Module).FirstOrDefault() ??
throw new BuildException(BuildExceptionCode.AdderMissing, node, null, parent.VariableType, localname);
var adderRef = Module.ImportReference(adderTuple.Item1);
adderRef = Module.ImportReference(adderRef.ResolveGenericParameters(adderTuple.Item2, Module));
Context.IL.Append(vardef.LoadAs(Context.Cache, adderRef.Parameters[0].ParameterType.ResolveGenericParameters(adderRef), Module));
Context.IL.Emit(OpCodes.Callvirt, adderRef);
if (adderRef.ReturnType.FullName != "System.Void")
Context.IL.Emit(OpCodes.Pop);
}
}
public void Visit(RootNode node, INode parentNode)
{
}
public void Visit(ListNode node, INode parentNode)
{
}
public static bool TryGetPropertyName(INode node, INode parentNode, out XmlName name)
{
name = default(XmlName);
if (!(parentNode is IElementNode parentElement))
return false;
foreach (var kvp in parentElement.Properties)
{
if (kvp.Value != node)
continue;
name = kvp.Key;
return true;
}
return false;
}
static bool IsCollectionItem(INode node, INode parentNode)
{
if (!(parentNode is IListNode parentList))
return false;
return parentList.CollectionItems.Contains(node);
}
internal static string GetContentProperty(XamlCache cache, TypeReference typeRef)
{
var typeDef = typeRef.ResolveCached(cache);
var attributes = typeDef.CustomAttributes;
var attr =
attributes.FirstOrDefault(cad => ContentPropertyAttribute.ContentPropertyTypes.Contains(cad.AttributeType.FullName));
if (attr != null)
return attr.ConstructorArguments[0].Value as string;
if (typeDef.BaseType == null)
return null;
return GetContentProperty(cache, typeDef.BaseType);
}
public static IEnumerable<Instruction> ProvideValue(VariableDefinitionReference vardefref, ILContext context,
ModuleDefinition module, ElementNode node, FieldReference bpRef = null,
PropertyReference propertyRef = null, TypeReference propertyDeclaringTypeRef = null)
{
GenericInstanceType markupExtension;
IList<TypeReference> genericArguments;
if (vardefref.VariableDefinition.VariableType.FullName == "Microsoft.Maui.Controls.Xaml.ArrayExtension" &&
vardefref.VariableDefinition.VariableType.ImplementsGenericInterface(context.Cache, "Microsoft.Maui.Controls.Xaml.IMarkupExtension`1",
out markupExtension, out genericArguments))
{
var markExt = markupExtension.ResolveCached(context.Cache);
var provideValueInfo = markExt.Methods.First(md => md.Name == "ProvideValue");
var provideValue = module.ImportReference(provideValueInfo);
provideValue =
module.ImportReference(provideValue.ResolveGenericParameters(markupExtension, module));
var typeNode = node.Properties[new XmlName("", "Type")];
TypeReference arrayTypeRef;
if (context.TypeExtensions.TryGetValue(typeNode, out arrayTypeRef))
vardefref.VariableDefinition = new VariableDefinition(module.ImportReference(arrayTypeRef.MakeArrayType()));
else
vardefref.VariableDefinition = new VariableDefinition(module.ImportReference(genericArguments.First()));
foreach (var instruction in context.Variables[node].LoadAs(context.Cache, markupExtension, module))
yield return instruction;
foreach (var instruction in node.PushServiceProvider(context, bpRef, propertyRef, propertyDeclaringTypeRef))
yield return instruction;
yield return Instruction.Create(OpCodes.Callvirt, provideValue);
if (arrayTypeRef != null)
yield return Instruction.Create(OpCodes.Castclass, module.ImportReference(arrayTypeRef.MakeArrayType()));
yield return Instruction.Create(OpCodes.Stloc, vardefref.VariableDefinition);
}
else if (vardefref.VariableDefinition.VariableType.ImplementsGenericInterface(context.Cache, "Microsoft.Maui.Controls.Xaml.IMarkupExtension`1",
out markupExtension, out genericArguments))
{
var acceptEmptyServiceProvider = vardefref.VariableDefinition.VariableType.GetCustomAttribute(context.Cache, module, ("Microsoft.Maui.Controls", "Microsoft.Maui.Controls.Xaml", "AcceptEmptyServiceProviderAttribute")) != null;
if (vardefref.VariableDefinition.VariableType.FullName == "Microsoft.Maui.Controls.Xaml.BindingExtension"
&& (node.Properties == null || !node.Properties.ContainsKey(new XmlName("", "Source"))) //do not compile bindings if Source is set
&& bpRef != null //do not compile bindings if we're not gonna SetBinding
)
foreach (var instruction in CompileBindingPath(node, context, vardefref.VariableDefinition))
yield return instruction;
var markExt = markupExtension.ResolveCached(context.Cache);
var provideValueInfo = markExt.Methods.First(md => md.Name == "ProvideValue");
var provideValue = module.ImportReference(provideValueInfo);
provideValue =
module.ImportReference(provideValue.ResolveGenericParameters(markupExtension, module));
vardefref.VariableDefinition = new VariableDefinition(module.ImportReference(genericArguments.First()));
foreach (var instruction in context.Variables[node].LoadAs(context.Cache, markupExtension, module))
yield return instruction;
if (acceptEmptyServiceProvider)
yield return Instruction.Create(OpCodes.Ldnull);
else
foreach (var instruction in node.PushServiceProvider(context, bpRef, propertyRef, propertyDeclaringTypeRef))
yield return instruction;
yield return Instruction.Create(OpCodes.Callvirt, provideValue);
yield return Instruction.Create(OpCodes.Stloc, vardefref.VariableDefinition);
}
else if (context.Variables[node].VariableType.ImplementsInterface(context.Cache, module.ImportReference(context.Cache, ("Microsoft.Maui.Controls", "Microsoft.Maui.Controls.Xaml", "IMarkupExtension"))))
{
var acceptEmptyServiceProvider = context.Variables[node].VariableType.GetCustomAttribute(context.Cache, module, ("Microsoft.Maui.Controls", "Microsoft.Maui.Controls.Xaml", "AcceptEmptyServiceProviderAttribute")) != null;
var markupExtensionType = ("Microsoft.Maui.Controls", "Microsoft.Maui.Controls.Xaml", "IMarkupExtension");
vardefref.VariableDefinition = new VariableDefinition(module.TypeSystem.Object);
foreach (var instruction in context.Variables[node].LoadAs(context.Cache, module.GetTypeDefinition(context.Cache, markupExtensionType), module))
yield return instruction;
if (acceptEmptyServiceProvider)
yield return Create(Ldnull);
else
foreach (var instruction in node.PushServiceProvider(context, bpRef, propertyRef, propertyDeclaringTypeRef))
yield return instruction;
yield return Create(Callvirt, module.ImportMethodReference(context.Cache,
markupExtensionType,
methodName: "ProvideValue",
parameterTypes: new[] { ("System.ComponentModel", "System", "IServiceProvider") }));
yield return Create(Stloc, vardefref.VariableDefinition);
}
else if (context.Variables[node].VariableType.ImplementsInterface(context.Cache, module.ImportReference(context.Cache, ("Microsoft.Maui.Controls", "Microsoft.Maui.Controls.Xaml", "IValueProvider"))))
{
var acceptEmptyServiceProvider = context.Variables[node].VariableType.GetCustomAttribute(context.Cache, module, ("Microsoft.Maui.Controls", "Microsoft.Maui.Controls.Xaml", "AcceptEmptyServiceProviderAttribute")) != null;
var valueProviderType = context.Variables[node].VariableType;
//If the IValueProvider has a ProvideCompiledAttribute that can be resolved, shortcut this
var compiledValueProviderName = valueProviderType?.GetCustomAttribute(context.Cache, module, ("Microsoft.Maui.Controls", "Microsoft.Maui.Controls.Xaml", "ProvideCompiledAttribute"))?.ConstructorArguments?[0].Value as string;
Type compiledValueProviderType;
if (compiledValueProviderName != null && (compiledValueProviderType = Type.GetType(compiledValueProviderName)) != null)
{
var compiledValueProvider = Activator.CreateInstance(compiledValueProviderType);
var cProvideValue = typeof(ICompiledValueProvider).GetMethods().FirstOrDefault(md => md.Name == "ProvideValue");
var instructions = (IEnumerable<Instruction>)cProvideValue.Invoke(compiledValueProvider, new object[] {
vardefref,
context.Body.Method.Module,
node as BaseNode,
context});
foreach (var i in instructions)
yield return i;
yield break;
}
var valueProviderInterface = ("Microsoft.Maui.Controls", "Microsoft.Maui.Controls.Xaml", "IValueProvider");
vardefref.VariableDefinition = new VariableDefinition(module.TypeSystem.Object);
foreach (var instruction in context.Variables[node].LoadAs(context.Cache, module.GetTypeDefinition(context.Cache, valueProviderInterface), module))
yield return instruction;
if (acceptEmptyServiceProvider)
yield return Create(Ldnull);
else
foreach (var instruction in node.PushServiceProvider(context, bpRef, propertyRef, propertyDeclaringTypeRef))
yield return instruction;
yield return Create(Callvirt, module.ImportMethodReference(context.Cache,
valueProviderInterface,
methodName: "ProvideValue",
parameterTypes: new[] { ("System.ComponentModel", "System", "IServiceProvider") }));
yield return Create(Stloc, vardefref.VariableDefinition);
}
}
//Once we get compiled IValueProvider, this will move to the BindingExpression
static IEnumerable<Instruction> CompileBindingPath(ElementNode node, ILContext context, VariableDefinition bindingExt)
{
//TODO support casting operators
var module = context.Module;
if (!node.Properties.TryGetValue(new XmlName("", "Path"), out INode pathNode) && node.CollectionItems.Any())
pathNode = node.CollectionItems[0];
var path = (pathNode as ValueNode)?.Value as string;
if (!node.Properties.TryGetValue(new XmlName("", "Mode"), out INode modeNode)
|| !Enum.TryParse((modeNode as ValueNode)?.Value as string, true, out BindingMode declaredmode))
declaredmode = BindingMode.TwoWay; //meaning the mode isn't specified in the Binding extension. generate getters, setters, handlers
INode dataTypeNode = null;
IElementNode n = node;
while (n != null)
{
if (n.Properties.TryGetValue(XmlName.xDataType, out dataTypeNode))
break;
n = n.Parent as IElementNode;
}
if (dataTypeNode is null) {
context.LoggingHelper.LogWarningOrError(BuildExceptionCode.BindingWithoutDataType, context.XamlFilePath, node.LineNumber, node.LinePosition, 0, 0, null);
yield break;
}
if (dataTypeNode is ElementNode enode
&& enode.XmlType.NamespaceUri == XamlParser.X2009Uri
&& enode.XmlType.Name == nameof(Microsoft.Maui.Controls.Xaml.NullExtension))
{
context.LoggingHelper.LogWarningOrError(BuildExceptionCode.BindingWithNullDataType, context.XamlFilePath, node.LineNumber, node.LinePosition, 0, 0, null);
yield break;
}
string dataType = null;
if (dataTypeNode is ElementNode elementNode
&& elementNode.XmlType.NamespaceUri == XamlParser.X2009Uri
&& elementNode.XmlType.Name == nameof(Microsoft.Maui.Controls.Xaml.TypeExtension)
&& elementNode.Properties.ContainsKey(new XmlName("", nameof(Microsoft.Maui.Controls.Xaml.TypeExtension.TypeName)))
&& (elementNode.Properties[new XmlName("", nameof(Microsoft.Maui.Controls.Xaml.TypeExtension.TypeName))] as ValueNode)?.Value is string stringtype)
dataType = stringtype;
if ((dataTypeNode as ValueNode)?.Value is string sType)
dataType = sType;
if (dataType is null)
throw new BuildException(XDataTypeSyntax, dataTypeNode as IXmlLineInfo, null);
var prefix = dataType.Contains(":") ? dataType.Substring(0, dataType.IndexOf(":", StringComparison.Ordinal)) : "";
var namespaceuri = node.NamespaceResolver.LookupNamespace(prefix) ?? "";
if (!string.IsNullOrEmpty(prefix) && string.IsNullOrEmpty(namespaceuri))
throw new BuildException(XmlnsUndeclared, dataTypeNode as IXmlLineInfo, null, prefix);
var dtXType = new XmlType(namespaceuri, dataType, null);
var tSourceRef = dtXType.GetTypeReference(context.Cache, module, (IXmlLineInfo)node);
if (tSourceRef == null)
yield break; //throw
var properties = ParsePath(context, path, tSourceRef, node as IXmlLineInfo, module);
TypeReference tPropertyRef = tSourceRef;
if (properties != null && properties.Count > 0)
{
var lastProp = properties[properties.Count - 1];
if (lastProp.property != null)
tPropertyRef = lastProp.property.PropertyType.ResolveGenericParameters(lastProp.propDeclTypeRef);
else //array type
tPropertyRef = lastProp.propDeclTypeRef.ResolveCached(context.Cache);
}
tPropertyRef = module.ImportReference(tPropertyRef);
var valuetupleRef = context.Module.ImportReference(module.ImportReference(context.Cache, ("mscorlib", "System", "ValueTuple`2")).MakeGenericInstanceType(new[] { tPropertyRef, module.TypeSystem.Boolean }));
var funcRef = module.ImportReference(module.ImportReference(context.Cache, ("mscorlib", "System", "Func`2")).MakeGenericInstanceType(new[] { tSourceRef, valuetupleRef }));
var actionRef = module.ImportReference(module.ImportReference(context.Cache, ("mscorlib", "System", "Action`2")).MakeGenericInstanceType(new[] { tSourceRef, tPropertyRef }));
var funcObjRef = module.ImportReference(module.ImportReference(context.Cache, ("mscorlib", "System", "Func`2")).MakeGenericInstanceType(new[] { tSourceRef, module.TypeSystem.Object }));
var tupleRef = module.ImportReference(module.ImportReference(context.Cache, ("mscorlib", "System", "Tuple`2")).MakeGenericInstanceType(new[] { funcObjRef, module.TypeSystem.String }));
var typedBindingRef = module.ImportReference(module.ImportReference(context.Cache, ("Microsoft.Maui.Controls", "Microsoft.Maui.Controls.Internals", "TypedBinding`2")).MakeGenericInstanceType(new[] { tSourceRef, tPropertyRef }));
//FIXME: make sure the non-deprecated one is used
var ctorInfo = module.ImportReference(typedBindingRef.ResolveCached(context.Cache).Methods.FirstOrDefault(md =>
md.IsConstructor
&& !md.IsStatic
&& md.Parameters.Count == 3
&& !md.HasCustomAttributes(module.ImportReference(context.Cache, ("mscorlib", "System", "ObsoleteAttribute")))));
var ctorinforef = ctorInfo.MakeGeneric(typedBindingRef, funcRef, actionRef, tupleRef);
var bindingExtensionType = ("Microsoft.Maui.Controls.Xaml", "Microsoft.Maui.Controls.Xaml", "BindingExtension");
foreach (var instruction in bindingExt.LoadAs(context.Cache, module.GetTypeDefinition(context.Cache, bindingExtensionType), module))
yield return instruction;
foreach (var instruction in CompiledBindingGetGetter(tSourceRef, tPropertyRef, properties, node, context))
yield return instruction;
if (declaredmode != BindingMode.OneTime && declaredmode != BindingMode.OneWay)
{ //if the mode is explicitly 1w, or 1t, no need for setters
foreach (var instruction in CompiledBindingGetSetter(tSourceRef, tPropertyRef, properties, node, context))
yield return instruction;
}
else
yield return Create(Ldnull);
if (declaredmode != BindingMode.OneTime)
{ //if the mode is explicitly 1t, no need for handlers
foreach (var instruction in CompiledBindingGetHandlers(tSourceRef, tPropertyRef, properties, node, context))
yield return instruction;
}
else
yield return Create(Ldnull);
yield return Create(Newobj, module.ImportReference(ctorinforef));
yield return Create(Callvirt, module.ImportPropertySetterReference(context.Cache, bindingExtensionType, propertyName: "TypedBinding"));
}
static IList<(PropertyDefinition property, TypeReference propDeclTypeRef, string indexArg)> ParsePath(ILContext context, string path, TypeReference tSourceRef, IXmlLineInfo lineInfo, ModuleDefinition module)
{
if (string.IsNullOrWhiteSpace(path))
return null;
path = path.Trim(' ', '.'); //trim leading or trailing dots
var parts = path.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries);
var properties = new List<(PropertyDefinition property, TypeReference propDeclTypeRef, string indexArg)>();
var previousPartTypeRef = tSourceRef;
foreach (var part in parts)
{
var p = part;
string indexArg = null;
var lbIndex = p.IndexOf('[');
if (lbIndex != -1)
{
var rbIndex = p.LastIndexOf(']');
if (rbIndex == -1)
throw new BuildException(BuildExceptionCode.BindingIndexerNotClosed, lineInfo, null);
var argLength = rbIndex - lbIndex - 1;
if (argLength == 0)
throw new BuildException(BuildExceptionCode.BindingIndexerEmpty, lineInfo, null);
indexArg = p.Substring(lbIndex + 1, argLength).Trim();
if (indexArg.Length == 0)
throw new BuildException(BuildExceptionCode.BindingIndexerEmpty, lineInfo, null);
p = p.Substring(0, lbIndex);
p = p.Trim();
}
if (p.Length > 0)
{
var property = previousPartTypeRef.GetProperty(context.Cache, pd => pd.Name == p && pd.GetMethod != null && pd.GetMethod.IsPublic, out var propDeclTypeRef)
?? throw new BuildException(BuildExceptionCode.BindingPropertyNotFound, lineInfo, null, p, previousPartTypeRef);
properties.Add((property, propDeclTypeRef, null));
previousPartTypeRef = property.PropertyType.ResolveGenericParameters(propDeclTypeRef);
}
if (indexArg != null)
{
var defaultMemberAttribute = previousPartTypeRef.GetCustomAttribute(context.Cache, module, ("mscorlib", "System.Reflection", "DefaultMemberAttribute"));
var indexerName = defaultMemberAttribute?.ConstructorArguments?.FirstOrDefault().Value as string ?? "Item";
PropertyDefinition indexer = null;
TypeReference indexerDeclTypeRef = null;
if (int.TryParse(indexArg, out _))
indexer = previousPartTypeRef.GetProperty(context.Cache,
pd => pd.Name == indexerName
&& pd.GetMethod != null
&& TypeRefComparer.Default.Equals(pd.GetMethod.Parameters[0].ParameterType.ResolveGenericParameters(previousPartTypeRef), module.ImportReference(context.Cache, ("mscorlib", "System", "Int32")))
&& pd.GetMethod.IsPublic, out indexerDeclTypeRef);
indexer = indexer ?? previousPartTypeRef.GetProperty(context.Cache,
pd => pd.Name == indexerName
&& pd.GetMethod != null
&& TypeRefComparer.Default.Equals(pd.GetMethod.Parameters[0].ParameterType.ResolveGenericParameters(previousPartTypeRef), module.ImportReference(context.Cache, ("mscorlib", "System", "String")))
&& pd.GetMethod.IsPublic, out indexerDeclTypeRef);
indexer = indexer ?? previousPartTypeRef.GetProperty(context.Cache,
pd => pd.Name == indexerName
&& pd.GetMethod != null
&& TypeRefComparer.Default.Equals(pd.GetMethod.Parameters[0].ParameterType.ResolveGenericParameters(previousPartTypeRef), module.ImportReference(context.Cache, ("mscorlib", "System", "Object")))
&& pd.GetMethod.IsPublic, out indexerDeclTypeRef);
properties.Add((indexer, indexerDeclTypeRef, indexArg));
if (indexer != null) //the case when we index on an array, not a list
{
var indexType = indexer.GetMethod.Parameters[0].ParameterType.ResolveGenericParameters(indexerDeclTypeRef);
if (!TypeRefComparer.Default.Equals(indexType, module.TypeSystem.String) && !TypeRefComparer.Default.Equals(indexType, module.TypeSystem.Int32))
throw new BuildException(BuildExceptionCode.BindingIndexerTypeUnsupported, lineInfo, null, indexType.FullName);
previousPartTypeRef = indexer.PropertyType.ResolveGenericParameters(indexerDeclTypeRef);
}
else
previousPartTypeRef.ResolveCached(context.Cache);
}
}
return properties;
}
static IEnumerable<Instruction> DigProperties(IEnumerable<(PropertyDefinition property, TypeReference propDeclTypeRef, string indexArg)> properties, Dictionary<TypeReference, VariableDefinition> locs, Func<Instruction> fallback, IXmlLineInfo lineInfo, ModuleDefinition module)
{
var first = true;
foreach (var (property, propDeclTypeRef, indexArg) in properties)
{
if (!first && propDeclTypeRef.IsValueType)
{
var importedPropDeclTypeRef = module.ImportReference(propDeclTypeRef);
if (!locs.TryGetValue(importedPropDeclTypeRef, out var loc))
{
loc = new VariableDefinition(importedPropDeclTypeRef);
locs[importedPropDeclTypeRef] = loc;
}
yield return Create(Stloc, loc);
yield return Create(Ldloca, loc);
}
if (fallback != null && !propDeclTypeRef.IsValueType)
{
yield return Create(Dup);
yield return Create(Brfalse, fallback());
}
if (indexArg != null)
{
if (property == null && int.TryParse(indexArg, out int index)) //array
yield return Create(Ldc_I4, index);
else
{
var indexType = property.GetMethod.Parameters[0].ParameterType.ResolveGenericParameters(propDeclTypeRef);
if (TypeRefComparer.Default.Equals(indexType, module.TypeSystem.String))
yield return Create(Ldstr, indexArg);
else if (TypeRefComparer.Default.Equals(indexType, module.TypeSystem.Int32) && int.TryParse(indexArg, out index))
yield return Create(Ldc_I4, index);
else
throw new BuildException(BindingIndexerParse, lineInfo, null, indexArg, property.Name);
}
}
if (indexArg != null && property == null)
yield return Create(Ldelem_Ref);
else
{
var getMethod = module.ImportReference((module.ImportReference(property.GetMethod)).ResolveGenericParameters(propDeclTypeRef, module));
if (property.GetMethod.IsVirtual)
yield return Create(Callvirt, getMethod);
else
yield return Create(Call, getMethod);
}
first = false;
}
}
static IEnumerable<Instruction> CompiledBindingGetGetter(TypeReference tSourceRef, TypeReference tPropertyRef, IList<(PropertyDefinition property, TypeReference propDeclTypeRef, string indexArg)> properties, ElementNode node, ILContext context)
{
// .method private static hidebysig default valuetype[mscorlib] System.ValueTuple`2<string, bool> '<Main>m__0' (class ViewModel A_0) cil managed
// {
// .custom instance void class [mscorlib] System.Runtime.CompilerServices.CompilerGeneratedAttribute::'.ctor'() = (01 00 00 00 ) // ....
// IL_0000: ldarg.0
// IL_0001: dup
// IL_0002: ldnull
// IL_0003: ceq
// IL_0005: brfalse IL_0013
// IL_000a: pop
// IL_000b: ldnull
// IL_000c: ldc.i4.0
// IL_000d: newobj instance void valuetype[mscorlib]System.ValueTuple`2<string, bool>::'.ctor'(!0, !1)
// IL_0012: ret
// IL_0013: nop
// IL_0014: call instance string class ViewModel::get_Text()
// IL_0019: ldc.i4.1
// IL_001a: newobj instance void valuetype[mscorlib]System.ValueTuple`2<string, bool>::'.ctor'(!0, !1)
// IL_001f: ret
// }
var module = context.Module;
var tupleRef = module.ImportReference(module.ImportReference(context.Cache, ("mscorlib", "System", "ValueTuple`2")).MakeGenericInstanceType(new[] { tPropertyRef, module.TypeSystem.Boolean }));
var tupleCtorRef = module.ImportCtorReference(context.Cache, tupleRef, 2);
tupleCtorRef = module.ImportReference(tupleCtorRef.ResolveGenericParameters(tupleRef, module));
var getter = new MethodDefinition($"<{context.Body.Method.Name}>typedBindingsM__{context.Cache.TypedBindingCount++}",
MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.Static,
tupleRef)
{
Parameters = { new ParameterDefinition(tSourceRef) },
CustomAttributes = { new CustomAttribute(module.ImportCtorReference(context.Cache, ("mscorlib", "System.Runtime.CompilerServices", "CompilerGeneratedAttribute"), parameterTypes: null)) }
};
getter.Body.InitLocals = true;
var il = getter.Body.GetILProcessor();
if (properties == null || properties.Count == 0)
{ //return self
il.Emit(Ldarg_0);
il.Emit(Ldc_I4_1); //true
il.Emit(Newobj, tupleCtorRef);
il.Emit(Ret);
}
else
{
var locs = new Dictionary<TypeReference, VariableDefinition>();
if (tSourceRef.IsValueType)
il.Emit(Ldarga_S, (byte)0);
else
il.Emit(Ldarg_0);
Instruction pop = null;
il.Append(DigProperties(properties, locs, () =>
{
if (pop == null)
pop = Create(Pop);
return pop;
}, node as IXmlLineInfo, module));
foreach (var loc in locs.Values)
getter.Body.Variables.Add(loc);
il.Emit(Ldc_I4_1); //true
il.Emit(Newobj, tupleCtorRef);
il.Emit(Ret);
if (pop != null)
{
if (!locs.TryGetValue(tupleRef, out var defaultValueVarDef))
{
defaultValueVarDef = new VariableDefinition(tupleRef);
getter.Body.Variables.Add(defaultValueVarDef);
}
il.Append(pop);
il.Emit(Ldloca_S, defaultValueVarDef);
il.Emit(Initobj, tupleRef);
il.Emit(Ldloc, defaultValueVarDef);
il.Emit(Ret);
}
}
context.Body.Method.DeclaringType.Methods.Add(getter);
// IL_02fa: ldnull
// IL_02fb: ldftn valuetype[mscorlib]System.ValueTuple`2 <string,bool> class Test::'<Main>m__0'(class ViewModel)
// IL_0301: newobj instance void class [mscorlib] System.Func`2<class ViewModel, valuetype[mscorlib] System.ValueTuple`2<string, bool>>::'.ctor'(object, native int)
yield return Create(Ldnull);
yield return Create(Ldftn, getter);
yield return Create(Newobj, module.ImportCtorReference(context.Cache, ("mscorlib", "System", "Func`2"), paramCount: 2, classArguments: new[] { tSourceRef, tupleRef }));
}
static IEnumerable<Instruction> CompiledBindingGetSetter(TypeReference tSourceRef, TypeReference tPropertyRef, IList<(PropertyDefinition property, TypeReference propDeclTypeRef, string indexArg)> properties, ElementNode node, ILContext context)
{
if (properties == null || properties.Count == 0)
{
yield return Create(Ldnull);
yield break;
}
// .method private static hidebysig default void '<Main>m__1' (class ViewModel vm, string s) cil managed
// {
// .custom instance void class [mscorlib]System.Runtime.CompilerServices.CompilerGeneratedAttribute::'.ctor'() = (01 00 00 00 ) // ....
//
// IL_0000: ldarg.0
// IL_0001: callvirt instance class ViewModel class ViewModel::get_Model()
// IL_0006: ldarg.1
// IL_0007: callvirt instance void class ViewModel::set_Text(string)
// IL_000c: ret
// }
var module = context.Module;
var setter = new MethodDefinition($"<{context.Body.Method.Name}>typedBindingsM__{context.Cache.TypedBindingCount++}",
MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.Static,
module.TypeSystem.Void)
{
Parameters = {
new ParameterDefinition(tSourceRef),
new ParameterDefinition(tPropertyRef)
},
CustomAttributes = {
new CustomAttribute (module.ImportCtorReference(context.Cache, ("mscorlib", "System.Runtime.CompilerServices", "CompilerGeneratedAttribute"), parameterTypes: null))
}
};
setter.Body.InitLocals = true;
var il = setter.Body.GetILProcessor();
if (!properties.Any() || properties.Last().property == null || properties.Last().property.SetMethod == null)
{
yield return Create(Ldnull); //throw or not ?
yield break;
}
var setterRef = module.ImportReference(properties.Last().property.SetMethod);
setterRef = module.ImportReference(setterRef.ResolveGenericParameters(properties.Last().propDeclTypeRef, module));
if (tSourceRef.IsValueType)
il.Emit(Ldarga_S, (byte)0);
else
il.Emit(Ldarg_0);
var locs = new Dictionary<TypeReference, VariableDefinition>();
Instruction pop = null;
il.Append(DigProperties(properties.Take(properties.Count - 1), locs, () =>
{
if (pop == null)
pop = Instruction.Create(Pop);
return pop;
}, node as IXmlLineInfo, module));
foreach (var loc in locs.Values)
setter.Body.Variables.Add(loc);
(PropertyDefinition lastProperty, TypeReference lastPropDeclTypeRef, string lastIndexArg) = properties.Last();
if (lastPropDeclTypeRef.IsValueType)
{
var importedPropDeclTypeRef = module.ImportReference(lastPropDeclTypeRef);
if (!locs.TryGetValue(importedPropDeclTypeRef, out var loc))
{
loc = new VariableDefinition(importedPropDeclTypeRef);
setter.Body.Variables.Add(loc);
}
il.Emit(Stloc, loc);
il.Emit(Ldloca, loc);
}
else
{
if (pop == null)
pop = Instruction.Create(Pop);
il.Emit(Dup);
il.Emit(Brfalse, pop);
}
if (lastIndexArg != null)
{
var indexType = lastProperty.GetMethod.Parameters[0].ParameterType.ResolveGenericParameters(lastPropDeclTypeRef);
if (TypeRefComparer.Default.Equals(indexType, module.TypeSystem.String))
il.Emit(Ldstr, lastIndexArg);
else if (TypeRefComparer.Default.Equals(indexType, module.TypeSystem.Int32))
{
if (!int.TryParse(lastIndexArg, out int index))
throw new BuildException(BindingIndexerParse, node as IXmlLineInfo, null, lastIndexArg, lastProperty.Name);
il.Emit(Ldc_I4, index);
}
}
il.Emit(Ldarg_1);
if (properties.Last().property.SetMethod.IsVirtual)
il.Emit(Callvirt, setterRef);
else
il.Emit(Call, setterRef);
il.Emit(Ret);
if (pop != null)
{
il.Append(pop);
il.Emit(Ret);
}
context.Body.Method.DeclaringType.Methods.Add(setter);
// IL_0024: ldnull
// IL_0025: ldftn void class Test::'<Main>m__1'(class ViewModel, string)
// IL_002b: newobj instance void class [mscorlib]System.Action`2<class ViewModel, string>::'.ctor'(object, native int)
yield return Create(Ldnull);
yield return Create(Ldftn, setter);
yield return Create(Newobj, module.ImportCtorReference(context.Cache, ("mscorlib", "System", "Action`2"),
paramCount: 2,
classArguments:
new[] { tSourceRef, tPropertyRef }));
}
static IEnumerable<Instruction> CompiledBindingGetHandlers(TypeReference tSourceRef, TypeReference tPropertyRef, IList<(PropertyDefinition property, TypeReference propDeclTypeRef, string indexArg)> properties, ElementNode node, ILContext context)
{
// .method private static hidebysig default object '<Main>m__2'(class ViewModel vm) cil managed {
// .custom instance void class [mscorlib] System.Runtime.CompilerServices.CompilerGeneratedAttribute::'.ctor'() = (01 00 00 00 ) // ....
// IL_0000: ldarg.0
// IL_0001: ret
// } // end of method Test::<Main>m__2
// .method private static hidebysig default object '<Main>m__3' (class ViewModel vm) cil managed {
// .custom instance void class [mscorlib] System.Runtime.CompilerServices.CompilerGeneratedAttribute::'.ctor'() = (01 00 00 00 ) // ....
// IL_0000: ldarg.0
// IL_0001: callvirt instance class ViewModel class ViewModel::get_Model()
// IL_0006: ret
// }
var module = context.Module;
var partGetters = new List<MethodDefinition>();
if (properties == null || properties.Count == 0)
{
yield return Create(Ldnull);
yield break;
}
for (int i = 0; i < properties.Count; i++)
{
var tuple = properties[i];
var partGetter = new MethodDefinition($"<{context.Body.Method.Name}>typedBindingsM__{context.Cache.TypedBindingCount++}", MethodAttributes.Private | MethodAttributes.HideBySig | MethodAttributes.Static, module.TypeSystem.Object)
{
Parameters = {
new ParameterDefinition(tSourceRef)
},
CustomAttributes = {
new CustomAttribute (module.ImportCtorReference(context.Cache, ("mscorlib", "System.Runtime.CompilerServices", "CompilerGeneratedAttribute"), parameterTypes: null))
}
};
partGetter.Body.InitLocals = true;
var il = partGetter.Body.GetILProcessor();
if (i == 0)
{ //return self
il.Emit(Ldarg_0);
if (tSourceRef.IsValueType)
il.Emit(Box, module.ImportReference(tSourceRef));
il.Emit(Ret);
context.Body.Method.DeclaringType.Methods.Add(partGetter);
partGetters.Add(partGetter);
continue;
}
if (tSourceRef.IsValueType)
il.Emit(Ldarga_S, (byte)0);
else
il.Emit(Ldarg_0);
var lastGetterTypeRef = properties[i - 1].property.PropertyType;
var locs = new Dictionary<TypeReference, VariableDefinition>();
il.Append(DigProperties(properties.Take(i), locs, null, node as IXmlLineInfo, module));
foreach (var loc in locs.Values)
partGetter.Body.Variables.Add(loc);
if (lastGetterTypeRef.IsValueType)
il.Emit(Box, module.ImportReference(lastGetterTypeRef));
il.Emit(Ret);
context.Body.Method.DeclaringType.Methods.Add(partGetter);
partGetters.Add(partGetter);
}
var funcObjRef = context.Module.ImportReference(module.ImportReference(context.Cache, ("mscorlib", "System", "Func`2")).MakeGenericInstanceType(new[] { tSourceRef, module.TypeSystem.Object }));
var tupleRef = context.Module.ImportReference(module.ImportReference(context.Cache, ("mscorlib", "System", "Tuple`2")).MakeGenericInstanceType(new[] { funcObjRef, module.TypeSystem.String }));
var funcCtor = module.ImportReference(funcObjRef.ResolveCached(context.Cache).GetConstructors().First());
funcCtor = funcCtor.MakeGeneric(funcObjRef, new[] { tSourceRef, module.TypeSystem.Object });
var tupleCtor = module.ImportReference(tupleRef.ResolveCached(context.Cache).GetConstructors().First());
tupleCtor = tupleCtor.MakeGeneric(tupleRef, new[] { funcObjRef, module.TypeSystem.String });
// IL_003a: ldc.i4.2
// IL_003b: newarr class [mscorlib] System.Tuple`2<class [mscorlib]System.Func`2<class ViewModel,object>,string>
// IL_0040: dup
// IL_0041: ldc.i4.0
// IL_0049: ldnull
// IL_004a: ldftn object class Test::'<Main>m__2'(class ViewModel)
// IL_0050: newobj instance void class [mscorlib]System.Func`2<class ViewModel, object>::'.ctor'(object, native int)
// IL_005f: ldstr "Model"
// IL_0064: newobj instance void class [mscorlib]System.Tuple`2<class [mscorlib]System.Func`2<class ViewModel, object>, string>::'.ctor'(!0, !1)
// IL_0069: stelem.ref
// IL_006a: dup
// IL_006b: ldc.i4.1
// IL_0073: ldnull
// IL_0074: ldftn object class Test::'<Main>m__3'(class ViewModel)
// IL_007a: newobj instance void class [mscorlib]System.Func`2<class ViewModel, object>::'.ctor'(object, native int)
// IL_0089: ldstr "Text"
// IL_008e: newobj instance void class [mscorlib]System.Tuple`2<class [mscorlib]System.Func`2<class ViewModel, object>, string>::'.ctor'(!0, !1)
// IL_0093: stelem.ref
yield return Create(Ldc_I4, properties.Count);
yield return Create(Newarr, tupleRef);
for (var i = 0; i < properties.Count; i++)
{
if (properties[i].property == null)
continue;
yield return Create(Dup);
yield return Create(Ldc_I4, i);
yield return Create(Ldnull);
yield return Create(Ldftn, partGetters[i]);
yield return Create(Newobj, module.ImportReference(funcCtor));
yield return Create(Ldstr, properties[i].Item1.Name);
yield return Create(Newobj, module.ImportReference(tupleCtor));
yield return Create(Stelem_Ref);
}
}
public static IEnumerable<Instruction> SetPropertyValue(VariableDefinition parent, XmlName propertyName, INode valueNode, ILContext context, IXmlLineInfo iXmlLineInfo)
{
var localName = propertyName.LocalName;
var bpRef = GetBindablePropertyReference(parent, propertyName.NamespaceURI, ref localName, out System.Boolean attached, context, iXmlLineInfo);
//If the target is an event, connect
if (CanConnectEvent(parent, localName, valueNode, attached, context))
return ConnectEvent(parent, localName, valueNode, iXmlLineInfo, context);
//If Value is DynamicResource, SetDynamicResource
if (CanSetDynamicResource(bpRef, valueNode, context))
return SetDynamicResource(parent, bpRef, valueNode as IElementNode, iXmlLineInfo, context);
//If Value is a BindingBase and target is a BP, SetBinding
if (CanSetBinding(bpRef, valueNode, context))
return SetBinding(parent, bpRef, valueNode as IElementNode, iXmlLineInfo, context);
//If it's a BP, SetValue ()
if (CanSetValue(bpRef, attached, valueNode, iXmlLineInfo, context))
return SetValue(parent, bpRef, valueNode, iXmlLineInfo, context);
//If it's a property, set it
if (CanSet(parent, localName, valueNode, context))
return Set(parent, localName, valueNode, iXmlLineInfo, context);
//If it's an already initialized property, add to it
if (CanAdd(parent, propertyName, valueNode, iXmlLineInfo, context))
return Add(parent, propertyName, valueNode, iXmlLineInfo, context);
throw new BuildException(MemberResolution, iXmlLineInfo, null, localName);
}
public static IEnumerable<Instruction> GetPropertyValue(VariableDefinition parent, XmlName propertyName, ILContext context, IXmlLineInfo lineInfo, out TypeReference propertyType)
{
var module = context.Body.Method.Module;
var localName = propertyName.LocalName;
bool attached;
var bpRef = GetBindablePropertyReference(parent, propertyName.NamespaceURI, ref localName, out attached, context, lineInfo);
//If it's a BP, GetValue ()
if (CanGetValue(parent, bpRef, attached, lineInfo, context, out _))
return GetValue(parent, bpRef, lineInfo, context, out propertyType);
//If it's a property, set it
if (CanGet(parent, localName, context, out _))
return Get(parent, localName, lineInfo, context, out propertyType);
throw new BuildException(PropertyResolution, lineInfo, null, localName, parent.VariableType.FullName);
}
static FieldReference GetBindablePropertyReference(VariableDefinition parent, string namespaceURI, ref string localName, out bool attached, ILContext context, IXmlLineInfo iXmlLineInfo)