5 // Jb Evain (jbevain@novell.com)
6 // Miguel de Icaza (miguel@novell.com)
8 // (C) 2008 Novell, Inc. (http://www.novell.com)
10 // Permission is hereby granted, free of charge, to any person obtaining
11 // a copy of this software and associated documentation files (the
12 // "Software"), to deal in the Software without restriction, including
13 // without limitation the rights to use, copy, modify, merge, publish,
14 // distribute, sublicense, and/or sell copies of the Software, and to
15 // permit persons to whom the Software is furnished to do so, subject to
16 // the following conditions:
18 // The above copyright notice and this permission notice shall be
19 // included in all copies or substantial portions of the Software.
21 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
22 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
23 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
24 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
25 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
26 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
27 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
31 using System.Collections;
32 using System.Collections.Generic;
33 using System.Collections.ObjectModel;
35 using System.Reflection;
36 using System.Reflection.Emit;
38 namespace System.Linq.Expressions {
40 public abstract class Expression {
42 ExpressionType node_type;
45 const BindingFlags PublicInstance = BindingFlags.Public | BindingFlags.Instance;
46 const BindingFlags NonPublicInstance = BindingFlags.NonPublic | BindingFlags.Instance;
47 const BindingFlags PublicStatic = BindingFlags.Public | BindingFlags.Static;
48 const BindingFlags AllInstance = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
49 const BindingFlags AllStatic = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
50 const BindingFlags All = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;
52 public ExpressionType NodeType {
53 get { return node_type; }
60 protected Expression (ExpressionType node_type, Type type)
62 this.node_type = node_type;
66 public override string ToString ()
68 return ExpressionPrinter.ToString (this);
71 #region Binary Expressions
73 static MethodInfo GetUnaryOperator (string oper_name, Type declaring, Type param)
75 return GetUnaryOperator (oper_name, declaring, param, null);
78 static MethodInfo GetUnaryOperator (string oper_name, Type declaring, Type param, Type ret)
80 var methods = declaring.GetMethods (PublicStatic);
82 foreach (var method in methods) {
83 if (method.Name != oper_name)
86 var parameters = method.GetParameters ();
87 if (parameters.Length != 1)
90 if (!IsAssignableToParameterType (param, parameters [0]))
93 if (ret != null && method.ReturnType != GetNotNullableOf (ret))
102 static bool IsAssignableToParameterType (Type type, ParameterInfo param)
104 var ptype = param.ParameterType;
106 ptype = ptype.GetElementType ();
108 return GetNotNullableOf (type).IsAssignableTo (ptype);
111 static MethodInfo CheckUnaryMethod (MethodInfo method, Type param)
113 if (method.ReturnType == typeof (void))
114 throw new ArgumentException ("Specified method must return a value", "method");
116 if (!method.IsStatic)
117 throw new ArgumentException ("Method must be static", "method");
119 var parameters = method.GetParameters ();
121 if (parameters.Length != 1)
122 throw new ArgumentException ("Must have only one parameters", "method");
124 if (!IsAssignableToParameterType (param, parameters [0]))
125 throw new InvalidOperationException ("left-side argument type does not match expression type");
130 static MethodInfo UnaryCoreCheck (string oper_name, Expression expression, MethodInfo method, Func<Type, bool> validator)
132 if (expression == null)
133 throw new ArgumentNullException ("expression");
136 return CheckUnaryMethod (method, expression.Type);
138 var type = GetNotNullableOf (expression.Type);
140 if (validator (type))
143 if (oper_name != null) {
144 method = GetUnaryOperator (oper_name, type, expression.Type);
149 throw new InvalidOperationException (
150 string.Format ("Operation {0} not defined for {1}", oper_name != null ? oper_name.Substring (3) : "is", expression.Type));
153 static MethodInfo GetBinaryOperator (string oper_name, Type on_type, Expression left, Expression right)
155 MethodInfo [] methods = on_type.GetMethods (PublicStatic);
157 foreach (var method in methods) {
158 if (method.Name != oper_name)
161 var parameters = method.GetParameters ();
162 if (parameters.Length != 2)
165 if (!IsAssignableToParameterType (left.Type, parameters [0]))
168 if (!IsAssignableToParameterType (right.Type, parameters [1]))
171 // Method has papers in order.
179 // Performs basic checks on the incoming expressions for binary expressions
180 // and any provided MethodInfo.
182 static MethodInfo BinaryCoreCheck (string oper_name, Expression left, Expression right, MethodInfo method)
185 throw new ArgumentNullException ("left");
187 throw new ArgumentNullException ("right");
190 if (method.ReturnType == typeof (void))
191 throw new ArgumentException ("Specified method must return a value", "method");
193 if (!method.IsStatic)
194 throw new ArgumentException ("Method must be static", "method");
196 var parameters = method.GetParameters ();
198 if (parameters.Length != 2)
199 throw new ArgumentException ("Must have only two parameters", "method");
201 if (!IsAssignableToParameterType (left.Type, parameters [0]))
202 throw new InvalidOperationException ("left-side argument type does not match left expression type");
204 if (!IsAssignableToParameterType (right.Type, parameters [1]))
205 throw new InvalidOperationException ("right-side argument type does not match right expression type");
209 Type ltype = left.Type;
210 Type rtype = right.Type;
211 Type ultype = GetNotNullableOf (ltype);
212 Type urtype = GetNotNullableOf (rtype);
214 if (oper_name == "op_BitwiseOr" || oper_name == "op_BitwiseAnd") {
215 if (ultype == typeof (bool)) {
216 if (ultype == urtype && ltype == rtype)
221 // Use IsNumber to avoid expensive reflection.
222 if (IsNumber (ultype)){
223 if (ultype == urtype && ltype == rtype)
226 if (oper_name != null){
227 method = GetBinaryOperator (oper_name, urtype, left, right);
233 if (oper_name != null){
234 method = GetBinaryOperator (oper_name, ultype, left, right);
240 // == and != allow reference types without operators defined.
242 if (!ltype.IsValueType && !rtype.IsValueType &&
243 (oper_name == "op_Equality" || oper_name == "op_Inequality"))
246 throw new InvalidOperationException (
247 String.Format ("Operation {0} not defined for {1} and {2}", oper_name != null ? oper_name.Substring (3) : "is", ltype, rtype));
252 // This is like BinaryCoreCheck, but if no method is used adds the restriction that
253 // only ints and bools are allowed
255 static MethodInfo BinaryBitwiseCoreCheck (string oper_name, Expression left, Expression right, MethodInfo method)
258 throw new ArgumentNullException ("left");
260 throw new ArgumentNullException ("right");
262 if (method == null) {
263 // avoid reflection shortcut and catches Ints/bools before we check Numbers in general
264 if (left.Type == right.Type && IsIntOrBool (left.Type))
268 method = BinaryCoreCheck (oper_name, left, right, method);
269 if (method == null) {
270 // The check in BinaryCoreCheck allows a bit more than we do
271 // (floats and doubles). Catch this here
272 if (left.Type == typeof (double) || left.Type == typeof (float))
273 throw new InvalidOperationException ("Types not supported");
279 static Type GetResultType (Expression expression, MethodInfo method)
281 return method == null ? expression.Type : method.ReturnType;
284 static BinaryExpression MakeSimpleBinary (ExpressionType et, Expression left, Expression right, MethodInfo method)
288 if (method == null) {
289 if (left.Type.IsNullable ()) {
290 if (!right.Type.IsNullable ())
291 throw new InvalidOperationException ("Assertion, internal error: left is nullable, requires right to be as well");
303 return new BinaryExpression (et, GetResultType (left, method), left, right, is_lifted, is_lifted, method, null);
306 static UnaryExpression MakeSimpleUnary (ExpressionType et, Expression expression, MethodInfo method)
311 if (method == null) {
312 type = expression.Type;
313 is_lifted = type.IsNullable ();
315 var parameter = method.GetParameters () [0].ParameterType;
316 type = method.ReturnType;
318 is_lifted = parameter.IsNullable () || expression.Type.IsNullable ();
320 if (is_lifted && !type.IsNullable ())
321 type = typeof (Nullable<>).MakeGenericType (type);
324 return new UnaryExpression (et, expression, type, method, is_lifted);
327 static BinaryExpression MakeBoolBinary (ExpressionType et, Expression left, Expression right, bool liftToNull, MethodInfo method)
330 Type ltype = left.Type;
331 Type rtype = right.Type;
332 bool lnullable = ltype.IsNullable ();
333 bool rnullable = rtype.IsNullable ();
336 // Implement the rules as described in "Expression.Equal" method.
337 if (method == null) {
338 if (!lnullable && !rnullable) {
341 result = typeof (bool);
342 } else if (lnullable && rnullable) {
344 result = liftToNull ? typeof(bool?) : typeof (bool);
346 throw new InvalidOperationException ("Internal error: this should have been caught in BinaryCoreCheck");
348 ParameterInfo [] pi = method.GetParameters ();
349 Type mltype = pi [0].ParameterType;
350 Type mrtype = pi [1].ParameterType;
352 if (ltype == mltype && rtype == mrtype) {
355 result = method.ReturnType;
356 } else if (ltype.IsValueType && rtype.IsValueType &&
357 ((lnullable && GetNullableArgumentType (ltype) == mltype) ||
358 (rnullable && GetNullableArgumentType (rtype) == mrtype))){
360 if (method.ReturnType == typeof(bool)){
361 result = liftToNull ? typeof(bool?) : typeof(bool);
364 // This behavior is not documented: what
365 // happens if the result is not typeof(bool), but
366 // the parameters are nullable: the result
367 // becomes nullable<returntype>
370 // https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=323139
371 result = typeof (Nullable<>).MakeGenericType (method.ReturnType);
376 result = method.ReturnType;
380 return new BinaryExpression (et, result, left, right, liftToNull, is_lifted, method, null);
386 public static BinaryExpression Add (Expression left, Expression right)
388 return Add (left, right, null);
391 public static BinaryExpression Add (Expression left, Expression right, MethodInfo method)
393 method = BinaryCoreCheck ("op_Addition", left, right, method);
395 return MakeSimpleBinary (ExpressionType.Add, left, right, method);
398 public static BinaryExpression AddChecked (Expression left, Expression right)
400 return AddChecked (left, right, null);
403 public static BinaryExpression AddChecked (Expression left, Expression right, MethodInfo method)
405 method = BinaryCoreCheck ("op_Addition", left, right, method);
407 // The check in BinaryCoreCheck allows a bit more than we do
408 // (byte, sbyte). Catch that here
409 if (method == null) {
410 if (left.Type == typeof (byte) || left.Type == typeof (sbyte))
411 throw new InvalidOperationException (String.Format ("AddChecked not defined for {0} and {1}", left.Type, right.Type));
414 return MakeSimpleBinary (ExpressionType.AddChecked, left, right, method);
417 public static BinaryExpression Subtract (Expression left, Expression right)
419 return Subtract (left, right, null);
422 public static BinaryExpression Subtract (Expression left, Expression right, MethodInfo method)
424 method = BinaryCoreCheck ("op_Subtraction", left, right, method);
426 return MakeSimpleBinary (ExpressionType.Subtract, left, right, method);
429 public static BinaryExpression SubtractChecked (Expression left, Expression right)
431 return SubtractChecked (left, right, null);
434 public static BinaryExpression SubtractChecked (Expression left, Expression right, MethodInfo method)
436 method = BinaryCoreCheck ("op_Subtraction", left, right, method);
438 // The check in BinaryCoreCheck allows a bit more than we do
439 // (byte, sbyte). Catch that here
440 if (method == null) {
441 if (left.Type == typeof (byte) || left.Type == typeof (sbyte))
442 throw new InvalidOperationException (String.Format ("SubtractChecked not defined for {0} and {1}", left.Type, right.Type));
445 return MakeSimpleBinary (ExpressionType.SubtractChecked, left, right, method);
448 public static BinaryExpression Modulo (Expression left, Expression right)
450 return Modulo (left, right, null);
453 public static BinaryExpression Modulo (Expression left, Expression right, MethodInfo method)
455 method = BinaryCoreCheck ("op_Modulus", left, right, method);
457 return MakeSimpleBinary (ExpressionType.Modulo, left, right, method);
460 public static BinaryExpression Multiply (Expression left, Expression right)
462 return Multiply (left, right, null);
465 public static BinaryExpression Multiply (Expression left, Expression right, MethodInfo method)
467 method = BinaryCoreCheck ("op_Multiply", left, right, method);
469 return MakeSimpleBinary (ExpressionType.Multiply, left, right, method);
472 public static BinaryExpression MultiplyChecked (Expression left, Expression right)
474 return MultiplyChecked (left, right, null);
477 public static BinaryExpression MultiplyChecked (Expression left, Expression right, MethodInfo method)
479 method = BinaryCoreCheck ("op_Multiply", left, right, method);
481 return MakeSimpleBinary (ExpressionType.MultiplyChecked, left, right, method);
484 public static BinaryExpression Divide (Expression left, Expression right)
486 return Divide (left, right, null);
489 public static BinaryExpression Divide (Expression left, Expression right, MethodInfo method)
491 method = BinaryCoreCheck ("op_Division", left, right, method);
493 return MakeSimpleBinary (ExpressionType.Divide, left, right, method);
496 public static BinaryExpression Power (Expression left, Expression right)
498 return Power (left, right, null);
501 public static BinaryExpression Power (Expression left, Expression right, MethodInfo method)
503 method = BinaryCoreCheck (null, left, right, method);
505 if (GetNotNullableOf (left.Type) != typeof (double))
506 throw new InvalidOperationException ("Power only supports double arguments");
508 return MakeSimpleBinary (ExpressionType.Power, left, right, method);
514 public static BinaryExpression And (Expression left, Expression right)
516 return And (left, right, null);
519 public static BinaryExpression And (Expression left, Expression right, MethodInfo method)
521 method = BinaryBitwiseCoreCheck ("op_BitwiseAnd", left, right, method);
523 return MakeSimpleBinary (ExpressionType.And, left, right, method);
526 public static BinaryExpression Or (Expression left, Expression right)
528 return Or (left, right, null);
531 public static BinaryExpression Or (Expression left, Expression right, MethodInfo method)
533 method = BinaryBitwiseCoreCheck ("op_BitwiseOr", left, right, method);
535 return MakeSimpleBinary (ExpressionType.Or, left, right, method);
538 public static BinaryExpression ExclusiveOr (Expression left, Expression right)
540 return ExclusiveOr (left, right, null);
543 public static BinaryExpression ExclusiveOr (Expression left, Expression right, MethodInfo method)
545 method = BinaryBitwiseCoreCheck ("op_ExclusiveOr", left, right, method);
547 return MakeSimpleBinary (ExpressionType.ExclusiveOr, left, right, method);
550 public static BinaryExpression LeftShift (Expression left, Expression right)
552 return LeftShift (left, right, null);
555 public static BinaryExpression LeftShift (Expression left, Expression right, MethodInfo method)
557 method = BinaryBitwiseCoreCheck ("op_LeftShift", left, right, method);
559 return MakeSimpleBinary (ExpressionType.LeftShift, left, right, method);
562 public static BinaryExpression RightShift (Expression left, Expression right)
564 return RightShift (left, right, null);
567 public static BinaryExpression RightShift (Expression left, Expression right, MethodInfo method)
569 method = BinaryCoreCheck ("op_RightShift", left, right, method);
571 return MakeSimpleBinary (ExpressionType.RightShift, left, right, method);
577 public static BinaryExpression AndAlso (Expression left, Expression right)
579 return AndAlso (left, right, null);
582 public static BinaryExpression AndAlso (Expression left, Expression right, MethodInfo method)
584 method = ConditionalBinaryCheck ("op_BitwiseAnd", left, right, method);
586 return MakeBoolBinary (ExpressionType.AndAlso, left, right, true, method);
589 static MethodInfo ConditionalBinaryCheck (string oper, Expression left, Expression right, MethodInfo method)
591 method = BinaryCoreCheck (oper, left, right, method);
593 if (method == null) {
594 if (GetNotNullableOf (left.Type) != typeof (bool))
595 throw new InvalidOperationException ("Only booleans are allowed");
597 // The method should have identical parameter and return types.
598 if (left.Type != right.Type || method.ReturnType != left.Type)
599 throw new ArgumentException ("left, right and return type must match");
605 public static BinaryExpression OrElse (Expression left, Expression right)
607 return OrElse (left, right, null);
610 public static BinaryExpression OrElse (Expression left, Expression right, MethodInfo method)
612 method = ConditionalBinaryCheck ("op_BitwiseOr", left, right, method);
614 return MakeBoolBinary (ExpressionType.OrElse, left, right, true, method);
620 public static BinaryExpression Equal (Expression left, Expression right)
622 return Equal (left, right, false, null);
625 public static BinaryExpression Equal (Expression left, Expression right, bool liftToNull, MethodInfo method)
627 method = BinaryCoreCheck ("op_Equality", left, right, method);
629 return MakeBoolBinary (ExpressionType.Equal, left, right, liftToNull, method);
632 public static BinaryExpression NotEqual (Expression left, Expression right)
634 return NotEqual (left, right, false, null);
638 public static BinaryExpression NotEqual (Expression left, Expression right, bool liftToNull, MethodInfo method)
640 method = BinaryCoreCheck ("op_Inequality", left, right, method);
642 return MakeBoolBinary (ExpressionType.NotEqual, left, right, liftToNull, method);
645 public static BinaryExpression GreaterThan (Expression left, Expression right)
647 return GreaterThan (left, right, false, null);
650 public static BinaryExpression GreaterThan (Expression left, Expression right, bool liftToNull, MethodInfo method)
652 method = BinaryCoreCheck ("op_GreaterThan", left, right, method);
654 return MakeBoolBinary (ExpressionType.GreaterThan, left, right, liftToNull, method);
657 public static BinaryExpression GreaterThanOrEqual (Expression left, Expression right)
659 return GreaterThanOrEqual (left, right, false, null);
663 public static BinaryExpression GreaterThanOrEqual (Expression left, Expression right, bool liftToNull, MethodInfo method)
665 method = BinaryCoreCheck ("op_GreaterThanOrEqual", left, right, method);
667 return MakeBoolBinary (ExpressionType.GreaterThanOrEqual, left, right, liftToNull, method);
670 public static BinaryExpression LessThan (Expression left, Expression right)
672 return LessThan (left, right, false, null);
675 public static BinaryExpression LessThan (Expression left, Expression right, bool liftToNull, MethodInfo method)
677 method = BinaryCoreCheck ("op_LessThan", left, right, method);
679 return MakeBoolBinary (ExpressionType.LessThan, left, right, liftToNull, method);
682 public static BinaryExpression LessThanOrEqual (Expression left, Expression right)
684 return LessThanOrEqual (left, right, false, null);
687 public static BinaryExpression LessThanOrEqual (Expression left, Expression right, bool liftToNull, MethodInfo method)
689 method = BinaryCoreCheck ("op_LessThanOrEqual", left, right, method);
691 return MakeBoolBinary (ExpressionType.LessThanOrEqual, left, right, liftToNull, method);
698 static void CheckArray (Expression array)
701 throw new ArgumentNullException ("array");
702 if (!array.Type.IsArray)
703 throw new ArgumentException ("The array argument must be of type array");
706 public static BinaryExpression ArrayIndex (Expression array, Expression index)
711 throw new ArgumentNullException ("index");
712 if (array.Type.GetArrayRank () != 1)
713 throw new ArgumentException ("The array argument must be a single dimensional array");
714 if (index.Type != typeof (int))
715 throw new ArgumentException ("The index must be of type int");
717 return new BinaryExpression (ExpressionType.ArrayIndex, array.Type.GetElementType (), array, index);
720 public static BinaryExpression Coalesce (Expression left, Expression right)
722 return Coalesce (left, right, null);
725 public static BinaryExpression Coalesce (Expression left, Expression right, LambdaExpression conversion)
728 throw new ArgumentNullException ("left");
730 throw new ArgumentNullException ("right");
733 // First arg must ne nullable (either Nullable<T> or a reference type
735 if (left.Type.IsValueType && !left.Type.IsNullable ())
736 throw new InvalidOperationException ("Left expression can never be null");
740 if (left.Type.IsNullable ()) {
741 Type lbase = GetNullableArgumentType (left.Type);
743 if (!right.Type.IsNullable () && right.Type.IsAssignableTo (lbase))
747 if (result == null && right.Type.IsAssignableTo (left.Type))
750 if (result == null) {
751 if (left.Type.IsNullable () && GetNullableArgumentType (left.Type).IsAssignableTo (right.Type))
756 throw new ArgumentException ("Incompatible argument types");
759 // FIXME: What do we do with "conversion"?
761 return new BinaryExpression (ExpressionType.Coalesce, result, left, right, false, false, null, conversion);
765 // MakeBinary constructors
767 public static BinaryExpression MakeBinary (ExpressionType binaryType, Expression left, Expression right)
769 return MakeBinary (binaryType, left, right, false, null);
772 public static BinaryExpression MakeBinary (ExpressionType binaryType, Expression left, Expression right, bool liftToNull, MethodInfo method)
774 return MakeBinary (binaryType, left, right, liftToNull, method, null);
777 public static BinaryExpression MakeBinary (ExpressionType binaryType, Expression left, Expression right, bool liftToNull, MethodInfo method, LambdaExpression conversion)
779 switch (binaryType) {
780 case ExpressionType.Add:
781 return Add (left, right, method);
782 case ExpressionType.AddChecked:
783 return AddChecked (left, right, method);
784 case ExpressionType.AndAlso:
785 return AndAlso (left, right);
786 case ExpressionType.Coalesce:
787 return Coalesce (left, right, conversion);
788 case ExpressionType.Divide:
789 return Divide (left, right, method);
790 case ExpressionType.Equal:
791 return Equal (left, right, liftToNull, method);
792 case ExpressionType.ExclusiveOr:
793 return ExclusiveOr (left, right, method);
794 case ExpressionType.GreaterThan:
795 return GreaterThan (left, right, liftToNull, method);
796 case ExpressionType.GreaterThanOrEqual:
797 return GreaterThanOrEqual (left, right, liftToNull, method);
798 case ExpressionType.LeftShift:
799 return LeftShift (left, right, method);
800 case ExpressionType.LessThan:
801 return LessThan (left, right, liftToNull, method);
802 case ExpressionType.LessThanOrEqual:
803 return LessThanOrEqual (left, right, liftToNull, method);
804 case ExpressionType.Modulo:
805 return Modulo (left, right, method);
806 case ExpressionType.Multiply:
807 return Multiply (left, right, method);
808 case ExpressionType.MultiplyChecked:
809 return MultiplyChecked (left, right, method);
810 case ExpressionType.NotEqual:
811 return NotEqual (left, right, liftToNull, method);
812 case ExpressionType.OrElse:
813 return OrElse (left, right);
814 case ExpressionType.Power:
815 return Power (left, right, method);
816 case ExpressionType.RightShift:
817 return RightShift (left, right, method);
818 case ExpressionType.Subtract:
819 return Subtract (left, right, method);
820 case ExpressionType.SubtractChecked:
821 return SubtractChecked (left, right, method);
822 case ExpressionType.And:
823 return And (left, right, method);
824 case ExpressionType.Or:
825 return Or (left, right, method);
828 throw new ArgumentException ("MakeBinary expect a binary node type");
833 public static MethodCallExpression ArrayIndex (Expression array, params Expression [] indexes)
835 return ArrayIndex (array, indexes as IEnumerable<Expression>);
838 public static MethodCallExpression ArrayIndex (Expression array, IEnumerable<Expression> indexes)
843 throw new ArgumentNullException ("indexes");
845 var args = indexes.ToReadOnlyCollection ();
846 if (array.Type.GetArrayRank () != args.Count)
847 throw new ArgumentException ("The number of arguments doesn't match the rank of the array");
849 foreach (var arg in args)
850 if (arg.Type != typeof (int))
851 throw new ArgumentException ("The index must be of type int");
853 return Call (array, array.Type.GetMethod ("Get", PublicInstance), args);
856 public static UnaryExpression ArrayLength (Expression array)
859 throw new ArgumentNullException ("array");
860 if (!array.Type.IsArray)
861 throw new ArgumentException ("The type of the expression must me Array");
862 if (array.Type.GetArrayRank () != 1)
863 throw new ArgumentException ("The array must be a single dimensional array");
865 return new UnaryExpression (ExpressionType.ArrayLength, array, typeof (int));
868 public static MemberAssignment Bind (MemberInfo member, Expression expression)
871 throw new ArgumentNullException ("member");
872 if (expression == null)
873 throw new ArgumentNullException ("expression");
877 var prop = member as PropertyInfo;
878 if (prop != null && prop.GetSetMethod (true) != null)
879 type = prop.PropertyType;
881 var field = member as FieldInfo;
883 type = field.FieldType;
886 throw new ArgumentException ("member");
888 if (!expression.Type.IsAssignableTo (type))
889 throw new ArgumentException ("member");
891 return new MemberAssignment (member, expression);
894 public static MemberAssignment Bind (MethodInfo propertyAccessor, Expression expression)
896 if (propertyAccessor == null)
897 throw new ArgumentNullException ("propertyAccessor");
898 if (expression == null)
899 throw new ArgumentNullException ("expression");
901 var prop = GetAssociatedProperty (propertyAccessor);
903 throw new ArgumentException ("propertyAccessor");
905 var setter = prop.GetSetMethod (true);
907 throw new ArgumentException ("setter");
909 if (!expression.Type.IsAssignableTo (prop.PropertyType))
910 throw new ArgumentException ("member");
912 return new MemberAssignment (prop, expression);
915 public static MethodCallExpression Call (Expression instance, MethodInfo method)
917 return Call (instance, method, null as IEnumerable<Expression>);
920 public static MethodCallExpression Call (MethodInfo method, params Expression [] arguments)
922 return Call (null, method, arguments as IEnumerable<Expression>);
925 public static MethodCallExpression Call (Expression instance, MethodInfo method, params Expression [] arguments)
927 return Call (instance, method, arguments as IEnumerable<Expression>);
930 public static MethodCallExpression Call (Expression instance, MethodInfo method, IEnumerable<Expression> arguments)
933 throw new ArgumentNullException ("method");
934 if (instance == null && !method.IsStatic)
935 throw new ArgumentNullException ("instance");
936 if (!method.IsStatic && !instance.Type.IsAssignableTo (method.DeclaringType))
937 throw new ArgumentException ("Type is not assignable to the declaring type of the method");
939 var args = arguments.ToReadOnlyCollection ();
941 CheckMethodArguments (method, args);
943 return new MethodCallExpression (instance, method, args);
946 static Type [] CollectTypes (IEnumerable<Expression> expressions)
948 return (from arg in expressions select arg.Type).ToArray ();
951 static MethodInfo TryMakeGeneric (MethodInfo method, Type [] args)
956 if (!method.IsGenericMethod && args == null)
959 if (args.Length == method.GetGenericArguments ().Length)
960 return method.MakeGenericMethod (args);
965 public static MethodCallExpression Call (Expression instance, string methodName, Type [] typeArguments, params Expression [] arguments)
967 if (instance == null)
968 throw new ArgumentNullException ("instance");
969 if (methodName == null)
970 throw new ArgumentNullException ("methodName");
972 var method = TryGetMethod (instance.Type, methodName, AllInstance,
973 CollectTypes (arguments), typeArguments);
975 var args = arguments.ToReadOnlyCollection ();
977 CheckMethodArguments (method, args);
979 return new MethodCallExpression (instance, method, args);
982 static bool MethodMatch (MethodInfo method, string name, Type [] parameterTypes)
984 if (method.Name != name)
987 var parameters = method.GetParameters ();
989 if (parameters.Length != parameterTypes.Length)
992 if (method.IsGenericMethod) // if it's a generic method, when can't compare its parameters
995 for (int i = 0; i < parameters.Length; i++)
996 if (!IsAssignableToParameterType (parameterTypes [i], parameters [i]))
1002 static MethodInfo TryGetMethod (Type type, string methodName, BindingFlags flags, Type [] parameterTypes, Type [] argumentTypes)
1004 var methods = from meth in type.GetMethods (flags)
1005 where MethodMatch (meth, methodName, parameterTypes)
1008 if (methods.Count () > 1)
1009 throw new InvalidOperationException ("Too much method candidates");
1011 var method = TryMakeGeneric (methods.FirstOrDefault (), argumentTypes);
1015 throw new InvalidOperationException ("No such method");
1018 public static MethodCallExpression Call (Type type, string methodName, Type [] typeArguments, params Expression [] arguments)
1021 throw new ArgumentNullException ("type");
1022 if (methodName == null)
1023 throw new ArgumentNullException ("methodName");
1025 var method = TryGetMethod (type, methodName, AllStatic,
1026 CollectTypes (arguments), typeArguments);
1028 var args = arguments.ToReadOnlyCollection ();
1030 CheckMethodArguments (method, args);
1032 return new MethodCallExpression (method, args);
1035 public static ConditionalExpression Condition (Expression test, Expression ifTrue, Expression ifFalse)
1038 throw new ArgumentNullException ("test");
1040 throw new ArgumentNullException ("ifTrue");
1041 if (ifFalse == null)
1042 throw new ArgumentNullException ("ifFalse");
1043 if (test.Type != typeof (bool))
1044 throw new ArgumentException ("Test expression should be of type bool");
1045 if (ifTrue.Type != ifFalse.Type)
1046 throw new ArgumentException ("The ifTrue and ifFalse type do not match");
1048 return new ConditionalExpression (test, ifTrue, ifFalse);
1051 public static ConstantExpression Constant (object value)
1054 return new ConstantExpression (null, typeof (object));
1056 return Constant (value, value.GetType ());
1059 public static ConstantExpression Constant (object value, Type type)
1062 throw new ArgumentNullException ("type");
1065 // value must be compatible with type, no conversions
1069 if (type.IsValueType && !type.IsNullable ())
1070 throw new ArgumentException ();
1072 if (!(type.IsValueType && type.IsNullable ()) && !value.GetType ().IsAssignableTo (type))
1073 throw new ArgumentException ();
1077 return new ConstantExpression (value, type);
1080 static bool IsConvertiblePrimitive (Type type)
1082 var t = GetNotNullableOf (type);
1084 if (t == typeof (bool))
1090 return t.IsPrimitive;
1093 internal static bool IsPrimitiveConversion (Type type, Type target)
1098 if (IsConvertiblePrimitive (type) && IsConvertiblePrimitive (target))
1104 internal static bool IsReferenceConversion (Type type, Type target)
1109 if (type.IsAssignableTo (target) || target.IsAssignableTo (type))
1112 if (type == typeof (object) || target == typeof (object))
1115 if (type.IsInterface || target.IsInterface)
1121 public static UnaryExpression Convert (Expression expression, Type type)
1123 return Convert (expression, type, null);
1126 static MethodInfo GetUserConversionMethod (Type type, Type target)
1128 var method = GetUnaryOperator ("op_Explicit", type, type, target);
1130 method = GetUnaryOperator ("op_Implicit", type, type, target);
1132 throw new InvalidOperationException ();
1137 public static UnaryExpression Convert (Expression expression, Type type, MethodInfo method)
1139 if (expression == null)
1140 throw new ArgumentNullException ("expression");
1142 throw new ArgumentNullException ("type");
1144 var et = expression.Type;
1147 CheckUnaryMethod (method, et);
1148 else if (!IsPrimitiveConversion (et, type) && !IsReferenceConversion (et, type))
1149 method = GetUserConversionMethod (et, type);
1151 return new UnaryExpression (ExpressionType.Convert,
1152 expression, type, method,
1153 IsConvertNodeLifted (method, expression, type));
1156 static bool IsConvertNodeLifted (MethodInfo method, Expression operand, Type target)
1159 return operand.Type.IsNullable () || target.IsNullable ();
1161 if (operand.Type.IsNullable () && !ParameterMatch (method, operand.Type))
1164 if (target.IsNullable () && !ReturnTypeMatch (method, target))
1170 static bool ParameterMatch (MethodInfo method, Type type)
1172 return method.GetParameters () [0].ParameterType == type;
1175 static bool ReturnTypeMatch (MethodInfo method, Type type)
1177 return method.ReturnType == type;
1180 public static UnaryExpression ConvertChecked (Expression expression, Type type)
1182 return ConvertChecked (expression, type, null);
1185 public static UnaryExpression ConvertChecked (Expression expression, Type type, MethodInfo method)
1187 if (expression == null)
1188 throw new ArgumentNullException ("expression");
1190 throw new ArgumentNullException ("type");
1192 var et = expression.Type;
1195 CheckUnaryMethod (method, et);
1196 else if (IsReferenceConversion (et, type))
1197 return Convert (expression, type, method);
1198 else if (!IsPrimitiveConversion (et, type))
1199 method = GetUserConversionMethod (et, type);
1201 return new UnaryExpression (ExpressionType.ConvertChecked,
1202 expression, type, method,
1203 IsConvertNodeLifted (method, expression, type));
1206 public static ElementInit ElementInit (MethodInfo addMethod, params Expression [] arguments)
1208 return ElementInit (addMethod, arguments as IEnumerable<Expression>);
1211 public static ElementInit ElementInit (MethodInfo addMethod, IEnumerable<Expression> arguments)
1213 if (addMethod == null)
1214 throw new ArgumentNullException ("addMethod");
1215 if (arguments == null)
1216 throw new ArgumentNullException ("arguments");
1217 if (addMethod.Name.ToLowerInvariant () != "add")
1218 throw new ArgumentException ("addMethod");
1219 if (addMethod.IsStatic)
1220 throw new ArgumentException ("addMethod must be an instance method", "addMethod");
1222 var args = arguments.ToReadOnlyCollection ();
1224 CheckMethodArguments (addMethod, args);
1226 return new ElementInit (addMethod, args);
1229 public static MemberExpression Field (Expression expression, FieldInfo field)
1232 throw new ArgumentNullException ("field");
1233 if (!field.IsStatic) {
1234 if (expression == null)
1235 throw new ArgumentNullException ("expression");
1236 if (!expression.Type.IsAssignableTo (field.DeclaringType))
1237 throw new ArgumentException ("field");
1240 return new MemberExpression (expression, field, field.FieldType);
1243 public static MemberExpression Field (Expression expression, string fieldName)
1245 if (expression == null)
1246 throw new ArgumentNullException ("expression");
1248 var field = expression.Type.GetField (fieldName, AllInstance);
1250 throw new ArgumentException (string.Format ("No field named {0} on {1}", fieldName, expression.Type));
1252 return new MemberExpression (expression, field, field.FieldType);
1255 public static Type GetActionType (params Type [] typeArgs)
1257 if (typeArgs == null)
1258 throw new ArgumentNullException ("typeArgs");
1260 if (typeArgs.Length > 4)
1261 throw new ArgumentException ("No Action type of this arity");
1263 if (typeArgs.Length == 0)
1264 return typeof (Action);
1267 switch (typeArgs.Length) {
1269 action = typeof (Action<>);
1272 action = typeof (Action<,>);
1275 action = typeof (Action<,,>);
1278 action = typeof (Action<,,,>);
1282 return action.MakeGenericType (typeArgs);
1285 public static Type GetFuncType (params Type [] typeArgs)
1287 if (typeArgs == null)
1288 throw new ArgumentNullException ("typeArgs");
1290 if (typeArgs.Length < 1 || typeArgs.Length > 5)
1291 throw new ArgumentException ("No Func type of this arity");
1294 switch (typeArgs.Length) {
1296 func = typeof (Func<>);
1299 func = typeof (Func<,>);
1302 func = typeof (Func<,,>);
1305 func = typeof (Func<,,,>);
1308 func = typeof (Func<,,,,>);
1312 return func.MakeGenericType (typeArgs);
1315 public static InvocationExpression Invoke (Expression expression, params Expression [] arguments)
1317 return Invoke (expression, arguments as IEnumerable<Expression>);
1320 static Type GetInvokableType (Type t)
1322 if (t.IsAssignableTo (typeof (Delegate)))
1325 return GetGenericType (t, typeof (Expression<>));
1328 static Type GetGenericType (Type t, Type def)
1333 if (t.IsGenericType && t.GetGenericTypeDefinition () == def)
1336 return GetGenericType (t.BaseType, def);
1339 public static InvocationExpression Invoke (Expression expression, IEnumerable<Expression> arguments)
1341 if (expression == null)
1342 throw new ArgumentNullException ("expression");
1344 var type = GetInvokableType (expression.Type);
1346 throw new ArgumentException ("The type of the expression is not invokable");
1348 var args = arguments.ToReadOnlyCollection ();
1349 CheckForNull (args, "arguments");
1351 var invoke = type.GetMethod ("Invoke");
1353 throw new ArgumentException ("expression");
1355 if (invoke.GetParameters ().Length != args.Count)
1356 throw new InvalidOperationException ("Arguments count doesn't match parameters length");
1358 CheckMethodArguments (invoke, args);
1360 return new InvocationExpression (expression, invoke.ReturnType, args);
1363 static bool CanAssign (Type target, Type source)
1365 // This catches object and value type mixage, type compatibility is handled later
1366 if (target.IsValueType ^ source.IsValueType)
1369 return source.IsAssignableTo (target);
1372 static void CheckLambda (Type delegateType, Expression body, ReadOnlyCollection<ParameterExpression> parameters)
1374 if (!delegateType.IsSubclassOf (typeof (System.Delegate)))
1375 throw new ArgumentException ("delegateType");
1377 var invoke = delegateType.GetMethod ("Invoke", BindingFlags.Instance | BindingFlags.Public);
1379 throw new ArgumentException ("delegate must contain an Invoke method", "delegateType");
1381 var invoke_parameters = invoke.GetParameters ();
1382 if (invoke_parameters.Length != parameters.Count)
1383 throw new ArgumentException (string.Format ("Different number of arguments in delegate {0}", delegateType), "delegateType");
1385 for (int i = 0; i < invoke_parameters.Length; i++) {
1386 if (!CanAssign (parameters [i].Type, invoke_parameters [i].ParameterType))
1387 throw new ArgumentException (String.Format ("Can not assign a {0} to a {1}", invoke_parameters [i].ParameterType, parameters [i].Type));
1390 if (invoke.ReturnType != typeof (void) && !CanAssign (invoke.ReturnType, body.Type))
1391 throw new ArgumentException (String.Format ("body type {0} can not be assigned to {1}", body.Type, invoke.ReturnType));
1394 public static Expression<TDelegate> Lambda<TDelegate> (Expression body, params ParameterExpression [] parameters)
1396 return Lambda<TDelegate> (body, parameters as IEnumerable<ParameterExpression>);
1399 public static Expression<TDelegate> Lambda<TDelegate> (Expression body, IEnumerable<ParameterExpression> parameters)
1402 throw new ArgumentNullException ("body");
1404 var ps = parameters.ToReadOnlyCollection ();
1406 CheckLambda (typeof (TDelegate), body, ps);
1408 return new Expression<TDelegate> (body, ps);
1411 public static LambdaExpression Lambda (Expression body, params ParameterExpression [] parameters)
1414 throw new ArgumentNullException ("body");
1415 if (parameters.Length > 4)
1416 throw new ArgumentException ("Too many parameters");
1418 return Lambda (GetDelegateType (body.Type, parameters), body, parameters);
1421 static Type GetDelegateType (Type return_type, ParameterExpression [] parameters)
1423 if (parameters == null)
1424 parameters = new ParameterExpression [0];
1426 if (return_type == typeof (void))
1427 return GetActionType (parameters.Select (p => p.Type).ToArray ());
1429 var types = new Type [parameters.Length + 1];
1430 for (int i = 0; i < types.Length - 1; i++)
1431 types [i] = parameters [i].Type;
1433 types [types.Length - 1] = return_type;
1434 return GetFuncType (types);
1437 public static LambdaExpression Lambda (Type delegateType, Expression body, params ParameterExpression [] parameters)
1439 return Lambda (delegateType, body, parameters as IEnumerable<ParameterExpression>);
1442 static LambdaExpression CreateExpressionOf (Type type, Expression body, ReadOnlyCollection<ParameterExpression> parameters)
1444 return (LambdaExpression) Activator.CreateInstance (
1445 typeof (Expression<>).MakeGenericType (type),
1446 NonPublicInstance, null, new object [] { body, parameters }, null);
1449 public static LambdaExpression Lambda (Type delegateType, Expression body, IEnumerable<ParameterExpression> parameters)
1451 if (delegateType == null)
1452 throw new ArgumentNullException ("delegateType");
1454 throw new ArgumentNullException ("body");
1456 var ps = parameters.ToReadOnlyCollection ();
1458 CheckLambda (delegateType, body, ps);
1460 return CreateExpressionOf (delegateType, body, ps);
1463 public static MemberListBinding ListBind (MemberInfo member, params ElementInit [] initializers)
1465 return ListBind (member, initializers as IEnumerable<ElementInit>);
1468 static void CheckIsAssignableToIEnumerable (Type t)
1470 if (!t.IsAssignableTo (typeof (IEnumerable)))
1471 throw new ArgumentException (string.Format ("Type {0} doesn't implemen IEnumerable", t));
1474 public static MemberListBinding ListBind (MemberInfo member, IEnumerable<ElementInit> initializers)
1477 throw new ArgumentNullException ("member");
1478 if (initializers == null)
1479 throw new ArgumentNullException ("initializers");
1481 var inits = initializers.ToReadOnlyCollection ();
1482 CheckForNull (inits, "initializers");
1484 member.OnFieldOrProperty (
1485 field => CheckIsAssignableToIEnumerable (field.FieldType),
1486 prop => CheckIsAssignableToIEnumerable (prop.PropertyType));
1488 return new MemberListBinding (member, inits);
1491 public static MemberListBinding ListBind (MethodInfo propertyAccessor, params ElementInit [] initializers)
1493 return ListBind (propertyAccessor, initializers as IEnumerable<ElementInit>);
1496 static void CheckForNull<T> (ReadOnlyCollection<T> collection, string name) where T : class
1498 foreach (var t in collection)
1500 throw new ArgumentNullException (name);
1503 public static MemberListBinding ListBind (MethodInfo propertyAccessor, IEnumerable<ElementInit> initializers)
1505 if (propertyAccessor == null)
1506 throw new ArgumentNullException ("propertyAccessor");
1507 if (initializers == null)
1508 throw new ArgumentNullException ("initializers");
1510 var inits = initializers.ToReadOnlyCollection ();
1511 CheckForNull (inits, "initializers");
1513 var prop = GetAssociatedProperty (propertyAccessor);
1515 throw new ArgumentException ("propertyAccessor");
1517 CheckIsAssignableToIEnumerable (prop.PropertyType);
1519 return new MemberListBinding (prop, inits);
1522 public static ListInitExpression ListInit (NewExpression newExpression, params ElementInit [] initializers)
1524 return ListInit (newExpression, initializers as IEnumerable<ElementInit>);
1527 public static ListInitExpression ListInit (NewExpression newExpression, IEnumerable<ElementInit> initializers)
1529 var inits = CheckListInit (newExpression, initializers);
1531 return new ListInitExpression (newExpression, inits);
1534 public static ListInitExpression ListInit (NewExpression newExpression, params Expression [] initializers)
1536 return ListInit (newExpression, initializers as IEnumerable<Expression>);
1539 public static ListInitExpression ListInit (NewExpression newExpression, IEnumerable<Expression> initializers)
1541 var inits = CheckListInit (newExpression, initializers);
1543 var add_method = GetAddMethod (newExpression.Type, inits [0].Type);
1544 if (add_method == null)
1545 throw new InvalidOperationException ("No suitable add method found");
1547 return new ListInitExpression (newExpression, CreateInitializers (add_method, inits));
1550 static ReadOnlyCollection<ElementInit> CreateInitializers (MethodInfo add_method, ReadOnlyCollection<Expression> initializers)
1552 return (from init in initializers select Expression.ElementInit (add_method, init)).ToReadOnlyCollection ();
1555 static MethodInfo GetAddMethod (Type type, Type arg)
1557 return type.GetMethod ("Add", PublicInstance | BindingFlags.IgnoreCase, null, new [] { arg }, null);
1560 public static ListInitExpression ListInit (NewExpression newExpression, MethodInfo addMethod, params Expression [] initializers)
1562 return ListInit (newExpression, addMethod, initializers as IEnumerable<Expression>);
1565 static ReadOnlyCollection<T> CheckListInit<T> (NewExpression newExpression, IEnumerable<T> initializers) where T : class
1567 if (newExpression == null)
1568 throw new ArgumentNullException ("newExpression");
1569 if (initializers == null)
1570 throw new ArgumentNullException ("initializers");
1571 if (!newExpression.Type.IsAssignableTo (typeof (IEnumerable)))
1572 throw new InvalidOperationException ("The type of the new expression does not implement IEnumerable");
1574 var inits = initializers.ToReadOnlyCollection ();
1575 if (inits.Count == 0)
1576 throw new ArgumentException ("Empty initializers");
1578 CheckForNull (inits, "initializers");
1583 public static ListInitExpression ListInit (NewExpression newExpression, MethodInfo addMethod, IEnumerable<Expression> initializers)
1585 var inits = CheckListInit (newExpression, initializers);
1587 if (addMethod != null) {
1588 if (addMethod.Name.ToLowerInvariant () != "add")
1589 throw new ArgumentException ("addMethod");
1591 var parameters = addMethod.GetParameters ();
1592 if (parameters.Length != 1)
1593 throw new ArgumentException ("addMethod");
1595 foreach (var expression in inits)
1596 if (!IsAssignableToParameterType (expression.Type, parameters [0]))
1597 throw new InvalidOperationException ("Initializer not assignable to the add method parameter type");
1600 if (addMethod == null)
1601 addMethod = GetAddMethod (newExpression.Type, inits [0].Type);
1603 if (addMethod == null)
1604 throw new InvalidOperationException ("No suitable add method found");
1606 return new ListInitExpression (newExpression, CreateInitializers (addMethod, inits));
1609 public static MemberExpression MakeMemberAccess (Expression expression, MemberInfo member)
1611 if (expression == null)
1612 throw new ArgumentNullException ("expression");
1614 throw new ArgumentNullException ("member");
1616 var field = member as FieldInfo;
1618 return Field (expression, field);
1620 var property = member as PropertyInfo;
1621 if (property != null)
1622 return Property (expression, property);
1624 throw new ArgumentException ("Member should either be a field or a property");
1627 public static UnaryExpression MakeUnary (ExpressionType unaryType, Expression operand, Type type)
1629 return MakeUnary (unaryType, operand, type, null);
1632 public static UnaryExpression MakeUnary (ExpressionType unaryType, Expression operand, Type type, MethodInfo method)
1634 switch (unaryType) {
1635 case ExpressionType.ArrayLength:
1636 return ArrayLength (operand);
1637 case ExpressionType.Convert:
1638 return Convert (operand, type, method);
1639 case ExpressionType.ConvertChecked:
1640 return ConvertChecked (operand, type, method);
1641 case ExpressionType.Negate:
1642 return Negate (operand, method);
1643 case ExpressionType.NegateChecked:
1644 return NegateChecked (operand, method);
1645 case ExpressionType.Not:
1646 return Not (operand, method);
1647 case ExpressionType.Quote:
1648 return Quote (operand);
1649 case ExpressionType.TypeAs:
1650 return TypeAs (operand, type);
1651 case ExpressionType.UnaryPlus:
1652 return UnaryPlus (operand, method);
1655 throw new ArgumentException ("MakeUnary expect an unary operator");
1658 public static MemberMemberBinding MemberBind (MemberInfo member, params MemberBinding [] bindings)
1660 return MemberBind (member, bindings as IEnumerable<MemberBinding>);
1663 public static MemberMemberBinding MemberBind (MemberInfo member, IEnumerable<MemberBinding> bindings)
1666 throw new ArgumentNullException ("member");
1668 var type = member.OnFieldOrProperty (
1669 field => field.FieldType,
1670 prop => prop.PropertyType);
1672 return new MemberMemberBinding (member, CheckMemberBindings (type, bindings));
1675 public static MemberMemberBinding MemberBind (MethodInfo propertyAccessor, params MemberBinding [] bindings)
1677 return MemberBind (propertyAccessor, bindings as IEnumerable<MemberBinding>);
1680 public static MemberMemberBinding MemberBind (MethodInfo propertyAccessor, IEnumerable<MemberBinding> bindings)
1682 if (propertyAccessor == null)
1683 throw new ArgumentNullException ("propertyAccessor");
1685 var bds = bindings.ToReadOnlyCollection ();
1686 CheckForNull (bds, "bindings");
1688 var prop = GetAssociatedProperty (propertyAccessor);
1690 throw new ArgumentException ("propertyAccessor");
1692 return new MemberMemberBinding (prop, CheckMemberBindings (prop.PropertyType, bindings));
1695 static ReadOnlyCollection<MemberBinding> CheckMemberBindings (Type type, IEnumerable<MemberBinding> bindings)
1697 if (bindings == null)
1698 throw new ArgumentNullException ("bindings");
1700 var bds = bindings.ToReadOnlyCollection ();
1701 CheckForNull (bds, "bindings");
1703 foreach (var binding in bds)
1704 if (!type.IsAssignableTo (binding.Member.DeclaringType))
1705 throw new ArgumentException ("Type not assignable to member type");
1710 public static MemberInitExpression MemberInit (NewExpression newExpression, params MemberBinding [] bindings)
1712 return MemberInit (newExpression, bindings as IEnumerable<MemberBinding>);
1715 public static MemberInitExpression MemberInit (NewExpression newExpression, IEnumerable<MemberBinding> bindings)
1717 if (newExpression == null)
1718 throw new ArgumentNullException ("newExpression");
1720 return new MemberInitExpression (newExpression, CheckMemberBindings (newExpression.Type, bindings));
1723 public static UnaryExpression Negate (Expression expression)
1725 return Negate (expression, null);
1728 public static UnaryExpression Negate (Expression expression, MethodInfo method)
1730 method = UnaryCoreCheck ("op_UnaryNegation", expression, method, type => IsSignedNumber (type));
1732 return MakeSimpleUnary (ExpressionType.Negate, expression, method);
1735 public static UnaryExpression NegateChecked (Expression expression)
1737 return NegateChecked (expression, null);
1740 public static UnaryExpression NegateChecked (Expression expression, MethodInfo method)
1742 method = UnaryCoreCheck ("op_UnaryNegation", expression, method, type => IsSignedNumber (type));
1744 return MakeSimpleUnary (ExpressionType.Negate, expression, method);
1747 public static NewExpression New (ConstructorInfo constructor)
1749 if (constructor == null)
1750 throw new ArgumentNullException ("constructor");
1752 if (constructor.GetParameters ().Length > 0)
1753 throw new ArgumentException ("Constructor must be parameter less");
1755 return new NewExpression (constructor, (null as IEnumerable<Expression>).ToReadOnlyCollection (), null);
1758 public static NewExpression New (Type type)
1761 throw new ArgumentNullException ("type");
1763 CheckNotVoid (type);
1765 var args = (null as IEnumerable<Expression>).ToReadOnlyCollection ();
1767 if (type.IsValueType)
1768 return new NewExpression (type, args);
1770 var ctor = type.GetConstructor (Type.EmptyTypes);
1772 throw new ArgumentException ("Type doesn't have a parameter less constructor");
1774 return new NewExpression (ctor, args, null);
1777 public static NewExpression New (ConstructorInfo constructor, params Expression [] arguments)
1779 return New (constructor, arguments as IEnumerable<Expression>);
1782 public static NewExpression New (ConstructorInfo constructor, IEnumerable<Expression> arguments)
1784 if (constructor == null)
1785 throw new ArgumentNullException ("constructor");
1787 var args = arguments.ToReadOnlyCollection ();
1789 CheckMethodArguments (constructor, args);
1791 return new NewExpression (constructor, args, null);
1794 static void CheckMethodArguments (MethodBase method, ReadOnlyCollection<Expression> arguments)
1796 var parameters = method.GetParameters ();
1798 if (arguments.Count != parameters.Length)
1799 throw new ArgumentException ("The number of arguments doesn't match the number of parameters");
1801 for (int i = 0; i < parameters.Length; i++) {
1802 if (arguments [i] == null)
1803 throw new ArgumentNullException ("arguments");
1805 if (!IsAssignableToParameterType (arguments [i].Type, parameters [i]))
1806 throw new ArgumentException ("arguments");
1810 public static NewExpression New (ConstructorInfo constructor, IEnumerable<Expression> arguments, params MemberInfo [] members)
1812 return New (constructor, arguments, members as IEnumerable<MemberInfo>);
1815 public static NewExpression New (ConstructorInfo constructor, IEnumerable<Expression> arguments, IEnumerable<MemberInfo> members)
1817 if (constructor == null)
1818 throw new ArgumentNullException ("constructor");
1820 var args = arguments.ToReadOnlyCollection ();
1821 var mmbs = members.ToReadOnlyCollection ();
1823 CheckForNull (args, "arguments");
1824 CheckForNull (mmbs, "members");
1826 CheckMethodArguments (constructor, args);
1828 if (args.Count != mmbs.Count)
1829 throw new ArgumentException ("Arguments count does not match members count");
1831 for (int i = 0; i < mmbs.Count; i++) {
1832 var member = mmbs [i];
1834 switch (member.MemberType) {
1835 case MemberTypes.Field:
1836 type = (member as FieldInfo).FieldType;
1838 case MemberTypes.Method:
1839 type = (member as MethodInfo).ReturnType;
1841 case MemberTypes.Property:
1842 var prop = member as PropertyInfo;
1843 if (prop.GetGetMethod (true) == null)
1844 throw new ArgumentException ("Property must have a getter");
1846 type = (member as PropertyInfo).PropertyType;
1849 throw new ArgumentException ("Member type not allowed");
1852 if (!args [i].Type.IsAssignableTo (type))
1853 throw new ArgumentException ("Argument type not assignable to member type");
1856 return new NewExpression (constructor, args, mmbs);
1859 public static NewArrayExpression NewArrayBounds (Type type, params Expression [] bounds)
1861 return NewArrayBounds (type, bounds as IEnumerable<Expression>);
1864 public static NewArrayExpression NewArrayBounds (Type type, IEnumerable<Expression> bounds)
1867 throw new ArgumentNullException ("type");
1869 throw new ArgumentNullException ("bounds");
1871 CheckNotVoid (type);
1873 var array_bounds = bounds.ToReadOnlyCollection ();
1874 foreach (var expression in array_bounds)
1875 if (!IsInt (expression.Type))
1876 throw new ArgumentException ("The bounds collection can only contain expression of integers types");
1878 return new NewArrayExpression (ExpressionType.NewArrayBounds, type.MakeArrayType (array_bounds.Count), array_bounds);
1881 public static NewArrayExpression NewArrayInit (Type type, params Expression [] initializers)
1883 return NewArrayInit (type, initializers as IEnumerable<Expression>);
1886 public static NewArrayExpression NewArrayInit (Type type, IEnumerable<Expression> initializers)
1889 throw new ArgumentNullException ("type");
1890 if (initializers == null)
1891 throw new ArgumentNullException ("initializers");
1893 CheckNotVoid (type);
1895 var inits = initializers.ToReadOnlyCollection ();
1897 foreach (var expression in inits) {
1898 if (expression == null)
1899 throw new ArgumentNullException ("initializers");
1901 if (!expression.Type.IsAssignableTo (type))
1902 throw new InvalidOperationException ();
1904 // TODO: Quote elements if type == typeof (Expression)
1907 return new NewArrayExpression (ExpressionType.NewArrayInit, type.MakeArrayType (), inits);
1910 public static UnaryExpression Not (Expression expression)
1912 return Not (expression, null);
1915 public static UnaryExpression Not (Expression expression, MethodInfo method)
1917 Func<Type, bool> validator = type => IsIntOrBool (type);
1919 method = UnaryCoreCheck ("op_LogicalNot", expression, method, validator);
1922 method = UnaryCoreCheck ("op_OnesComplement", expression, method, validator);
1924 return MakeSimpleUnary (ExpressionType.Not, expression, method);
1927 static void CheckNotVoid (Type type)
1929 if (type == typeof (void))
1930 throw new ArgumentException ("Type can't be void");
1933 public static ParameterExpression Parameter (Type type, string name)
1936 throw new ArgumentNullException ("type");
1938 CheckNotVoid (type);
1940 return new ParameterExpression (type, name);
1943 public static MemberExpression Property (Expression expression, MethodInfo propertyAccessor)
1945 if (propertyAccessor == null)
1946 throw new ArgumentNullException ("propertyAccessor");
1948 if (!propertyAccessor.IsStatic) {
1949 if (expression == null)
1950 throw new ArgumentNullException ("expression");
1951 if (!expression.Type.IsAssignableTo (propertyAccessor.DeclaringType))
1952 throw new ArgumentException ("expression");
1955 var prop = GetAssociatedProperty (propertyAccessor);
1957 throw new ArgumentException (string.Format ("Method {0} has no associated property", propertyAccessor));
1959 return new MemberExpression (expression, prop, prop.PropertyType);
1962 static PropertyInfo GetAssociatedProperty (MethodInfo method)
1964 foreach (var prop in method.DeclaringType.GetProperties (All)) {
1965 if (prop.GetGetMethod (true) == method)
1967 if (prop.GetSetMethod (true) == method)
1974 public static MemberExpression Property (Expression expression, PropertyInfo property)
1976 if (property == null)
1977 throw new ArgumentNullException ("property");
1979 var getter = property.GetGetMethod (true);
1981 throw new ArgumentException ("getter");
1983 if (!getter.IsStatic) {
1984 if (expression == null)
1985 throw new ArgumentNullException ("expression");
1986 if (!expression.Type.IsAssignableTo (property.DeclaringType))
1987 throw new ArgumentException ("expression");
1990 return new MemberExpression (expression, property, property.PropertyType);
1993 public static MemberExpression Property (Expression expression, string propertyName)
1995 if (expression == null)
1996 throw new ArgumentNullException ("expression");
1998 var prop = expression.Type.GetProperty (propertyName, AllInstance);
2000 throw new ArgumentException (string.Format ("No property named {0} on {1}", propertyName, expression.Type));
2002 return new MemberExpression (expression, prop, prop.PropertyType);
2005 public static MemberExpression PropertyOrField (Expression expression, string propertyOrFieldName)
2007 if (expression == null)
2008 throw new ArgumentNullException ("expression");
2009 if (propertyOrFieldName == null)
2010 throw new ArgumentNullException ("propertyOrFieldName");
2012 var prop = expression.Type.GetProperty (propertyOrFieldName, AllInstance);
2014 return new MemberExpression (expression, prop, prop.PropertyType);
2016 var field = expression.Type.GetField (propertyOrFieldName, AllInstance);
2018 return new MemberExpression (expression, field, field.FieldType);
2020 throw new ArgumentException (string.Format ("No field or property named {0} on {1}", propertyOrFieldName, expression.Type));
2023 public static UnaryExpression Quote (Expression expression)
2025 if (expression == null)
2026 throw new ArgumentNullException ("expression");
2028 return new UnaryExpression (ExpressionType.Quote, expression, expression.GetType ());
2031 public static UnaryExpression TypeAs (Expression expression, Type type)
2033 if (expression == null)
2034 throw new ArgumentNullException ("expression");
2036 throw new ArgumentNullException ("type");
2037 if (type.IsValueType && !type.IsNullable ())
2038 throw new ArgumentException ("TypeAs expect a reference or a nullable type");
2040 return new UnaryExpression (ExpressionType.TypeAs, expression, type);
2043 public static TypeBinaryExpression TypeIs (Expression expression, Type type)
2045 if (expression == null)
2046 throw new ArgumentNullException ("expression");
2048 throw new ArgumentNullException ("type");
2050 CheckNotVoid (type);
2052 return new TypeBinaryExpression (ExpressionType.TypeIs, expression, type, typeof (bool));
2055 public static UnaryExpression UnaryPlus (Expression expression)
2057 return UnaryPlus (expression, null);
2060 public static UnaryExpression UnaryPlus (Expression expression, MethodInfo method)
2062 method = UnaryCoreCheck ("op_UnaryPlus", expression, method, type => IsNumber (type));
2064 return MakeSimpleUnary (ExpressionType.UnaryPlus, expression, method);
2067 static bool IsInt (Type t)
2069 return t == typeof (byte) || t == typeof (sbyte) ||
2070 t == typeof (short) || t == typeof (ushort) ||
2071 t == typeof (int) || t == typeof (uint) ||
2072 t == typeof (long) || t == typeof (ulong);
2075 static bool IsIntOrBool (Type t)
2077 return IsInt (t) || t == typeof (bool);
2080 static bool IsNumber (Type t)
2085 return t == typeof (float) || t == typeof (double) || t == typeof (decimal);
2088 static bool IsSignedNumber (Type t)
2090 return IsNumber (t) && !IsUnsigned (t);
2093 internal static bool IsUnsigned (Type t)
2097 return IsUnsigned (t.GetElementType ());
2100 return t == typeof (ushort) ||
2101 t == typeof (uint) ||
2102 t == typeof (ulong) ||
2107 // returns the T in a a Nullable<T> type.
2109 internal static Type GetNullableArgumentType (Type type)
2111 return type.GetFirstGenericArgument ();
2114 internal static Type GetNotNullableOf (Type type)
2116 return type.IsNullable () ? GetNullableArgumentType (type) : type;
2120 // This method must be overwritten by derived classes to
2121 // compile the expression
2123 internal virtual void Emit (EmitContext ec)
2125 throw new NotImplementedException ();