-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMSDynamicObject.cs
933 lines (825 loc) · 32.2 KB
/
MSDynamicObject.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
#if false
/* ****************************************************************************
*
* Copyright (c) Microsoft Corporation.
*
* This source code is subject to terms and conditions of the Apache License, Version 2.0. A
* copy of the license can be found in the License.html file at the root of this distribution. If
* you cannot locate the Apache License, Version 2.0, please send an email to
* dlr@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
* by the terms of the Apache License, Version 2.0.
*
* You must not remove this notice, or any other, from this software.
*
*
* ***************************************************************************/
#if CLR2
using Microsoft.Scripting.Ast;
#else
using System.Linq.Expressions;
#endif
using System;
using System.Diagnostics;
using System.Dynamic;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace SqlProfiler
{
/// <summary>
/// Provides a simple class that can be inherited from to create an object with dynamic behavior
/// at runtime. Subclasses can override the various binder methods (GetMember, SetMember, Call, etc...)
/// to provide custom behavior that will be invoked at runtime.
///
/// If a method is not overridden then the DynamicObject does not directly support that behavior and
/// the call site will determine how the binding should be performed.
/// </summary>
#if !SILVERLIGHT
[Serializable]
#endif
public class MSDynamicObject : IDynamicMetaObjectProvider
{
/// <summary>
/// Enables derived types to create a new instance of DynamicObject. DynamicObject instances cannot be
/// directly instantiated because they have no implementation of dynamic behavior.
/// </summary>
protected MSDynamicObject()
{
}
#region Public Virtual APIs
/// <summary>
/// Provides the implementation of getting a member. Derived classes can override
/// this method to customize behavior. When not overridden the call site requesting the
/// binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="result">The result of the get operation.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
public virtual bool TryGetMember(GetMemberBinder binder, out object result)
{
result = null;
return false;
}
/// <summary>
/// Provides the implementation of setting a member. Derived classes can override
/// this method to customize behavior. When not overridden the call site requesting the
/// binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="value">The value to set.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
public virtual bool TrySetMember(SetMemberBinder binder, object value)
{
return false;
}
/// <summary>
/// Provides the implementation of deleting a member. Derived classes can override
/// this method to customize behavior. When not overridden the call site requesting the
/// binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
public virtual bool TryDeleteMember(DeleteMemberBinder binder)
{
return false;
}
/// <summary>
/// Provides the implementation of calling a member. Derived classes can override
/// this method to customize behavior. When not overridden the call site requesting the
/// binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="args">The arguments to be used for the invocation.</param>
/// <param name="result">The result of the invocation.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
public virtual bool TryInvokeMember(InvokeMemberBinder binder, object[] args, out object result)
{
result = null;
return false;
}
/// <summary>
/// Provides the implementation of converting the DynamicObject to another type. Derived classes
/// can override this method to customize behavior. When not overridden the call site
/// requesting the binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="result">The result of the conversion.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
public virtual bool TryConvert(ConvertBinder binder, out object result)
{
result = null;
return false;
}
/// <summary>
/// Provides the implementation of creating an instance of the DynamicObject. Derived classes
/// can override this method to customize behavior. When not overridden the call site requesting
/// the binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="args">The arguments used for creation.</param>
/// <param name="result">The created instance.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
public virtual bool TryCreateInstance(CreateInstanceBinder binder, object[] args, out object result)
{
result = null;
return false;
}
/// <summary>
/// Provides the implementation of invoking the DynamicObject. Derived classes can
/// override this method to customize behavior. When not overridden the call site requesting
/// the binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="args">The arguments to be used for the invocation.</param>
/// <param name="result">The result of the invocation.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
public virtual bool TryInvoke(InvokeBinder binder, object[] args, out object result)
{
result = null;
return false;
}
/// <summary>
/// Provides the implementation of performing a binary operation. Derived classes can
/// override this method to customize behavior. When not overridden the call site requesting
/// the binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="arg">The right operand for the operation.</param>
/// <param name="result">The result of the operation.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
public virtual bool TryBinaryOperation(BinaryOperationBinder binder, object arg, out object result)
{
result = null;
return false;
}
/// <summary>
/// Provides the implementation of performing a unary operation. Derived classes can
/// override this method to customize behavior. When not overridden the call site requesting
/// the binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="result">The result of the operation.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
public virtual bool TryUnaryOperation(UnaryOperationBinder binder, out object result)
{
result = null;
return false;
}
/// <summary>
/// Provides the implementation of performing a get index operation. Derived classes can
/// override this method to customize behavior. When not overridden the call site requesting
/// the binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="indexes">The indexes to be used.</param>
/// <param name="result">The result of the operation.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
public virtual bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result)
{
result = null;
return false;
}
/// <summary>
/// Provides the implementation of performing a set index operation. Derived classes can
/// override this method to custmize behavior. When not overridden the call site requesting
/// the binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="indexes">The indexes to be used.</param>
/// <param name="value">The value to set.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1007:UseGenericsWhereAppropriate")]
public virtual bool TrySetIndex(SetIndexBinder binder, object[] indexes, object value)
{
return false;
}
/// <summary>
/// Provides the implementation of performing a delete index operation. Derived classes
/// can override this method to custmize behavior. When not overridden the call site
/// requesting the binder determines the behavior.
/// </summary>
/// <param name="binder">The binder provided by the call site.</param>
/// <param name="indexes">The indexes to be deleted.</param>
/// <returns>true if the operation is complete, false if the call site should determine behavior.</returns>
public virtual bool TryDeleteIndex(DeleteIndexBinder binder, object[] indexes)
{
return false;
}
/// <summary>
/// Returns the enumeration of all dynamic member names.
/// </summary>
/// <returns>The list of dynamic member names.</returns>
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")]
public virtual System.Collections.Generic.IEnumerable<string> GetDynamicMemberNames()
{
return new string[0];
}
#endregion
#region MetaDynamic
private sealed class MetaDynamic : DynamicMetaObject
{
internal MetaDynamic(Expression expression, MSDynamicObject value)
: base(expression, BindingRestrictions.Empty, value)
{
}
public override System.Collections.Generic.IEnumerable<string> GetDynamicMemberNames()
{
return Value.GetDynamicMemberNames();
}
public override DynamicMetaObject BindGetMember(GetMemberBinder binder)
{
if (IsOverridden("TryGetMember"))
{
return CallMethodWithResult("TryGetMember", binder, NoArgs, (e) => binder.FallbackGetMember(this, e));
}
return base.BindGetMember(binder);
}
public override DynamicMetaObject BindSetMember(SetMemberBinder binder, DynamicMetaObject value)
{
if (IsOverridden("TrySetMember"))
{
return CallMethodReturnLast("TrySetMember", binder, NoArgs, value.Expression, (e) => binder.FallbackSetMember(this, value, e));
}
return base.BindSetMember(binder, value);
}
public override DynamicMetaObject BindDeleteMember(DeleteMemberBinder binder)
{
if (IsOverridden("TryDeleteMember"))
{
return CallMethodNoResult("TryDeleteMember", binder, NoArgs, (e) => binder.FallbackDeleteMember(this, e));
}
return base.BindDeleteMember(binder);
}
public override DynamicMetaObject BindConvert(ConvertBinder binder)
{
if (IsOverridden("TryConvert"))
{
return CallMethodWithResult("TryConvert", binder, NoArgs, (e) => binder.FallbackConvert(this, e));
}
return base.BindConvert(binder);
}
public override DynamicMetaObject BindInvokeMember(InvokeMemberBinder binder, DynamicMetaObject[] args)
{
// Generate a tree like:
//
// {
// object result;
// TryInvokeMember(payload, out result)
// ? result
// : TryGetMember(payload, out result)
// ? FallbackInvoke(result)
// : fallbackResult
// }
//
// Then it calls FallbackInvokeMember with this tree as the
// "error", giving the language the option of using this
// tree or doing .NET binding.
//
Fallback fallback = e => binder.FallbackInvokeMember(this, args, e);
var call = BuildCallMethodWithResult(
"TryInvokeMember",
binder,
/*DynamicMetaObject.*/GetExpressions(args),
BuildCallMethodWithResult(
"TryGetMember",
new GetBinderAdapter(binder),
NoArgs,
fallback(null),
(e) => binder.FallbackInvoke(e, args, null)
),
null
);
var retval = fallback(call);
return retval;
}
public override DynamicMetaObject BindCreateInstance(CreateInstanceBinder binder, DynamicMetaObject[] args)
{
if (IsOverridden("TryCreateInstance"))
{
return CallMethodWithResult("TryCreateInstance", binder, /*DynamicMetaObject.*/GetExpressions(args), (e) => binder.FallbackCreateInstance(this, args, e));
}
return base.BindCreateInstance(binder, args);
}
public override DynamicMetaObject BindInvoke(InvokeBinder binder, DynamicMetaObject[] args)
{
if (IsOverridden("TryInvoke"))
{
return CallMethodWithResult("TryInvoke", binder, /*DynamicMetaObject.*/GetExpressions(args), (e) => binder.FallbackInvoke(this, args, e));
}
return base.BindInvoke(binder, args);
}
public override DynamicMetaObject BindBinaryOperation(BinaryOperationBinder binder, DynamicMetaObject arg)
{
if (IsOverridden("TryBinaryOperation"))
{
return CallMethodWithResult("TryBinaryOperation", binder, /*DynamicMetaObject.*/GetExpressions(new DynamicMetaObject[] { arg }), (e) => binder.FallbackBinaryOperation(this, arg, e));
}
return base.BindBinaryOperation(binder, arg);
}
public override DynamicMetaObject BindUnaryOperation(UnaryOperationBinder binder)
{
if (IsOverridden("TryUnaryOperation"))
{
return CallMethodWithResult("TryUnaryOperation", binder, NoArgs, (e) => binder.FallbackUnaryOperation(this, e));
}
return base.BindUnaryOperation(binder);
}
public override DynamicMetaObject BindGetIndex(GetIndexBinder binder, DynamicMetaObject[] indexes)
{
if (IsOverridden("TryGetIndex"))
{
return CallMethodWithResult("TryGetIndex", binder, /*DynamicMetaObject.*/GetExpressions(indexes), (e) => binder.FallbackGetIndex(this, indexes, e));
}
return base.BindGetIndex(binder, indexes);
}
public override DynamicMetaObject BindSetIndex(SetIndexBinder binder, DynamicMetaObject[] indexes, DynamicMetaObject value)
{
if (IsOverridden("TrySetIndex"))
{
return CallMethodReturnLast("TrySetIndex", binder, /*DynamicMetaObject.*/GetExpressions(indexes), value.Expression, (e) => binder.FallbackSetIndex(this, indexes, value, e));
}
return base.BindSetIndex(binder, indexes, value);
}
public override DynamicMetaObject BindDeleteIndex(DeleteIndexBinder binder, DynamicMetaObject[] indexes)
{
if (IsOverridden("TryDeleteIndex"))
{
return CallMethodNoResult("TryDeleteIndex", binder, /*DynamicMetaObject.*/GetExpressions(indexes), (e) => binder.FallbackDeleteIndex(this, indexes, e));
}
return base.BindDeleteIndex(binder, indexes);
}
private delegate DynamicMetaObject Fallback(DynamicMetaObject errorSuggestion);
private readonly static Expression[] NoArgs = new Expression[0];
private static Expression[] GetConvertedArgs(params Expression[] args)
{
ReadOnlyCollectionBuilder<Expression> paramArgs = new ReadOnlyCollectionBuilder<Expression>(args.Length);
for (int i = 0; i < args.Length; i++)
{
paramArgs.Add(Expression.Convert(args[i], typeof(object)));
}
return paramArgs.ToArray();
}
/// <summary>
/// Helper method for generating expressions that assign byRef call
/// parameters back to their original variables
/// </summary>
private static Expression ReferenceArgAssign(Expression callArgs, Expression[] args)
{
ReadOnlyCollectionBuilder<Expression> block = null;
for (int i = 0; i < args.Length; i++)
{
ContractUtils.Requires(args[i] is ParameterExpression);
if (((ParameterExpression)args[i]).IsByRef)
{
if (block == null)
block = new ReadOnlyCollectionBuilder<Expression>();
block.Add(
Expression.Assign(
args[i],
Expression.Convert(
Expression.ArrayIndex(
callArgs,
Expression.Constant(i)
),
args[i].Type
)
)
);
}
}
if (block != null)
return Expression.Block(block);
else
return Expression.Empty();
}
/// <summary>
/// Helper method for generating arguments for calling methods
/// on DynamicObject. parameters is either a list of ParameterExpressions
/// to be passed to the method as an object[], or NoArgs to signify that
/// the target method takes no object[] parameter.
/// </summary>
private static Expression[] BuildCallArgs(DynamicMetaObjectBinder binder, Expression[] parameters, Expression arg0, Expression arg1)
{
if (!object.ReferenceEquals(parameters, NoArgs))
return arg1 != null ? new Expression[] { Constant(binder), arg0, arg1 } : new Expression[] { Constant(binder), arg0 };
else
return arg1 != null ? new Expression[] { Constant(binder), arg1 } : new Expression[] { Constant(binder) };
}
private static ConstantExpression Constant(DynamicMetaObjectBinder binder)
{
Type t = binder.GetType();
while (!t.IsVisible)
{
t = t.BaseType;
}
return Expression.Constant(binder, t);
}
/// <summary>
/// Helper method for generating a MetaObject which calls a
/// specific method on Dynamic that returns a result
/// </summary>
private DynamicMetaObject CallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback)
{
return CallMethodWithResult(methodName, binder, args, fallback, null);
}
/// <summary>
/// Helper method for generating a MetaObject which calls a
/// specific method on Dynamic that returns a result
/// </summary>
private DynamicMetaObject CallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback, Fallback fallbackInvoke)
{
//
// First, call fallback to do default binding
// This produces either an error or a call to a .NET member
//
DynamicMetaObject fallbackResult = fallback(null);
var callDynamic = BuildCallMethodWithResult(methodName, binder, args, fallbackResult, fallbackInvoke);
//
// Now, call fallback again using our new MO as the error
// When we do this, one of two things can happen:
// 1. Binding will succeed, and it will ignore our call to
// the dynamic method, OR
// 2. Binding will fail, and it will use the MO we created
// above.
//
return fallback(callDynamic);
}
/// <summary>
/// Helper method for generating a MetaObject which calls a
/// specific method on DynamicObject that returns a result.
///
/// args is either an array of arguments to be passed
/// to the method as an object[] or NoArgs to signify that
/// the target method takes no parameters.
/// </summary>
private DynamicMetaObject BuildCallMethodWithResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, DynamicMetaObject fallbackResult, Fallback fallbackInvoke)
{
if (!IsOverridden(methodName))
{
return fallbackResult;
}
//
// Build a new expression like:
// {
// object result;
// TryGetMember(payload, out result) ? fallbackInvoke(result) : fallbackResult
// }
//
var result = Expression.Parameter(typeof(object), null);
ParameterExpression callArgs = methodName != "TryBinaryOperation" ? Expression.Parameter(typeof(object[]), null) : Expression.Parameter(typeof(object), null);
var callArgsValue = GetConvertedArgs(args);
var resultMO = new DynamicMetaObject(result, BindingRestrictions.Empty);
// Need to add a conversion if calling TryConvert
if (binder.ReturnType != typeof(object))
{
Debug.Assert(binder is ConvertBinder && fallbackInvoke == null);
var convert = Expression.Convert(resultMO.Expression, binder.ReturnType);
// will always be a cast or unbox
Debug.Assert(convert.Method == null);
#if !SILVERLIGHT
// Prepare a good exception message in case the convert will fail
string convertFailed = string.Format("DynamicObjectResultNotAssignable {0} {1} {2}",
this.Value.GetType(),
binder.GetType(),
binder.ReturnType
);
Expression condition;
// If the return type can not be assigned null then just check for type assignablity otherwise allow null.
if (binder.ReturnType.IsValueType && Nullable.GetUnderlyingType(binder.ReturnType) == null)
{
condition = Expression.TypeIs(resultMO.Expression, binder.ReturnType);
}
else
{
condition = Expression.OrElse(
Expression.Equal(resultMO.Expression, Expression.Constant(null)),
Expression.TypeIs(resultMO.Expression, binder.ReturnType));
}
var checkedConvert = Expression.Condition(
condition,
convert,
Expression.Throw(
Expression.New(typeof(InvalidCastException).GetConstructor(new Type[] { typeof(string) }),
Expression.Call(
typeof(string).GetMethod("Format", new Type[] { typeof(string), typeof(object[]) }),
Expression.Constant(convertFailed),
Expression.NewArrayInit(typeof(object),
Expression.Condition(
Expression.Equal(resultMO.Expression, Expression.Constant(null)),
Expression.Constant("null"),
Expression.Call(
resultMO.Expression,
typeof(object).GetMethod("GetType")
),
typeof(object)
)
)
)
),
binder.ReturnType
),
binder.ReturnType
);
#else
var checkedConvert = convert;
#endif
resultMO = new DynamicMetaObject(checkedConvert, resultMO.Restrictions);
}
if (fallbackInvoke != null)
{
resultMO = fallbackInvoke(resultMO);
}
var callDynamic = new DynamicMetaObject(
Expression.Block(
new[] { result, callArgs },
methodName != "TryBinaryOperation" ? Expression.Assign(callArgs, Expression.NewArrayInit(typeof(object), callArgsValue)) : Expression.Assign(callArgs, callArgsValue[0]),
Expression.Condition(
Expression.Call(
GetLimitedSelf(),
typeof(MSDynamicObject).GetMethod(methodName),
BuildCallArgs(
binder,
args,
callArgs,
result
)
),
Expression.Block(
methodName != "TryBinaryOperation" ? ReferenceArgAssign(callArgs, args) : Expression.Empty(),
resultMO.Expression
),
fallbackResult.Expression,
binder.ReturnType
)
),
GetRestrictions().Merge(resultMO.Restrictions).Merge(fallbackResult.Restrictions)
);
return callDynamic;
}
/// <summary>
/// Helper method for generating a MetaObject which calls a
/// specific method on Dynamic, but uses one of the arguments for
/// the result.
///
/// args is either an array of arguments to be passed
/// to the method as an object[] or NoArgs to signify that
/// the target method takes no parameters.
/// </summary>
private DynamicMetaObject CallMethodReturnLast(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Expression value, Fallback fallback)
{
//
// First, call fallback to do default binding
// This produces either an error or a call to a .NET member
//
DynamicMetaObject fallbackResult = fallback(null);
//
// Build a new expression like:
// {
// object result;
// TrySetMember(payload, result = value) ? result : fallbackResult
// }
//
var result = Expression.Parameter(typeof(object), null);
var callArgs = Expression.Parameter(typeof(object[]), null);
var callArgsValue = GetConvertedArgs(args);
var callDynamic = new DynamicMetaObject(
Expression.Block(
new[] { result, callArgs },
Expression.Assign(callArgs, Expression.NewArrayInit(typeof(object), callArgsValue)),
Expression.Condition(
Expression.Call(
GetLimitedSelf(),
typeof(MSDynamicObject).GetMethod(methodName),
BuildCallArgs(
binder,
args,
callArgs,
Expression.Assign(result, Expression.Convert(value, typeof(object)))
)
),
Expression.Block(
ReferenceArgAssign(callArgs, args),
result
),
fallbackResult.Expression,
typeof(object)
)
),
GetRestrictions().Merge(fallbackResult.Restrictions)
);
//
// Now, call fallback again using our new MO as the error
// When we do this, one of two things can happen:
// 1. Binding will succeed, and it will ignore our call to
// the dynamic method, OR
// 2. Binding will fail, and it will use the MO we created
// above.
//
return fallback(callDynamic);
}
/// <summary>
/// Helper method for generating a MetaObject which calls a
/// specific method on Dynamic, but uses one of the arguments for
/// the result.
///
/// args is either an array of arguments to be passed
/// to the method as an object[] or NoArgs to signify that
/// the target method takes no parameters.
/// </summary>
private DynamicMetaObject CallMethodNoResult(string methodName, DynamicMetaObjectBinder binder, Expression[] args, Fallback fallback)
{
//
// First, call fallback to do default binding
// This produces either an error or a call to a .NET member
//
DynamicMetaObject fallbackResult = fallback(null);
var callArgs = Expression.Parameter(typeof(object[]), null);
var callArgsValue = GetConvertedArgs(args);
//
// Build a new expression like:
// if (TryDeleteMember(payload)) { } else { fallbackResult }
//
var callDynamic = new DynamicMetaObject(
Expression.Block(
new[] { callArgs },
Expression.Assign(callArgs, Expression.NewArrayInit(typeof(object), callArgsValue)),
Expression.Condition(
Expression.Call(
GetLimitedSelf(),
typeof(MSDynamicObject).GetMethod(methodName),
BuildCallArgs(
binder,
args,
callArgs,
null
)
),
Expression.Block(
ReferenceArgAssign(callArgs, args),
Expression.Empty()
),
fallbackResult.Expression,
typeof(void)
)
),
GetRestrictions().Merge(fallbackResult.Restrictions)
);
//
// Now, call fallback again using our new MO as the error
// When we do this, one of two things can happen:
// 1. Binding will succeed, and it will ignore our call to
// the dynamic method, OR
// 2. Binding will fail, and it will use the MO we created
// above.
//
return fallback(callDynamic);
}
/// <summary>
/// Checks if the derived type has overridden the specified method. If there is no
/// implementation for the method provided then Dynamic falls back to the base class
/// behavior which lets the call site determine how the binder is performed.
/// </summary>
private bool IsOverridden(string method)
{
var methods = Value.GetType().GetMember(method, MemberTypes.Method, BindingFlags.Public | BindingFlags.Instance);
foreach (MethodInfo mi in methods)
{
if (mi.DeclaringType != typeof(MSDynamicObject) && mi.GetBaseDefinition().DeclaringType == typeof(MSDynamicObject))
{
return true;
}
}
return false;
}
/// <summary>
/// Returns a Restrictions object which includes our current restrictions merged
/// with a restriction limiting our type
/// </summary>
private BindingRestrictions GetRestrictions()
{
Debug.Assert(Restrictions == BindingRestrictions.Empty, "We don't merge, restrictions are always empty");
return /*BindingRestrictions.*/GetTypeRestriction(this);
}
/// <summary>
/// Returns our Expression converted to DynamicObject
/// </summary>
private Expression GetLimitedSelf()
{
// Convert to DynamicObject rather than LimitType, because
// the limit type might be non-public.
if (TypeUtils.AreEquivalent(Expression.Type, typeof(MSDynamicObject)))
{
return Expression;
}
return Expression.Convert(Expression, typeof(MSDynamicObject));
}
private new MSDynamicObject Value
{
get
{
return (MSDynamicObject)base.Value;
}
}
// It is okay to throw NotSupported from this binder. This object
// is only used by DynamicObject.GetMember--it is not expected to
// (and cannot) implement binding semantics. It is just so the DO
// can use the Name and IgnoreCase properties.
private sealed class GetBinderAdapter : GetMemberBinder
{
internal GetBinderAdapter(InvokeMemberBinder binder)
: base(binder.Name, binder.IgnoreCase)
{
}
public override DynamicMetaObject FallbackGetMember(DynamicMetaObject target, DynamicMetaObject errorSuggestion)
{
throw new NotSupportedException();
}
}
}
#endregion
#region IDynamicMetaObjectProvider Members
/// <summary>
/// The provided MetaObject will dispatch to the Dynamic virtual methods.
/// The object can be encapsulated inside of another MetaObject to
/// provide custom behavior for individual actions.
/// </summary>
public virtual DynamicMetaObject GetMetaObject(Expression parameter)
{
return new MetaDynamic(parameter, this);
}
#endregion
#region Imported util methods
/// <summary>
/// Returns the list of expressions represented by the <see cref="DynamicMetaObject"/> instances.
/// </summary>
/// <param name="objects">An array of <see cref="DynamicMetaObject"/> instances to extract expressions from.</param>
/// <returns>The array of expressions.</returns>
internal static Expression[] GetExpressions(DynamicMetaObject[] objects)
{
ContractUtils.RequiresNotNull(objects, "objects");
Expression[] res = new Expression[objects.Length];
for (int i = 0; i < objects.Length; i++)
{
DynamicMetaObject mo = objects[i];
ContractUtils.RequiresNotNull(mo, "objects");
Expression expr = mo.Expression;
ContractUtils.RequiresNotNull(expr, "objects");
res[i] = expr;
}
return res;
}
/// <summary>
/// The method takes a DynamicMetaObject, and returns an instance restriction for testing null if the object
/// holds a null value, otherwise returns a type restriction.
/// </summary>
internal static BindingRestrictions GetTypeRestriction(DynamicMetaObject obj)
{
if (obj.Value == null && obj.HasValue)
{
return BindingRestrictions.GetInstanceRestriction(obj.Expression, null);
}
else
{
return BindingRestrictions.GetTypeRestriction(obj.Expression, obj.LimitType);
}
}
#endregion
}
internal static class ContractUtils
{
internal static void Requires(bool precondition)
{
if (!precondition)
{
throw new ArgumentException("Strings.MethodPreconditionViolated");
}
}
internal static void RequiresNotNull(object value, string paramName)
{
Debug.Assert(!string.IsNullOrEmpty(paramName));
if (value == null)
{
throw new ArgumentNullException(paramName);
}
}
}
internal static class TypeUtils
{
internal static bool AreEquivalent(Type t1, Type t2)
{
#if CLR2 || SILVERLIGHT
return t1 == t2;
#else
return t1 == t2 || t1.IsEquivalentTo(t2);
#endif
}
}
}
#endif