/
BinaryExpression.cs
2866 lines (2656 loc) · 174 KB
/
BinaryExpression.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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Dynamic.Utils;
using System.Reflection;
using System.Runtime.CompilerServices;
using static System.Linq.Expressions.CachedReflectionInfo;
namespace System.Linq.Expressions
{
/// <summary>
/// Represents an expression that has a binary operator.
/// </summary>
[DebuggerTypeProxy(typeof(BinaryExpressionProxy))]
public class BinaryExpression : Expression
{
internal BinaryExpression(Expression left, Expression right)
{
Left = left;
Right = right;
}
/// <summary>
/// Gets a value that indicates whether the expression tree node can be reduced.
/// </summary>
public override bool CanReduce
{
get
{
// Only OpAssignments are reducible.
return IsOpAssignment(NodeType);
}
}
private static bool IsOpAssignment(ExpressionType op)
{
switch (op)
{
case ExpressionType.AddAssign:
case ExpressionType.SubtractAssign:
case ExpressionType.MultiplyAssign:
case ExpressionType.AddAssignChecked:
case ExpressionType.SubtractAssignChecked:
case ExpressionType.MultiplyAssignChecked:
case ExpressionType.DivideAssign:
case ExpressionType.ModuloAssign:
case ExpressionType.PowerAssign:
case ExpressionType.AndAssign:
case ExpressionType.OrAssign:
case ExpressionType.RightShiftAssign:
case ExpressionType.LeftShiftAssign:
case ExpressionType.ExclusiveOrAssign:
return true;
}
return false;
}
/// <summary>
/// Gets the right operand of the binary operation.
/// </summary>
public Expression Right { get; }
/// <summary>
/// Gets the left operand of the binary operation.
/// </summary>
public Expression Left { get; }
/// <summary>
/// Gets the implementing method for the binary operation.
/// </summary>
public MethodInfo? Method => GetMethod();
internal virtual MethodInfo? GetMethod() => null;
// Note: takes children in evaluation order, which is also the order
// that ExpressionVisitor visits them. Having them this way reduces the
// chances people will make a mistake and use an inconsistent order in
// derived visitors.
/// <summary>
/// Creates a new expression that is like this one, but using the
/// supplied children. If all of the children are the same, it will
/// return this expression.
/// </summary>
/// <param name="left">The <see cref="Left"/> property of the result.</param>
/// <param name="conversion">The <see cref="Conversion"/> property of the result.</param>
/// <param name="right">The <see cref="Right"/> property of the result.</param>
/// <returns>This expression if no children changed, or an expression with the updated children.</returns>
public BinaryExpression Update(Expression left, LambdaExpression? conversion, Expression right)
{
if (left == Left && right == Right && conversion == Conversion)
{
return this;
}
if (IsReferenceComparison)
{
if (NodeType == ExpressionType.Equal)
{
return Expression.ReferenceEqual(left, right);
}
else
{
return Expression.ReferenceNotEqual(left, right);
}
}
return Expression.MakeBinary(NodeType, left, right, IsLiftedToNull, Method, conversion);
}
/// <summary>
/// Reduces the binary expression node to a simpler expression.
/// If CanReduce returns true, this should return a valid expression.
/// This method is allowed to return another node which itself
/// must be reduced.
/// </summary>
/// <returns>The reduced expression.</returns>
public override Expression Reduce()
{
// Only reduce OpAssignment expressions.
if (IsOpAssignment(NodeType))
{
return Left.NodeType switch
{
ExpressionType.MemberAccess => ReduceMember(),
ExpressionType.Index => ReduceIndex(),
_ => ReduceVariable(),
};
}
return this;
}
// Return the corresponding Op of an assignment op.
private static ExpressionType GetBinaryOpFromAssignmentOp(ExpressionType op)
{
Debug.Assert(IsOpAssignment(op));
return op switch
{
ExpressionType.AddAssign => ExpressionType.Add,
ExpressionType.AddAssignChecked => ExpressionType.AddChecked,
ExpressionType.SubtractAssign => ExpressionType.Subtract,
ExpressionType.SubtractAssignChecked => ExpressionType.SubtractChecked,
ExpressionType.MultiplyAssign => ExpressionType.Multiply,
ExpressionType.MultiplyAssignChecked => ExpressionType.MultiplyChecked,
ExpressionType.DivideAssign => ExpressionType.Divide,
ExpressionType.ModuloAssign => ExpressionType.Modulo,
ExpressionType.PowerAssign => ExpressionType.Power,
ExpressionType.AndAssign => ExpressionType.And,
ExpressionType.OrAssign => ExpressionType.Or,
ExpressionType.RightShiftAssign => ExpressionType.RightShift,
ExpressionType.LeftShiftAssign => ExpressionType.LeftShift,
ExpressionType.ExclusiveOrAssign => ExpressionType.ExclusiveOr,
_ => throw ContractUtils.Unreachable,
};
}
private Expression ReduceVariable()
{
// v (op)= r
// ... is reduced into ...
// v = v (op) r
ExpressionType op = GetBinaryOpFromAssignmentOp(NodeType);
Expression r = Expression.MakeBinary(op, Left, Right, false, Method);
LambdaExpression? conversion = GetConversion();
if (conversion != null)
{
r = Expression.Invoke(conversion, r);
}
return Expression.Assign(Left, r);
}
private Expression ReduceMember()
{
MemberExpression member = (MemberExpression)Left;
if (member.Expression == null)
{
// static member, reduce the same as variable
return ReduceVariable();
}
else
{
// left.b (op)= r
// ... is reduced into ...
// temp1 = left
// temp2 = temp1.b (op) r
// temp1.b = temp2
// temp2
ParameterExpression temp1 = Variable(member.Expression.Type, "temp1");
// 1. temp1 = left
Expression e1 = Expression.Assign(temp1, member.Expression);
// 2. temp2 = temp1.b (op) r
ExpressionType op = GetBinaryOpFromAssignmentOp(NodeType);
Expression e2 = Expression.MakeBinary(op, Expression.MakeMemberAccess(temp1, member.Member), Right, false, Method);
LambdaExpression? conversion = GetConversion();
if (conversion != null)
{
e2 = Expression.Invoke(conversion, e2);
}
ParameterExpression temp2 = Variable(e2.Type, "temp2");
e2 = Expression.Assign(temp2, e2);
// 3. temp1.b = temp2
Expression e3 = Expression.Assign(Expression.MakeMemberAccess(temp1, member.Member), temp2);
// 3. temp2
Expression e4 = temp2;
return Expression.Block(
new TrueReadOnlyCollection<ParameterExpression>(temp1, temp2),
new TrueReadOnlyCollection<Expression>(e1, e2, e3, e4)
);
}
}
private Expression ReduceIndex()
{
// left[a0, a1, ... aN] (op)= r
//
// ... is reduced into ...
//
// tempObj = left
// tempArg0 = a0
// ...
// tempArgN = aN
// tempValue = tempObj[tempArg0, ... tempArgN] (op) r
// tempObj[tempArg0, ... tempArgN] = tempValue
var index = (IndexExpression)Left;
var vars = new ArrayBuilder<ParameterExpression>(index.ArgumentCount + 2);
var exprs = new ArrayBuilder<Expression>(index.ArgumentCount + 3);
ParameterExpression tempObj = Expression.Variable(index.Object!.Type, "tempObj");
vars.UncheckedAdd(tempObj);
exprs.UncheckedAdd(Expression.Assign(tempObj, index.Object));
int n = index.ArgumentCount;
var tempArgs = new ArrayBuilder<Expression>(n);
for (var i = 0; i < n; i++)
{
Expression arg = index.GetArgument(i);
ParameterExpression tempArg = Expression.Variable(arg.Type, "tempArg" + i);
vars.UncheckedAdd(tempArg);
tempArgs.UncheckedAdd(tempArg);
exprs.UncheckedAdd(Expression.Assign(tempArg, arg));
}
IndexExpression tempIndex = Expression.MakeIndex(tempObj, index.Indexer, tempArgs.ToReadOnly());
// tempValue = tempObj[tempArg0, ... tempArgN] (op) r
ExpressionType binaryOp = GetBinaryOpFromAssignmentOp(NodeType);
Expression op = Expression.MakeBinary(binaryOp, tempIndex, Right, false, Method);
LambdaExpression? conversion = GetConversion();
if (conversion != null)
{
op = Expression.Invoke(conversion, op);
}
ParameterExpression tempValue = Expression.Variable(op.Type, "tempValue");
vars.UncheckedAdd(tempValue);
exprs.UncheckedAdd(Expression.Assign(tempValue, op));
// tempObj[tempArg0, ... tempArgN] = tempValue
exprs.UncheckedAdd(Expression.Assign(tempIndex, tempValue));
return Expression.Block(vars.ToReadOnly(), exprs.ToReadOnly());
}
/// <summary>
/// Gets the type conversion function that is used by a coalescing or compound assignment operation.
/// </summary>
public LambdaExpression? Conversion => GetConversion();
internal virtual LambdaExpression? GetConversion() => null;
/// <summary>
/// Gets a value that indicates whether the expression tree node represents a lifted call to an operator.
/// </summary>
public bool IsLifted
{
get
{
if (NodeType == ExpressionType.Coalesce || NodeType == ExpressionType.Assign)
{
return false;
}
if (Left.Type.IsNullableType())
{
MethodInfo? method = GetMethod();
return method == null ||
!TypeUtils.AreEquivalent(method.GetParametersCached()[0].ParameterType.GetNonRefType(), Left.Type);
}
return false;
}
}
/// <summary>
/// Gets a value that indicates whether the expression tree node represents a lifted call to an operator whose return type is lifted to a nullable type.
/// </summary>
public bool IsLiftedToNull => IsLifted && Type.IsNullableType();
/// <summary>
/// Dispatches to the specific visit method for this node type.
/// </summary>
protected internal override Expression Accept(ExpressionVisitor visitor)
{
return visitor.VisitBinary(this);
}
internal static BinaryExpression Create(ExpressionType nodeType, Expression left, Expression right, Type type, MethodInfo? method, LambdaExpression? conversion)
{
Debug.Assert(nodeType != ExpressionType.Assign);
if (conversion != null)
{
Debug.Assert(method == null && TypeUtils.AreEquivalent(type, right.Type) && nodeType == ExpressionType.Coalesce);
return new CoalesceConversionBinaryExpression(left, right, conversion);
}
if (method != null)
{
return new MethodBinaryExpression(nodeType, left, right, type, method);
}
if (type == typeof(bool))
{
return new LogicalBinaryExpression(nodeType, left, right);
}
return new SimpleBinaryExpression(nodeType, left, right, type);
}
internal bool IsLiftedLogical
{
get
{
Type left = Left.Type;
Type right = Right.Type;
MethodInfo? method = GetMethod();
ExpressionType kind = NodeType;
return
(kind == ExpressionType.AndAlso || kind == ExpressionType.OrElse) &&
TypeUtils.AreEquivalent(right, left) &&
left.IsNullableType() &&
method != null &&
TypeUtils.AreEquivalent(method.ReturnType, left.GetNonNullableType());
}
}
internal bool IsReferenceComparison
{
get
{
Type left = Left.Type;
Type right = Right.Type;
MethodInfo? method = GetMethod();
ExpressionType kind = NodeType;
return (kind == ExpressionType.Equal || kind == ExpressionType.NotEqual) &&
method == null && !left.IsValueType && !right.IsValueType;
}
}
//
// For a user-defined type T which has op_False defined and L, R are
// nullable, (L AndAlso R) is computed as:
//
// L.HasValue
// ? T.op_False(L.GetValueOrDefault())
// ? L
// : R.HasValue
// ? (T?)(T.op_BitwiseAnd(L.GetValueOrDefault(), R.GetValueOrDefault()))
// : null
// : null
//
// For a user-defined type T which has op_True defined and L, R are
// nullable, (L OrElse R) is computed as:
//
// L.HasValue
// ? T.op_True(L.GetValueOrDefault())
// ? L
// : R.HasValue
// ? (T?)(T.op_BitwiseOr(L.GetValueOrDefault(), R.GetValueOrDefault()))
// : null
// : null
//
//
// This is the same behavior as VB. If you think about it, it makes
// sense: it's combining the normal pattern for short-circuiting
// operators, with the normal pattern for lifted operations: if either
// of the operands is null, the result is also null.
//
internal Expression ReduceUserdefinedLifted()
{
Debug.Assert(IsLiftedLogical);
ParameterExpression left = Parameter(Left.Type, "left");
ParameterExpression right = Parameter(Right.Type, "right");
string opName = NodeType == ExpressionType.AndAlso ? "op_False" : "op_True";
MethodInfo? opTrueFalse = TypeUtils.GetBooleanOperator(Method!.DeclaringType!, opName);
Debug.Assert(opTrueFalse != null);
return Block(
new TrueReadOnlyCollection<ParameterExpression>(left),
new TrueReadOnlyCollection<Expression>(
Assign(left, Left),
Condition(
GetHasValueProperty(left),
Condition(
Call(opTrueFalse, CallGetValueOrDefault(left)),
left,
Block(
new TrueReadOnlyCollection<ParameterExpression>(right),
new TrueReadOnlyCollection<Expression>(
Assign(right, Right),
Condition(
GetHasValueProperty(right),
Convert(
Call(
Method,
CallGetValueOrDefault(left),
CallGetValueOrDefault(right)
),
Type
),
Constant(null, Type)
)
)
)
),
Constant(null, Type)
)
)
);
}
[DynamicDependency("GetValueOrDefault", typeof(Nullable<>))]
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "The method will be preserved by the DynamicDependency.")]
[UnconditionalSuppressMessage("DynamicCode", "IL3050",
Justification = "GetValueOrDefault is not generic and therefore MakeGenericMethod will not be called")]
private static MethodCallExpression CallGetValueOrDefault(ParameterExpression nullable)
{
return Call(nullable, "GetValueOrDefault", null);
}
[DynamicDependency("HasValue", typeof(Nullable<>))]
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2026:RequiresUnreferencedCode",
Justification = "The property will be preserved by the DynamicDependency.")]
private static MemberExpression GetHasValueProperty(ParameterExpression nullable)
{
return Property(nullable, "HasValue");
}
}
// Optimized representation of simple logical expressions:
// && || == != > < >= <=
internal sealed class LogicalBinaryExpression : BinaryExpression
{
internal LogicalBinaryExpression(ExpressionType nodeType, Expression left, Expression right)
: base(left, right)
{
NodeType = nodeType;
}
public sealed override Type Type => typeof(bool);
public sealed override ExpressionType NodeType { get; }
}
// Optimized assignment node, only holds onto children
internal class AssignBinaryExpression : BinaryExpression
{
internal AssignBinaryExpression(Expression left, Expression right)
: base(left, right)
{
}
public static AssignBinaryExpression Make(Expression left, Expression right, bool byRef)
{
if (byRef)
{
return new ByRefAssignBinaryExpression(left, right);
}
else
{
return new AssignBinaryExpression(left, right);
}
}
internal virtual bool IsByRef => false;
public sealed override Type Type => Left.Type;
public sealed override ExpressionType NodeType => ExpressionType.Assign;
}
internal sealed class ByRefAssignBinaryExpression : AssignBinaryExpression
{
internal ByRefAssignBinaryExpression(Expression left, Expression right)
: base(left, right)
{
}
internal override bool IsByRef => true;
}
// Coalesce with conversion
// This is not a frequently used node, but rather we want to save every
// other BinaryExpression from holding onto the null conversion lambda
internal sealed class CoalesceConversionBinaryExpression : BinaryExpression
{
private readonly LambdaExpression _conversion;
internal CoalesceConversionBinaryExpression(Expression left, Expression right, LambdaExpression conversion)
: base(left, right)
{
_conversion = conversion;
}
internal override LambdaExpression GetConversion() => _conversion;
public sealed override ExpressionType NodeType => ExpressionType.Coalesce;
public sealed override Type Type => Right.Type;
}
// OpAssign with conversion
// This is not a frequently used node, but rather we want to save every
// other BinaryExpression from holding onto the null conversion lambda
internal sealed class OpAssignMethodConversionBinaryExpression : MethodBinaryExpression
{
private readonly LambdaExpression _conversion;
internal OpAssignMethodConversionBinaryExpression(ExpressionType nodeType, Expression left, Expression right, Type type, MethodInfo method, LambdaExpression conversion)
: base(nodeType, left, right, type, method)
{
_conversion = conversion;
}
internal override LambdaExpression GetConversion() => _conversion;
}
// Class that handles most binary expressions
// If needed, it can be optimized even more (often Type == left.Type)
internal class SimpleBinaryExpression : BinaryExpression
{
internal SimpleBinaryExpression(ExpressionType nodeType, Expression left, Expression right, Type type)
: base(left, right)
{
NodeType = nodeType;
Type = type;
}
public sealed override ExpressionType NodeType { get; }
public sealed override Type Type { get; }
}
// Class that handles binary expressions with a method
// If needed, it can be optimized even more (often Type == method.ReturnType)
internal class MethodBinaryExpression : SimpleBinaryExpression
{
private readonly MethodInfo _method;
internal MethodBinaryExpression(ExpressionType nodeType, Expression left, Expression right, Type type, MethodInfo method)
: base(nodeType, left, right, type)
{
_method = method;
}
internal override MethodInfo GetMethod() => _method;
}
public partial class Expression
{
#region Assign
/// <summary>
/// Creates a <see cref="BinaryExpression"/> that represents an assignment operation.
/// </summary>
/// <param name="left">An <see cref="Expression"/> to set the <see cref="BinaryExpression.Left"/> property equal to.</param>
/// <param name="right">An <see cref="Expression"/> to set the <see cref="BinaryExpression.Right"/> property equal to.</param>
/// <returns>A <see cref="BinaryExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Assign"/>
/// and the <see cref="BinaryExpression.Left"/> and <see cref="BinaryExpression.Right"/> properties set to the specified values.
/// </returns>
public static BinaryExpression Assign(Expression left, Expression right)
{
RequiresCanWrite(left, nameof(left));
ExpressionUtils.RequiresCanRead(right, nameof(right));
TypeUtils.ValidateType(left.Type, nameof(left), allowByRef: true, allowPointer: true);
TypeUtils.ValidateType(right.Type, nameof(right), allowByRef: true, allowPointer: true);
if (!TypeUtils.AreReferenceAssignable(left.Type, right.Type))
{
throw Error.ExpressionTypeDoesNotMatchAssignment(right.Type, left.Type);
}
return new AssignBinaryExpression(left, right);
}
#endregion
private static BinaryExpression? GetUserDefinedBinaryOperator(ExpressionType binaryType, string name, Expression left, Expression right, bool liftToNull)
{
// try exact match first
MethodInfo? method = GetUserDefinedBinaryOperator(binaryType, left.Type, right.Type, name);
if (method != null)
{
return new MethodBinaryExpression(binaryType, left, right, method.ReturnType, method);
}
// try lifted call
if (left.Type.IsNullableType() && right.Type.IsNullableType())
{
Type nnLeftType = left.Type.GetNonNullableType();
Type nnRightType = right.Type.GetNonNullableType();
method = GetUserDefinedBinaryOperator(binaryType, nnLeftType, nnRightType, name);
if (method != null && method.ReturnType.IsValueType && !method.ReturnType.IsNullableType())
{
if (method.ReturnType != typeof(bool) || liftToNull)
{
return new MethodBinaryExpression(binaryType, left, right, method.ReturnType.LiftPrimitiveOrThrow(), method);
}
else
{
return new MethodBinaryExpression(binaryType, left, right, typeof(bool), method);
}
}
}
return null;
}
private static BinaryExpression GetMethodBasedBinaryOperator(ExpressionType binaryType, Expression left, Expression right, MethodInfo method, bool liftToNull)
{
System.Diagnostics.Debug.Assert(method != null);
ValidateOperator(method);
ParameterInfo[] pms = method.GetParametersCached();
if (pms.Length != 2)
throw Error.IncorrectNumberOfMethodCallArguments(method, nameof(method));
if (ParameterIsAssignable(pms[0], left.Type) && ParameterIsAssignable(pms[1], right.Type))
{
ValidateParamsWithOperandsOrThrow(pms[0].ParameterType, left.Type, binaryType, method.Name);
ValidateParamsWithOperandsOrThrow(pms[1].ParameterType, right.Type, binaryType, method.Name);
return new MethodBinaryExpression(binaryType, left, right, method.ReturnType, method);
}
// check for lifted call
if (left.Type.IsNullableType() && right.Type.IsNullableType() &&
ParameterIsAssignable(pms[0], left.Type.GetNonNullableType()) &&
ParameterIsAssignable(pms[1], right.Type.GetNonNullableType()) &&
method.ReturnType.IsValueType && !method.ReturnType.IsNullableType())
{
if (method.ReturnType != typeof(bool) || liftToNull)
{
return new MethodBinaryExpression(binaryType, left, right, method.ReturnType.LiftPrimitiveOrThrow(), method);
}
else
{
return new MethodBinaryExpression(binaryType, left, right, typeof(bool), method);
}
}
throw Error.OperandTypesDoNotMatchParameters(binaryType, method.Name);
}
private static BinaryExpression GetMethodBasedAssignOperator(ExpressionType binaryType, Expression left, Expression right, MethodInfo method, LambdaExpression? conversion, bool liftToNull)
{
BinaryExpression b = GetMethodBasedBinaryOperator(binaryType, left, right, method, liftToNull);
if (conversion == null)
{
// return type must be assignable back to the left type
if (!TypeUtils.AreReferenceAssignable(left.Type, b.Type))
{
throw Error.UserDefinedOpMustHaveValidReturnType(binaryType, b.Method!.Name);
}
}
else
{
// add the conversion to the result
ValidateOpAssignConversionLambda(conversion, b.Left, b.Method!, b.NodeType);
b = new OpAssignMethodConversionBinaryExpression(b.NodeType, b.Left, b.Right, b.Left.Type, b.Method!, conversion);
}
return b;
}
private static BinaryExpression GetUserDefinedBinaryOperatorOrThrow(ExpressionType binaryType, string name, Expression left, Expression right, bool liftToNull)
{
BinaryExpression? b = GetUserDefinedBinaryOperator(binaryType, name, left, right, liftToNull);
if (b != null)
{
ParameterInfo[] pis = b.Method!.GetParametersCached();
ValidateParamsWithOperandsOrThrow(pis[0].ParameterType, left.Type, binaryType, name);
ValidateParamsWithOperandsOrThrow(pis[1].ParameterType, right.Type, binaryType, name);
return b;
}
throw Error.BinaryOperatorNotDefined(binaryType, left.Type, right.Type);
}
private static BinaryExpression GetUserDefinedAssignOperatorOrThrow(ExpressionType binaryType, string name, Expression left, Expression right, LambdaExpression? conversion, bool liftToNull)
{
BinaryExpression b = GetUserDefinedBinaryOperatorOrThrow(binaryType, name, left, right, liftToNull);
if (conversion == null)
{
// return type must be assignable back to the left type
if (!TypeUtils.AreReferenceAssignable(left.Type, b.Type))
{
throw Error.UserDefinedOpMustHaveValidReturnType(binaryType, b.Method!.Name);
}
}
else
{
// add the conversion to the result
ValidateOpAssignConversionLambda(conversion, b.Left, b.Method!, b.NodeType);
b = new OpAssignMethodConversionBinaryExpression(b.NodeType, b.Left, b.Right, b.Left.Type, b.Method!, conversion);
}
return b;
}
[UnconditionalSuppressMessage("ReflectionAnalysis", "IL2072:UnrecognizedReflectionPattern",
Justification = "The trimmer doesn't remove operators when System.Linq.Expressions is used. See https://github.com/mono/linker/pull/2125.")]
private static MethodInfo? GetUserDefinedBinaryOperator(ExpressionType binaryType, Type leftType, Type rightType, string name)
{
// This algorithm is wrong, we should be checking for uniqueness and erroring if
// it is defined on both types.
Type[] types = new Type[] { leftType, rightType };
Type nnLeftType = leftType.GetNonNullableType();
Type nnRightType = rightType.GetNonNullableType();
MethodInfo? method = nnLeftType.GetAnyStaticMethodValidated(name, types);
if (method == null && !TypeUtils.AreEquivalent(leftType, rightType))
{
method = nnRightType.GetAnyStaticMethodValidated(name, types);
}
if (IsLiftingConditionalLogicalOperator(leftType, rightType, method, binaryType))
{
method = GetUserDefinedBinaryOperator(binaryType, nnLeftType, nnRightType, name);
}
return method;
}
private static bool IsLiftingConditionalLogicalOperator(Type left, Type right, MethodInfo? method, ExpressionType binaryType)
{
return right.IsNullableType() &&
left.IsNullableType() &&
method == null &&
(binaryType == ExpressionType.AndAlso || binaryType == ExpressionType.OrElse);
}
internal static bool ParameterIsAssignable(ParameterInfo pi, Type argType)
{
Type pType = pi.ParameterType;
if (pType.IsByRef)
pType = pType.GetElementType()!;
return TypeUtils.AreReferenceAssignable(pType, argType);
}
private static void ValidateParamsWithOperandsOrThrow(Type paramType, Type operandType, ExpressionType exprType, string name)
{
if (paramType.IsNullableType() && !operandType.IsNullableType())
{
throw Error.OperandTypesDoNotMatchParameters(exprType, name);
}
}
private static void ValidateOperator(MethodInfo method)
{
Debug.Assert(method != null);
ValidateMethodInfo(method, nameof(method));
if (!method.IsStatic)
throw Error.UserDefinedOperatorMustBeStatic(method, nameof(method));
if (method.ReturnType == typeof(void))
throw Error.UserDefinedOperatorMustNotBeVoid(method, nameof(method));
}
private static void ValidateMethodInfo(MethodInfo method, string paramName)
{
if (method.ContainsGenericParameters)
throw method.IsGenericMethodDefinition ? Error.MethodIsGeneric(method, paramName) : Error.MethodContainsGenericParameters(method, paramName);
}
private static bool IsNullComparison(Expression left, Expression right)
{
// If we have x==null, x!=null, null==x or null!=x where x is
// nullable but not null, then this is treated as a call to x.HasValue
// and is legal even if there is no equality operator defined on the
// type of x.
return IsNullConstant(left)
? !IsNullConstant(right) && right.Type.IsNullableType()
: IsNullConstant(right) && left.Type.IsNullableType();
}
// Note: this has different meaning than ConstantCheck.IsNull
// That function attempts to determine if the result of a tree will be
// null at runtime. This function is used at tree construction time and
// only looks for a ConstantExpression with a null Value. It can't
// become "smarter" or that would break tree construction.
private static bool IsNullConstant(Expression e)
{
var c = e as ConstantExpression;
return c != null && c.Value == null;
}
private static void ValidateUserDefinedConditionalLogicOperator(ExpressionType nodeType, Type left, Type right, MethodInfo method)
{
ValidateOperator(method);
ParameterInfo[] pms = method.GetParametersCached();
if (pms.Length != 2)
throw Error.IncorrectNumberOfMethodCallArguments(method, nameof(method));
if (!ParameterIsAssignable(pms[0], left))
{
if (!(left.IsNullableType() && ParameterIsAssignable(pms[0], left.GetNonNullableType())))
throw Error.OperandTypesDoNotMatchParameters(nodeType, method.Name);
}
if (!ParameterIsAssignable(pms[1], right))
{
if (!(right.IsNullableType() && ParameterIsAssignable(pms[1], right.GetNonNullableType())))
throw Error.OperandTypesDoNotMatchParameters(nodeType, method.Name);
}
if (pms[0].ParameterType != pms[1].ParameterType)
{
throw Error.UserDefinedOpMustHaveConsistentTypes(nodeType, method.Name);
}
if (method.ReturnType != pms[0].ParameterType)
{
throw Error.UserDefinedOpMustHaveConsistentTypes(nodeType, method.Name);
}
if (IsValidLiftedConditionalLogicalOperator(left, right, pms))
{
left = left.GetNonNullableType();
}
Type? declaringType = method.DeclaringType;
if (declaringType == null)
{
throw Error.LogicalOperatorMustHaveBooleanOperators(nodeType, method.Name);
}
MethodInfo? opTrue = TypeUtils.GetBooleanOperator(declaringType, "op_True");
MethodInfo? opFalse = TypeUtils.GetBooleanOperator(declaringType, "op_False");
if (opTrue == null || opTrue.ReturnType != typeof(bool) ||
opFalse == null || opFalse.ReturnType != typeof(bool))
{
throw Error.LogicalOperatorMustHaveBooleanOperators(nodeType, method.Name);
}
VerifyOpTrueFalse(nodeType, left, opFalse, nameof(method));
VerifyOpTrueFalse(nodeType, left, opTrue, nameof(method));
}
private static void VerifyOpTrueFalse(ExpressionType nodeType, Type left, MethodInfo opTrue, string paramName)
{
ParameterInfo[] pmsOpTrue = opTrue.GetParametersCached();
if (pmsOpTrue.Length != 1)
throw Error.IncorrectNumberOfMethodCallArguments(opTrue, paramName);
if (!ParameterIsAssignable(pmsOpTrue[0], left))
{
if (!(left.IsNullableType() && ParameterIsAssignable(pmsOpTrue[0], left.GetNonNullableType())))
throw Error.OperandTypesDoNotMatchParameters(nodeType, opTrue.Name);
}
}
private static bool IsValidLiftedConditionalLogicalOperator(Type left, Type right, ParameterInfo[] pms)
{
return TypeUtils.AreEquivalent(left, right) &&
right.IsNullableType() &&
TypeUtils.AreEquivalent(pms[1].ParameterType, right.GetNonNullableType());
}
/// <summary>
/// Creates a <see cref="BinaryExpression" />, given the left and right operands, by calling an appropriate factory method.
/// </summary>
/// <param name="binaryType">The ExpressionType that specifies the type of binary operation.</param>
/// <param name="left">An Expression that represents the left operand.</param>
/// <param name="right">An Expression that represents the right operand.</param>
/// <returns>The BinaryExpression that results from calling the appropriate factory method.</returns>
public static BinaryExpression MakeBinary(ExpressionType binaryType, Expression left, Expression right)
{
return MakeBinary(binaryType, left, right, liftToNull: false, method: null, conversion: null);
}
/// <summary>
/// Creates a <see cref="BinaryExpression" />, given the left and right operands, by calling an appropriate factory method.
/// </summary>
/// <param name="binaryType">The ExpressionType that specifies the type of binary operation.</param>
/// <param name="left">An Expression that represents the left operand.</param>
/// <param name="right">An Expression that represents the right operand.</param>
/// <param name="liftToNull">true to set IsLiftedToNull to true; false to set IsLiftedToNull to false.</param>
/// <param name="method">A MethodInfo that specifies the implementing method.</param>
/// <returns>The BinaryExpression that results from calling the appropriate factory method.</returns>
public static BinaryExpression MakeBinary(ExpressionType binaryType, Expression left, Expression right, bool liftToNull, MethodInfo? method)
{
return MakeBinary(binaryType, left, right, liftToNull, method, conversion: null);
}
///
/// <summary>
/// Creates a <see cref="BinaryExpression" />, given the left and right operands, by calling an appropriate factory method.
/// </summary>
/// <param name="binaryType">The ExpressionType that specifies the type of binary operation.</param>
/// <param name="left">An Expression that represents the left operand.</param>
/// <param name="right">An Expression that represents the right operand.</param>
/// <param name="liftToNull">true to set IsLiftedToNull to true; false to set IsLiftedToNull to false.</param>
/// <param name="method">A MethodInfo that specifies the implementing method.</param>
/// <param name="conversion">A LambdaExpression that represents a type conversion function. This parameter is used if binaryType is Coalesce or compound assignment.</param>
/// <returns>The BinaryExpression that results from calling the appropriate factory method.</returns>
public static BinaryExpression MakeBinary(ExpressionType binaryType, Expression left, Expression right, bool liftToNull, MethodInfo? method, LambdaExpression? conversion) =>
binaryType switch
{
ExpressionType.Add => Add(left, right, method),
ExpressionType.AddChecked => AddChecked(left, right, method),
ExpressionType.Subtract => Subtract(left, right, method),
ExpressionType.SubtractChecked => SubtractChecked(left, right, method),
ExpressionType.Multiply => Multiply(left, right, method),
ExpressionType.MultiplyChecked => MultiplyChecked(left, right, method),
ExpressionType.Divide => Divide(left, right, method),
ExpressionType.Modulo => Modulo(left, right, method),
ExpressionType.Power => Power(left, right, method),
ExpressionType.And => And(left, right, method),
ExpressionType.AndAlso => AndAlso(left, right, method),
ExpressionType.Or => Or(left, right, method),
ExpressionType.OrElse => OrElse(left, right, method),
ExpressionType.LessThan => LessThan(left, right, liftToNull, method),
ExpressionType.LessThanOrEqual => LessThanOrEqual(left, right, liftToNull, method),
ExpressionType.GreaterThan => GreaterThan(left, right, liftToNull, method),
ExpressionType.GreaterThanOrEqual => GreaterThanOrEqual(left, right, liftToNull, method),
ExpressionType.Equal => Equal(left, right, liftToNull, method),
ExpressionType.NotEqual => NotEqual(left, right, liftToNull, method),
ExpressionType.ExclusiveOr => ExclusiveOr(left, right, method),
ExpressionType.Coalesce => Coalesce(left, right, conversion),
ExpressionType.ArrayIndex => ArrayIndex(left, right),
ExpressionType.RightShift => RightShift(left, right, method),
ExpressionType.LeftShift => LeftShift(left, right, method),
ExpressionType.Assign => Assign(left, right),
ExpressionType.AddAssign => AddAssign(left, right, method, conversion),
ExpressionType.AndAssign => AndAssign(left, right, method, conversion),
ExpressionType.DivideAssign => DivideAssign(left, right, method, conversion),
ExpressionType.ExclusiveOrAssign => ExclusiveOrAssign(left, right, method, conversion),
ExpressionType.LeftShiftAssign => LeftShiftAssign(left, right, method, conversion),
ExpressionType.ModuloAssign => ModuloAssign(left, right, method, conversion),
ExpressionType.MultiplyAssign => MultiplyAssign(left, right, method, conversion),
ExpressionType.OrAssign => OrAssign(left, right, method, conversion),
ExpressionType.PowerAssign => PowerAssign(left, right, method, conversion),
ExpressionType.RightShiftAssign => RightShiftAssign(left, right, method, conversion),
ExpressionType.SubtractAssign => SubtractAssign(left, right, method, conversion),
ExpressionType.AddAssignChecked => AddAssignChecked(left, right, method, conversion),
ExpressionType.SubtractAssignChecked => SubtractAssignChecked(left, right, method, conversion),
ExpressionType.MultiplyAssignChecked => MultiplyAssignChecked(left, right, method, conversion),
_ => throw Error.UnhandledBinary(binaryType, nameof(binaryType)),
};
#region Equality Operators
/// <summary>
/// Creates a <see cref="BinaryExpression"/> that represents an equality comparison.
/// </summary>
/// <param name="left">An <see cref="Expression"/> to set the <see cref="BinaryExpression.Left"/> property equal to.</param>
/// <param name="right">An <see cref="Expression"/> to set the <see cref="BinaryExpression.Right"/> property equal to.</param>
/// <returns>A <see cref="BinaryExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Equal"/>
/// and the <see cref="BinaryExpression.Left"/> and <see cref="BinaryExpression.Right"/> properties set to the specified values.</returns>
public static BinaryExpression Equal(Expression left, Expression right)
{
return Equal(left, right, liftToNull: false, method: null);
}
/// <summary>
/// Creates a <see cref="BinaryExpression"/> that represents an equality comparison.
/// </summary>
/// <param name="left">An <see cref="Expression"/> to set the <see cref="BinaryExpression.Left"/> property equal to.</param>
/// <param name="right">An <see cref="Expression"/> to set the <see cref="BinaryExpression.Right"/> property equal to.</param>
/// <param name="method">A <see cref="MethodInfo"/> to set the <see cref="BinaryExpression.Method"/> property equal to.</param>
/// <param name="liftToNull">true to set IsLiftedToNull to true; false to set IsLiftedToNull to false.</param>
/// <returns>A <see cref="BinaryExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Equal"/>
/// and the <see cref="BinaryExpression.Left"/>, <see cref="BinaryExpression.Right"/>, <see cref="BinaryExpression.IsLiftedToNull"/>, and <see cref="BinaryExpression.Method"/> properties set to the specified values.
/// </returns>
public static BinaryExpression Equal(Expression left, Expression right, bool liftToNull, MethodInfo? method)
{
ExpressionUtils.RequiresCanRead(left, nameof(left));
ExpressionUtils.RequiresCanRead(right, nameof(right));
if (method == null)
{
return GetEqualityComparisonOperator(ExpressionType.Equal, "op_Equality", left, right, liftToNull);
}
return GetMethodBasedBinaryOperator(ExpressionType.Equal, left, right, method, liftToNull);
}
/// <summary>
/// Creates a <see cref="BinaryExpression"/> that represents a reference equality comparison.
/// </summary>
/// <param name="left">An <see cref="Expression"/> to set the <see cref="BinaryExpression.Left"/> property equal to.</param>
/// <param name="right">An <see cref="Expression"/> to set the <see cref="BinaryExpression.Right"/> property equal to.</param>
/// <returns>A <see cref="BinaryExpression"/> that has the <see cref="NodeType"/> property equal to <see cref="ExpressionType.Equal"/>
/// and the <see cref="BinaryExpression.Left"/> and <see cref="BinaryExpression.Right"/> properties set to the specified values.
/// </returns>
public static BinaryExpression ReferenceEqual(Expression left, Expression right)
{
ExpressionUtils.RequiresCanRead(left, nameof(left));
ExpressionUtils.RequiresCanRead(right, nameof(right));
if (TypeUtils.HasReferenceEquality(left.Type, right.Type))
{
return new LogicalBinaryExpression(ExpressionType.Equal, left, right);
}
throw Error.ReferenceEqualityNotDefined(left.Type, right.Type);
}
/// <summary>
/// Creates a <see cref="BinaryExpression"/> that represents an inequality comparison.