1 // Permission is hereby granted, free of charge, to any person obtaining
2 // a copy of this software and associated documentation files (the
3 // "Software"), to deal in the Software without restriction, including
4 // without limitation the rights to use, copy, modify, merge, publish,
5 // distribute, sublicense, and/or sell copies of the Software, and to
6 // permit persons to whom the Software is furnished to do so, subject to
7 // the following conditions:
9 // The above copyright notice and this permission notice shall be
10 // included in all copies or substantial portions of the Software.
12 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
13 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
14 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
15 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
16 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
17 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
20 // Marek Safar (marek.safar@seznam.cz)
21 // Antonello Provenzano <antonello@deveel.com>
22 // Federico Di Gregorio <fog@initd.org>
24 using System.Collections.Generic;
25 using System.Collections.ObjectModel;
26 using System.Reflection;
29 namespace System.Linq.Expressions
31 public abstract class Expression
34 protected Expression (ExpressionType nodeType, Type type)
36 this.nodeType = nodeType;
43 private ExpressionType nodeType;
51 public ExpressionType NodeType {
52 get { return nodeType; }
56 #region Internal methods
57 internal virtual void BuildString (StringBuilder builder)
59 builder.Append ("[").Append (nodeType).Append ("]");
62 internal static Type GetNonNullableType(Type type)
64 // The Nullable<> class takes a single generic type so we can directly return
65 // the first element of the array (if the type is nullable.)
67 if (IsNullableType (type))
68 return type.GetGenericArguments ()[0];
73 internal static bool IsNullableType(Type type)
76 throw new ArgumentNullException("type");
78 if (type.IsGenericType) {
79 Type genType = type.GetGenericTypeDefinition();
80 return typeof(Nullable<>).IsAssignableFrom(genType);
87 #region Private support methods
88 private static int IsWhat(Type type)
90 // This method return a "type code" that can be easily compared to a bitmask
91 // to determine the "broad type" (integer, boolean, floating-point) of the given type.
92 // It is used by the three methods below.
94 if (IsNullableType (type))
95 type = GetNonNullableType (type);
97 switch (Type.GetTypeCode (type)) {
98 case TypeCode.Byte: case TypeCode.SByte:
99 case TypeCode.Int16: case TypeCode.UInt16:
100 case TypeCode.Int32: case TypeCode.UInt32:
101 case TypeCode.Int64: case TypeCode.UInt64:
104 case TypeCode.Boolean:
107 case TypeCode.Single:
108 case TypeCode.Double:
109 case TypeCode.Decimal:
117 private static bool IsInteger (Type type)
119 return (IsWhat(type) & 1) != 0;
122 private static bool IsIntegerOrBool (Type type)
124 return (IsWhat(type) & 3) != 0;
127 private static bool IsNumeric (Type type)
129 return (IsWhat(type) & 5) != 0;
132 private const BindingFlags opBindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
134 private static MethodInfo GetUserDefinedBinaryOperator (Type leftType, Type rightType, string name)
136 Type[] types = new Type[2] { leftType, rightType };
139 method = leftType.GetMethod (name, opBindingFlags, null, types, null);
140 if (method != null) return method;
142 method = rightType.GetMethod (name, opBindingFlags, null, types, null);
143 if (method != null) return method;
145 if (method == null && IsNullableType (leftType) && IsNullableType (rightType))
146 return GetUserDefinedBinaryOperator (GetNonNullableType (leftType), GetNonNullableType (rightType), name);
151 private static BinaryExpression GetUserDefinedBinaryOperatorOrThrow (ExpressionType nodeType, string name,
152 Expression left, Expression right)
154 MethodInfo method = GetUserDefinedBinaryOperator(left.type, right.type, name);
157 return new BinaryExpression (nodeType, left, right, method, method.ReturnType);
159 throw new InvalidOperationException (String.Format (
160 "The binary operator Add is not defined for the types '{0}' and '{1}'.", left.type, right.type));
162 // Note: here the code in ExpressionUtils has a series of checks to make sure that
163 // the method is static, that its return type is not void and that the number of
164 // parameters is 2 and they are of the right type, but we already know that! Or not?
167 private static MethodInfo FindMethod (Type type, string methodName, Type [] typeArgs, Expression [] args, BindingFlags flags)
169 MemberInfo[] members = type.FindMembers(MemberTypes.Method, flags,
170 delegate(MemberInfo mi, object obj) { return mi.Name == (String)obj; },
172 if (members.Length == 0)
173 throw new InvalidOperationException (String.Format (
174 "No method '{0}' exists on type '{1}'.", methodName, type.FullName));
176 MethodInfo methodDefinition = null;
177 MethodInfo method = null;
180 foreach (MemberInfo member in members) {
181 MethodInfo mi = (MethodInfo)member;
182 if (mi.IsGenericMethodDefinition) {
183 // If the generic method definition matches we save it away to be able to make the
184 // correct closed method later on.
185 Type[] genericArgs = mi.GetGenericArguments();
186 if (genericArgs.Length != typeArgs.Length) goto next;
188 methodDefinition = mi;
192 // If there is a discrepancy between method's generic types and the given types or if
193 // the method is open we simply discard it and go on.
194 if ((mi.IsGenericMethod && (typeArgs == null || mi.ContainsGenericParameters))
195 || (!mi.IsGenericMethod && typeArgs != null))
198 // If the method is a closed generic we try to match the generic types.
199 if (mi.IsGenericMethod) {
200 Type[] genericArgs = mi.GetGenericArguments();
201 if (genericArgs.Length != typeArgs.Length) goto next;
202 for (int i=0 ; i < genericArgs.Length ; i++)
203 if (genericArgs[i] != typeArgs[i]) goto next;
206 // Finally we test for the method's parameters.
207 ParameterInfo[] parameters = mi.GetParameters ();
208 if (parameters.Length != args.Length) goto next;
209 for (int i=0 ; i < parameters.Length ; i++)
210 if (parameters[i].ParameterType != args[i].type) goto next;
222 throw new InvalidOperationException(String.Format(
223 "No method '{0}' on type '{1}' is compatible with the supplied arguments.", methodName, type.FullName));
226 private static PropertyInfo GetProperty (MethodInfo mi)
228 // If the method has the hidebysig and specialname attributes it can be a property accessor;
229 // if that's the case we try to extract the type of the property and then we use it and the
230 // property name (derived from the method name) to find the right ProprtyInfo.
232 if (mi.IsHideBySig && mi.IsSpecialName) {
233 Type propertyType = null;
234 if (mi.Name.StartsWith("set_")) {
235 ParameterInfo[] parameters = mi.GetParameters();
236 if (parameters.Length == 1)
237 propertyType = parameters[0].ParameterType;
239 else if (mi.Name.StartsWith("get_")) {
240 propertyType = mi.ReturnType;
243 if (propertyType != null) {
244 PropertyInfo pi = mi.DeclaringType.GetProperty(mi.Name.Substring(4),
245 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
246 null, propertyType, new Type[0], null);
247 if (pi != null) return pi;
251 throw new ArgumentException (String.Format(
252 "The method '{0}.{1}' is not a property accessor", mi.DeclaringType.FullName, mi.Name));
255 private static void ValidateUserDefinedConditionalLogicOperator (ExpressionType nodeType, Type left, Type right, MethodInfo method)
257 // Conditional logic need the "definitely true" and "definitely false" operators.
258 Type[] types = new Type[1] { left };
260 MethodInfo opTrue = left.GetMethod ("op_True", opBindingFlags, null, types, null);
261 MethodInfo opFalse = left.GetMethod ("op_False", opBindingFlags, null, types, null);
263 if (opTrue == null || opFalse == null)
264 throw new ArgumentException (String.Format (
265 "The user-defined operator method '{0}' for operator '{1}' must have associated boolean True and False operators.",
266 method.Name, nodeType));
269 private static void ValidateSettableFieldOrPropertyMember (MemberInfo member, out Type memberType)
271 if (member.MemberType == MemberTypes.Field) {
272 memberType = typeof (FieldInfo);
274 else if (member.MemberType == MemberTypes.Property) {
275 PropertyInfo pi = (PropertyInfo)member;
277 throw new ArgumentException (String.Format ("The property '{0}' has no 'set' accessor", pi));
278 memberType = typeof (PropertyInfo);
281 throw new ArgumentException ("Argument must be either a FieldInfo or PropertyInfo");
287 public override string ToString()
289 StringBuilder builder = new StringBuilder ();
290 BuildString (builder);
291 return builder.ToString ();
296 public static BinaryExpression Add(Expression left, Expression right, MethodInfo method)
299 throw new ArgumentNullException ("left");
301 throw new ArgumentNullException ("right");
304 return new BinaryExpression(ExpressionType.Add, left, right, method, method.ReturnType);
306 // Since both the expressions define the same numeric type we don't have
307 // to look for the "op_Addition" method.
308 if (left.type == right.type && IsNumeric (left.type))
309 return new BinaryExpression(ExpressionType.Add, left, right, left.type);
311 // Else we try for a user-defined operator.
312 return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Add, "op_Addition", left, right);
315 public static BinaryExpression Add(Expression left, Expression right)
317 return Add(left, right, null);
322 public static BinaryExpression AddChecked(Expression left, Expression right, MethodInfo method)
325 throw new ArgumentNullException ("left");
327 throw new ArgumentNullException ("right");
330 return new BinaryExpression(ExpressionType.AddChecked, left, right, method, method.ReturnType);
332 // Since both the expressions define the same numeric type we don't have
333 // to look for the "op_Addition" method.
334 if (left.type == right.type && IsNumeric (left.type))
335 return new BinaryExpression(ExpressionType.AddChecked, left, right, left.type);
337 method = GetUserDefinedBinaryOperator (left.type, right.type, "op_Addition");
339 throw new InvalidOperationException(String.Format(
340 "The binary operator AddChecked is not defined for the types '{0}' and '{1}'.", left.type, right.type));
342 Type retType = method.ReturnType;
344 // Note: here the code did some very strange checks for bool (but note that bool does
345 // not define an addition operator) and created nullables for value types (but the new
346 // MS code does not do that). All that has been removed.
348 return new BinaryExpression(ExpressionType.AddChecked, left, right, method, retType);
351 public static BinaryExpression AddChecked(Expression left, Expression right)
353 return AddChecked(left, right, null);
358 public static BinaryExpression And(Expression left, Expression right, MethodInfo method)
361 throw new ArgumentNullException ("left");
363 throw new ArgumentNullException ("right");
366 return new BinaryExpression(ExpressionType.And, left, right, method, method.ReturnType);
368 // Since both the expressions define the same integer or boolean type we don't have
369 // to look for the "op_BitwiseAnd" method.
370 if (left.type == right.type && IsIntegerOrBool (left.type))
371 return new BinaryExpression(ExpressionType.And, left, right, left.type);
373 // Else we try for a user-defined operator.
374 return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.And, "op_BitwiseAnd", left, right);
377 public static BinaryExpression And(Expression left, Expression right)
379 return And(left, right, null);
384 public static BinaryExpression AndAlso(Expression left, Expression right, MethodInfo method)
387 throw new ArgumentNullException ("left");
389 throw new ArgumentNullException ("right");
391 // Since both the expressions define the same boolean type we don't have
392 // to look for the "op_BitwiseAnd" method.
393 if (left.type == right.type && left.type == typeof(bool))
394 return new BinaryExpression(ExpressionType.AndAlso, left, right, left.type);
396 // Else we must validate the method to make sure it has companion "true" and "false" operators.
398 method = GetUserDefinedBinaryOperator (left.type, right.type, "op_BitwiseAnd");
400 throw new InvalidOperationException(String.Format(
401 "The binary operator AndAlso is not defined for the types '{0}' and '{1}'.", left.type, right.type));
402 ValidateUserDefinedConditionalLogicOperator(ExpressionType.AndAlso, left.type, right.type, method);
404 return new BinaryExpression(ExpressionType.AndAlso, left, right, method, method.ReturnType);
407 public static BinaryExpression AndAlso(Expression left, Expression right)
409 return AndAlso(left, right, null);
414 public static BinaryExpression ArrayIndex(Expression array, Expression index)
417 throw new ArgumentNullException ("array");
419 throw new ArgumentNullException ("index");
420 if (!array.type.IsArray)
421 throw new ArgumentException ("Argument must be array");
422 if (index.type != typeof(int))
423 throw new ArgumentException ("Argument for array index must be of type Int32");
425 return new BinaryExpression(ExpressionType.ArrayIndex, array, index, array.type.GetElementType());
428 public static MethodCallExpression ArrayIndex(Expression array, params Expression[] indexes)
430 return ArrayIndex(array, (IEnumerable<Expression>)indexes);
433 public static MethodCallExpression ArrayIndex(Expression array, IEnumerable<Expression> indexes)
436 throw new ArgumentNullException ("array");
438 throw new ArgumentNullException ("indexes");
439 if (!array.type.IsArray)
440 throw new ArgumentException ("Argument must be array");
442 // We'll need an array of typeof(Type) elements long as the array's rank later
443 // and also a generic List to hold the indexes (ReadOnlyCollection wants that.)
445 Type[] types = (Type[])Array.CreateInstance(typeof(Type), array.type.GetArrayRank());
446 Expression[] indexesList = new Expression[array.type.GetArrayRank()];
449 foreach (Expression index in indexes) {
450 if (index.type != typeof(int))
451 throw new ArgumentException ("Argument for array index must be of type Int32");
452 if (rank == array.type.GetArrayRank())
453 throw new ArgumentException ("Incorrect number of indexes");
455 types[rank] = index.type;
456 indexesList[rank] = index;
460 // If the array's rank is equalto the number of given indexes we can go on and
461 // look for a Get(Int32, ...) method with "rank" parameters to generate the
462 // MethodCallExpression.
464 MethodInfo method = array.type.GetMethod("Get",
465 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, types, null);
467 // This should not happen, but we check anyway.
469 throw new InvalidOperationException(String.Format(
470 "The method Get(...) is not defined for the type '{0}'.", array.type));
472 return new MethodCallExpression(ExpressionType.Call, method, array, new ReadOnlyCollection<Expression>(indexesList));
477 public static UnaryExpression ArrayLength(Expression array)
480 throw new ArgumentNullException ("array");
481 if (!array.type.IsArray)
482 throw new ArgumentException ("Argument must be array");
484 return new UnaryExpression(ExpressionType.ArrayLength, array, typeof(Int32));
489 public static MemberAssignment Bind (MemberInfo member, Expression expression)
492 throw new ArgumentNullException ("member");
493 if (expression == null)
494 throw new ArgumentNullException ("expression");
497 ValidateSettableFieldOrPropertyMember(member, out memberType);
499 return new MemberAssignment(member, expression);
502 public static MemberAssignment Bind (MethodInfo propertyAccessor, Expression expression)
504 if (propertyAccessor == null)
505 throw new ArgumentNullException ("propertyAccessor");
506 if (expression == null)
507 throw new ArgumentNullException ("expression");
509 return new MemberAssignment(GetProperty(propertyAccessor), expression);
514 public static MethodCallExpression Call(Expression instance, MethodInfo method)
517 throw new ArgumentNullException("method");
518 if (instance == null && !method.IsStatic)
519 throw new ArgumentNullException("instance");
521 return Call(instance, method, (Expression[])null);
524 public static MethodCallExpression Call(Expression instance, MethodInfo method, params Expression[] arguments)
526 return Call(instance, method, (IEnumerable<Expression>)arguments);
529 public static MethodCallExpression Call(Expression instance, MethodInfo method, IEnumerable<Expression> arguments)
532 throw new ArgumentNullException("method");
533 if (arguments == null)
534 throw new ArgumentNullException("arguments");
535 if (instance == null && !method.IsStatic)
536 throw new ArgumentNullException("instance");
538 if (method.IsGenericMethodDefinition)
539 throw new ArgumentException();
540 if (method.ContainsGenericParameters)
541 throw new ArgumentException();
542 if (instance != null && !instance.type.IsAssignableFrom(method.DeclaringType))
543 throw new ArgumentException();
545 ReadOnlyCollection<Expression> roArgs = Enumerable.ToReadOnlyCollection<Expression>(arguments);
547 ParameterInfo[] pars = method.GetParameters();
548 if (Enumerable.Count<Expression>(arguments) != pars.Length)
549 throw new ArgumentException();
553 //TODO: validate the parameters against the arguments...
556 return new MethodCallExpression(ExpressionType.Call, method, instance, roArgs);
559 public static MethodCallExpression Call (Expression instance, string methodName, Type [] typeArguments, params Expression [] arguments)
561 if (instance == null)
562 throw new ArgumentNullException("instance");
563 if (arguments == null)
564 throw new ArgumentNullException("arguments");
566 return Call (null, FindMethod (instance.type, methodName, typeArguments, arguments,
567 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance),
568 (IEnumerable<Expression>)arguments);
571 public static MethodCallExpression Call(MethodInfo method, params Expression[] arguments)
573 return Call(null, method, (IEnumerable<Expression>)arguments);
576 public static MethodCallExpression Call (Type type, string methodName, Type [] typeArguments, params Expression [] arguments)
578 // FIXME: MS implementation does not check for type here and simply lets FindMethod() raise
579 // a NullReferenceException. Shall we do the same or raise the correct exception here?
581 // throw new ArgumentNullException("type");
583 if (methodName == null)
584 throw new ArgumentNullException("methodName");
585 if (arguments == null)
586 throw new ArgumentNullException("arguments");
588 // Note that we're looking for static methods only (this version of Call() doesn't take an instance).
589 return Call (null, FindMethod (type, methodName, typeArguments, arguments,
590 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static),
591 (IEnumerable<Expression>)arguments);
595 // NOTE: CallVirtual is not implemented because it is already marked as Obsolete by MS.
597 public static ConditionalExpression Condition(Expression test, Expression ifTrue, Expression ifFalse)
600 throw new ArgumentNullException("test");
602 throw new ArgumentNullException("ifTrue");
604 throw new ArgumentNullException("ifFalse");
605 if (test.type != typeof(bool))
606 throw new ArgumentException();
607 if (ifTrue.type != ifFalse.type)
608 throw new ArgumentException();
610 return new ConditionalExpression(test, ifTrue, ifFalse, ifTrue.type);
613 public static ConstantExpression Constant(object value, Type type)
616 throw new ArgumentNullException("type");
617 if (value == null && !IsNullableType(type))
618 throw new ArgumentException("Argument types do not match");
620 return new ConstantExpression(value, type);
623 public static ConstantExpression Constant(object value)
626 return new ConstantExpression(value, value.GetType());
628 return new ConstantExpression(null, typeof(object));
632 public static BinaryExpression Divide(Expression left, Expression right, MethodInfo method)
635 throw new ArgumentNullException ("left");
637 throw new ArgumentNullException ("right");
640 return new BinaryExpression(ExpressionType.Divide, left, right, method, method.ReturnType);
642 // Since both the expressions define the same numeric type we don't have
643 // to look for the "op_Addition" method.
644 if (left.type == right.type && IsNumeric (left.type))
645 return new BinaryExpression(ExpressionType.Divide, left, right, left.type);
647 // Else we try for a user-defined operator.
648 return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Divide, "op_Division", left, right);
651 public static BinaryExpression Divide(Expression left, Expression right)
653 return Divide(left, right, null);
658 public static BinaryExpression ExclusiveOr (Expression left, Expression right, System.Reflection.MethodInfo method)
661 throw new ArgumentNullException ("left");
663 throw new ArgumentNullException ("right");
666 return new BinaryExpression(ExpressionType.ExclusiveOr, left, right, method, method.ReturnType);
668 // Since both the expressions define the same integer or boolean type we don't have
669 // to look for the "op_BitwiseAnd" method.
670 if (left.type == right.type && IsIntegerOrBool (left.type))
671 return new BinaryExpression(ExpressionType.ExclusiveOr, left, right, left.type);
673 // Else we try for a user-defined operator.
674 return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.ExclusiveOr, "op_ExclusiveOr", left, right);
677 public static BinaryExpression ExclusiveOr (Expression left, Expression right)
679 return ExclusiveOr (left, right, null);
683 public static MemberExpression Field(Expression expression, FieldInfo field)
686 throw new ArgumentNullException("field");
688 return new MemberExpression(expression, field, field.FieldType);
691 public static MemberExpression Field(Expression expression, string fieldName)
693 if (expression == null)
694 throw new ArgumentNullException("expression");
696 FieldInfo field = expression.Type.GetField(fieldName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
698 throw new ArgumentException();
700 return Field(expression, field);
703 public static FuncletExpression Funclet(Funclet funclet, Type type)
706 throw new ArgumentNullException("funclet");
708 throw new ArgumentNullException("type");
710 return new FuncletExpression(funclet, type);
713 public static Type GetFuncType(params Type[] typeArgs)
715 if (typeArgs == null)
716 throw new ArgumentNullException("typeArgs");
717 if (typeArgs.Length > 5)
718 throw new ArgumentException();
720 return typeof(Func<,,,,>).MakeGenericType(typeArgs);
724 public static BinaryExpression LeftShift (Expression left, Expression right, MethodInfo method)
727 throw new ArgumentNullException ("left");
729 throw new ArgumentNullException ("right");
732 return new BinaryExpression(ExpressionType.LeftShift, left, right, method, method.ReturnType);
734 // If the left side is any kind of integer and the right is int32 we don't have
735 // to look for the "op_Addition" method.
736 if (IsInteger(left.type) && right.type == typeof(Int32))
737 return new BinaryExpression(ExpressionType.LeftShift, left, right, left.type);
739 // Else we try for a user-defined operator.
740 return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.LeftShift, "op_LeftShift", left, right);
743 public static BinaryExpression LeftShift (Expression left, Expression right)
745 return LeftShift (left, right, null);
749 public static ListInitExpression ListInit(NewExpression newExpression, params Expression[] initializers)
751 if (initializers == null)
752 throw new ArgumentNullException("inizializers");
754 return ListInit(newExpression, Enumerable.ToReadOnlyCollection<Expression>(initializers));
757 public static ListInitExpression ListInit(NewExpression newExpression, IEnumerable<Expression> initializers)
759 if (newExpression == null)
760 throw new ArgumentNullException("newExpression");
761 if (initializers == null)
762 throw new ArgumentNullException("inizializers");
764 return new ListInitExpression(newExpression, Enumerable.ToReadOnlyCollection<Expression>(initializers));
767 public static MemberInitExpression MemberInit(NewExpression newExpression, IEnumerable<MemberBinding> bindings)
769 if (newExpression == null)
770 throw new ArgumentNullException("newExpression");
772 if (bindings == null)
773 throw new ArgumentNullException("bindings");
775 return new MemberInitExpression(newExpression, Enumerable.ToReadOnlyCollection<MemberBinding>(bindings));
779 public static BinaryExpression Modulo (Expression left, Expression right, MethodInfo method)
782 throw new ArgumentNullException ("left");
784 throw new ArgumentNullException ("right");
787 return new BinaryExpression(ExpressionType.Modulo, left, right, method, method.ReturnType);
789 // Since both the expressions define the same integer or boolean type we don't have
790 // to look for the "op_BitwiseAnd" method.
791 if (left.type == right.type && IsNumeric (left.type))
792 return new BinaryExpression(ExpressionType.Modulo, left, right, left.type);
794 // Else we try for a user-defined operator.
795 return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Modulo, "op_Modulus", left, right);
799 public static BinaryExpression Modulo (Expression left, Expression right)
801 return Modulo (left, right, null);
806 public static BinaryExpression Multiply (Expression left, Expression right, MethodInfo method)
809 throw new ArgumentNullException ("left");
811 throw new ArgumentNullException ("right");
814 return new BinaryExpression(ExpressionType.Multiply, left, right, method, method.ReturnType);
816 // Since both the expressions define the same integer or boolean type we don't have
817 // to look for the "op_BitwiseAnd" method.
818 if (left.type == right.type && IsNumeric (left.type))
819 return new BinaryExpression(ExpressionType.Multiply, left, right, left.type);
821 // Else we try for a user-defined operator.
822 return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Multiply, "op_Multiply", left, right);
826 public static BinaryExpression Multiply (Expression left, Expression right)
828 return Multiply (left, right, null);
832 #region MultiplyChecked
833 public static BinaryExpression MultiplyChecked (Expression left, Expression right, MethodInfo method)
836 throw new ArgumentNullException ("left");
838 throw new ArgumentNullException ("right");
841 return new BinaryExpression(ExpressionType.MultiplyChecked, left, right, method, method.ReturnType);
843 // Since both the expressions define the same numeric type we don't have
844 // to look for the "op_Addition" method.
845 if (left.type == right.type && IsNumeric (left.type))
846 return new BinaryExpression(ExpressionType.MultiplyChecked, left, right, left.type);
848 method = GetUserDefinedBinaryOperator (left.type, right.type, "op_Multiply");
850 throw new InvalidOperationException(String.Format(
851 "The binary operator MultiplyChecked is not defined for the types '{0}' and '{1}'.", left.type, right.type));
853 Type retType = method.ReturnType;
855 return new BinaryExpression(ExpressionType.MultiplyChecked, left, right, method, retType);
858 public static BinaryExpression MultiplyChecked (Expression left, Expression right)
860 return MultiplyChecked(left, right, null);
864 public static MemberExpression Property(Expression expression, PropertyInfo property)
866 if (property == null)
867 throw new ArgumentNullException("property");
869 MethodInfo getMethod = property.GetGetMethod(true);
870 if (getMethod == null)
871 throw new ArgumentException(); // to access the property we need to have
874 return new MemberExpression(expression, property, property.PropertyType);
878 public static BinaryExpression Or (Expression left, Expression right, MethodInfo method)
881 throw new ArgumentNullException ("left");
883 throw new ArgumentNullException ("right");
886 return new BinaryExpression(ExpressionType.Or, left, right, method, method.ReturnType);
888 // Since both the expressions define the same integer or boolean type we don't have
889 // to look for the "op_BitwiseOr" method.
890 if (left.type == right.type && IsIntegerOrBool (left.type))
891 return new BinaryExpression(ExpressionType.Or, left, right, left.type);
893 // Else we try for a user-defined operator.
894 return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Or, "op_BitwiseOr", left, right);
898 public static BinaryExpression Or (Expression left, Expression right)
900 return Or (left, right, null);
905 public static BinaryExpression OrElse (Expression left, Expression right, MethodInfo method)
908 throw new ArgumentNullException ("left");
910 throw new ArgumentNullException ("right");
912 // Since both the expressions define the same boolean type we don't have
913 // to look for the "op_BitwiseOr" method.
914 if (left.type == right.type && left.type == typeof(bool))
915 return new BinaryExpression(ExpressionType.OrElse, left, right, left.type);
917 // Else we must validate the method to make sure it has companion "true" and "false" operators.
919 method = GetUserDefinedBinaryOperator (left.type, right.type, "op_BitwiseOr");
921 throw new InvalidOperationException(String.Format(
922 "The binary operator OrElse is not defined for the types '{0}' and '{1}'.", left.type, right.type));
923 ValidateUserDefinedConditionalLogicOperator(ExpressionType.OrElse, left.type, right.type, method);
925 return new BinaryExpression(ExpressionType.OrElse, left, right, method, method.ReturnType);
928 public static BinaryExpression OrElse (Expression left, Expression right)
930 return OrElse(left, right, null);
934 public static UnaryExpression Quote(Expression expression)
936 if (expression == null)
937 throw new ArgumentNullException("expression");
939 return new UnaryExpression(ExpressionType.Quote, expression, expression.GetType());
943 public static MemberExpression Property(Expression expression, string propertyName)
945 if (expression == null)
946 throw new ArgumentNullException("expression");
948 PropertyInfo property = expression.Type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
950 if (property == null)
951 throw new ArgumentException();
953 return Property(expression, property);
956 public static MemberExpression PropertyOrField(Expression expression, string propertyOrFieldName)
958 if (expression == null)
959 throw new ArgumentNullException("expression");
961 PropertyInfo property = expression.Type.GetProperty(propertyOrFieldName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
962 if (property != null)
963 return Property(expression, property);
965 FieldInfo field = expression.Type.GetField(propertyOrFieldName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
967 return Field(expression, field);
969 //TODO: should we return <null> here?
970 // the name is not defined in the Type of the expression given...
971 throw new ArgumentException();
975 public static BinaryExpression RightShift (Expression left, Expression right, MethodInfo method)
978 throw new ArgumentNullException ("left");
980 throw new ArgumentNullException ("right");
983 return new BinaryExpression(ExpressionType.RightShift, left, right, method, method.ReturnType);
985 // If the left side is any kind of integer and the right is int32 we don't have
986 // to look for the "op_Addition" method.
987 if (IsInteger(left.type) && right.type == typeof(Int32))
988 return new BinaryExpression(ExpressionType.RightShift, left, right, left.type);
990 // Else we try for a user-defined operator.
991 return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.RightShift, "op_RightShift", left, right);
994 public static BinaryExpression RightShift (Expression left, Expression right)
996 return RightShift (left, right, null);
1001 public static BinaryExpression Subtract (Expression left, Expression right, MethodInfo method)
1004 throw new ArgumentNullException ("left");
1006 throw new ArgumentNullException ("right");
1009 return new BinaryExpression(ExpressionType.Subtract, left, right, method, method.ReturnType);
1011 // Since both the expressions define the same numeric type we don't have
1012 // to look for the "op_Addition" method.
1013 if (left.type == right.type && IsNumeric (left.type))
1014 return new BinaryExpression(ExpressionType.Subtract, left, right, left.type);
1016 // Else we try for a user-defined operator.
1017 return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Subtract, "op_Subtraction", left, right);
1020 public static BinaryExpression Subtract (Expression left, Expression right)
1022 return Subtract (left, right, null);
1026 #region SubtractChecked
1027 public static BinaryExpression SubtractChecked (Expression left, Expression right, MethodInfo method)
1030 throw new ArgumentNullException ("left");
1032 throw new ArgumentNullException ("right");
1035 return new BinaryExpression(ExpressionType.SubtractChecked, left, right, method, method.ReturnType);
1037 // Since both the expressions define the same numeric type we don't have
1038 // to look for the "op_Addition" method.
1039 if (left.type == right.type && IsNumeric (left.type))
1040 return new BinaryExpression(ExpressionType.SubtractChecked, left, right, left.type);
1042 method = GetUserDefinedBinaryOperator (left.type, right.type, "op_Subtraction");
1044 throw new InvalidOperationException(String.Format(
1045 "The binary operator AddChecked is not defined for the types '{0}' and '{1}'.", left.type, right.type));
1047 Type retType = method.ReturnType;
1049 // Note: here the code did some very strange checks for bool (but note that bool does
1050 // not define an addition operator) and created nullables for value types (but the new
1051 // MS code does not do that). All that has been removed.
1053 return new BinaryExpression(ExpressionType.SubtractChecked, left, right, method, retType);
1056 public static BinaryExpression SubtractChecked (Expression left, Expression right)
1058 return SubtractChecked (left, right, null);
1063 public static UnaryExpression TypeAs(Expression expression, Type type)
1065 if (expression == null)
1066 throw new ArgumentNullException("expression");
1068 throw new ArgumentNullException("type");
1070 return new UnaryExpression(ExpressionType.TypeAs, expression, type);
1075 public static TypeBinaryExpression TypeIs(Expression expression, Type type)
1077 if (expression == null)
1078 throw new ArgumentNullException("expression");
1080 throw new ArgumentNullException("type");
1082 return new TypeBinaryExpression(ExpressionType.TypeIs, expression, type, typeof(bool));