Implemented RightShift and LeftShift.
[mono.git] / mcs / class / System.Core / System.Linq.Expressions / Expression.cs
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:
8 // 
9 // The above copyright notice and this permission notice shall be
10 // included in all copies or substantial portions of the Software.
11 // 
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
18 //
19 // Authors:
20 //        Marek Safar (marek.safar@seznam.cz)
21 //        Antonello Provenzano  <antonello@deveel.com>
22 //        Federico Di Gregorio <fog@initd.org>
23
24 using System.Collections.Generic;
25 using System.Collections.ObjectModel;
26 using System.Reflection;
27 using System.Text;
28
29 namespace System.Linq.Expressions
30 {
31     public abstract class Expression
32     {
33         #region .ctor
34         protected Expression (ExpressionType nodeType, Type type)
35         {
36             this.nodeType = nodeType;
37             this.type = type;
38         }
39         #endregion
40         
41         #region Fields
42         private Type type;
43         private ExpressionType nodeType;
44         #endregion
45         
46         #region Properties
47         public Type Type {
48             get { return type; }
49         }
50
51         public ExpressionType NodeType {
52             get { return nodeType; }
53         }
54         #endregion
55
56         #region Internal methods 
57         internal virtual void BuildString (StringBuilder builder)
58         {
59             builder.Append ("[").Append (nodeType).Append ("]");
60         }
61         
62         internal static Type GetNonNullableType(Type type)
63         {
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.)
66             
67             if (IsNullableType (type))
68                 return type.GetGenericArguments ()[0];
69             else
70                 return type;
71         }
72
73         internal static bool IsNullableType(Type type)
74         {
75             if (type == null)
76                 throw new ArgumentNullException("type");
77
78             if (type.IsGenericType) {
79                 Type genType = type.GetGenericTypeDefinition();
80                 return typeof(Nullable<>).IsAssignableFrom(genType);
81             }
82
83             return false;
84         }
85         #endregion
86         
87         #region Private support methods
88         private static int IsWhat(Type type)
89         {
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.
93
94             if (IsNullableType (type))
95                 type = GetNonNullableType (type);
96                 
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:
102                 return 1;
103                 
104                 case TypeCode.Boolean:
105                 return 2;
106                 
107                 case TypeCode.Single:
108                 case TypeCode.Double:
109                 case TypeCode.Decimal:
110                 return 4;
111                 
112                 default:
113                 return 0;
114             }
115         }
116         
117         private static bool IsInteger (Type type)
118         {
119             return (IsWhat(type) & 1) != 0;
120         }
121
122         private static bool IsIntegerOrBool (Type type)
123         {
124             return (IsWhat(type) & 3) != 0;
125         }
126
127         private static bool IsNumeric (Type type)
128         {
129             return (IsWhat(type) & 5) != 0;        
130         }
131         
132         private const BindingFlags opBindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
133
134         private static MethodInfo GetUserDefinedBinaryOperator (Type leftType, Type rightType, string name)
135         {
136             Type[] types = new Type[2] { leftType, rightType };
137             MethodInfo method;
138             
139             method  = leftType.GetMethod (name, opBindingFlags, null, types, null);
140             if (method != null) return method;
141                 
142             method = rightType.GetMethod (name, opBindingFlags, null, types, null);
143             if (method != null) return method;
144
145             if (method == null && IsNullableType (leftType) && IsNullableType (rightType))
146                 return GetUserDefinedBinaryOperator (GetNonNullableType (leftType), GetNonNullableType (rightType), name);
147         
148             return null;
149         }
150
151         private static BinaryExpression GetUserDefinedBinaryOperatorOrThrow (ExpressionType nodeType, string name,
152                 Expression left, Expression right)
153         {
154             MethodInfo method = GetUserDefinedBinaryOperator(left.type, right.type, name);
155
156             if (method != null)
157                 return new BinaryExpression (nodeType, left, right, method, method.ReturnType);
158             else
159                 throw new InvalidOperationException (String.Format (
160                     "The binary operator Add is not defined for the types '{0}' and '{1}'.", left.type, right.type));
161
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?
165         }
166         
167         private static MethodInfo FindMethod (Type type, string methodName, Type [] typeArgs, Expression [] args, BindingFlags flags)
168         {
169             MemberInfo[] members = type.FindMembers(MemberTypes.Method, flags,
170                 delegate(MemberInfo mi, object obj) { return mi.Name == (String)obj; },
171                 methodName);
172             if (members.Length == 0)
173                 throw new InvalidOperationException (String.Format (
174                     "No method '{0}' exists on type '{1}'.", methodName, type.FullName));
175
176             MethodInfo methodDefinition = null;
177             MethodInfo method = null;
178             int methodCount = 1;        
179
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;
187
188                     methodDefinition = mi;
189                     goto next;
190                 }
191                 
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))
196                     goto next;
197                     
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;
204                 }
205                 
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;
211
212                 method = mi;
213                 break;
214                 
215              next:
216                 continue;
217             }
218             
219             if (method != null)
220                 return method;
221             else
222                 throw new InvalidOperationException(String.Format(
223                     "No method '{0}' on type '{1}' is compatible with the supplied arguments.", methodName, type.FullName));
224         }
225
226         private static PropertyInfo GetProperty (MethodInfo mi)
227         {
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.
231             
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;
238                 }
239                 else if (mi.Name.StartsWith("get_")) {
240                     propertyType = mi.ReturnType;
241                 }
242                 
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;
248                 }
249             }
250             
251             throw new ArgumentException (String.Format( 
252                 "The method '{0}.{1}' is not a property accessor", mi.DeclaringType.FullName, mi.Name));
253         }
254         
255         private static void ValidateUserDefinedConditionalLogicOperator (ExpressionType nodeType, Type left, Type right, MethodInfo method)
256         {
257             // Conditional logic need the "definitely true" and "definitely false" operators.
258             Type[] types = new Type[1] { left };
259                         
260             MethodInfo opTrue  = left.GetMethod ("op_True", opBindingFlags, null, types, null);
261             MethodInfo opFalse = left.GetMethod ("op_False", opBindingFlags, null, types, null);
262             
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));
267         }
268         
269         private static void ValidateSettableFieldOrPropertyMember (MemberInfo member, out Type memberType)
270         {
271             if (member.MemberType == MemberTypes.Field) {
272                 memberType = typeof (FieldInfo);
273             }
274             else if (member.MemberType == MemberTypes.Property) {
275                 PropertyInfo pi = (PropertyInfo)member;
276                 if (!pi.CanWrite)
277                     throw new ArgumentException (String.Format ("The property '{0}' has no 'set' accessor", pi));
278                 memberType = typeof (PropertyInfo);
279             }
280             else {
281                 throw new ArgumentException ("Argument must be either a FieldInfo or PropertyInfo");   
282             }
283         }
284         #endregion
285                 
286         #region ToString
287         public override string ToString()
288         {
289             StringBuilder builder = new StringBuilder ();
290             BuildString (builder);
291             return builder.ToString ();
292         }
293         #endregion
294
295         #region Add
296         public static BinaryExpression Add(Expression left, Expression right, MethodInfo method)
297         {
298             if (left == null)
299                 throw new ArgumentNullException ("left");
300             if (right == null)
301                 throw new ArgumentNullException ("right");
302
303             if (method != null)
304                 return new BinaryExpression(ExpressionType.Add, left, right, method, method.ReturnType);
305             
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);
310
311             // Else we try for a user-defined operator.
312             return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Add, "op_Addition", left, right);
313         }
314
315         public static BinaryExpression Add(Expression left, Expression right)
316         {
317             return Add(left, right, null);
318         }
319         #endregion
320         
321         #region AddChecked
322         public static BinaryExpression AddChecked(Expression left, Expression right, MethodInfo method)
323         {
324             if (left == null)
325                 throw new ArgumentNullException ("left");
326             if (right == null)
327                 throw new ArgumentNullException ("right");
328
329             if (method != null)
330                 return new BinaryExpression(ExpressionType.AddChecked, left, right, method, method.ReturnType);
331
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);
336
337             method = GetUserDefinedBinaryOperator (left.type, right.type, "op_Addition");
338             if (method == null)
339                 throw new InvalidOperationException(String.Format(
340                     "The binary operator AddChecked is not defined for the types '{0}' and '{1}'.", left.type, right.type));
341             
342             Type retType = method.ReturnType;
343
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.
347
348             return new BinaryExpression(ExpressionType.AddChecked, left, right, method, retType);
349         }
350
351         public static BinaryExpression AddChecked(Expression left, Expression right)
352         {
353             return AddChecked(left, right, null);
354         }
355         #endregion
356
357         #region And
358         public static BinaryExpression And(Expression left, Expression right, MethodInfo method)
359         {
360             if (left == null)
361                 throw new ArgumentNullException ("left");
362             if (right == null)
363                 throw new ArgumentNullException ("right");
364
365             if (method != null)
366                 return new BinaryExpression(ExpressionType.And, left, right, method, method.ReturnType);
367             
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);
372
373             // Else we try for a user-defined operator.
374             return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.And, "op_BitwiseAnd", left, right);
375         }
376
377         public static BinaryExpression And(Expression left, Expression right)
378         {
379             return And(left, right, null);
380         }
381         #endregion
382         
383         #region AndAlso
384         public static BinaryExpression AndAlso(Expression left, Expression right, MethodInfo method)
385         {
386             if (left == null)
387                 throw new ArgumentNullException ("left");
388             if (right == null)
389                 throw new ArgumentNullException ("right");
390
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);
395
396             // Else we must validate the method to make sure it has companion "true" and "false" operators.
397             if (method == null)
398                 method = GetUserDefinedBinaryOperator (left.type, right.type, "op_BitwiseAnd");
399             if (method == null)
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);
403             
404             return new BinaryExpression(ExpressionType.AndAlso, left, right, method, method.ReturnType);
405         }
406
407         public static BinaryExpression AndAlso(Expression left, Expression right)
408         {
409             return AndAlso(left, right, null);
410         }
411         #endregion
412         
413         #region ArrayIndex
414         public static BinaryExpression ArrayIndex(Expression array, Expression index)
415         {
416             if (array == null)
417                 throw new ArgumentNullException ("array");
418             if (index == null)
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");
424
425             return new BinaryExpression(ExpressionType.ArrayIndex, array, index, array.type.GetElementType());
426         }
427
428         public static MethodCallExpression ArrayIndex(Expression array, params Expression[] indexes)
429         {
430             return ArrayIndex(array, (IEnumerable<Expression>)indexes);
431         }
432
433         public static MethodCallExpression ArrayIndex(Expression array, IEnumerable<Expression> indexes)
434         {
435             if (array == null)
436                 throw new ArgumentNullException ("array");
437             if (indexes == null)
438                 throw new ArgumentNullException ("indexes");
439             if (!array.type.IsArray)
440                 throw new ArgumentException ("Argument must be array");
441
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.)
444             
445             Type[] types = (Type[])Array.CreateInstance(typeof(Type), array.type.GetArrayRank());
446             Expression[] indexesList = new Expression[array.type.GetArrayRank()];
447             
448             int rank = 0;
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");
454
455                 types[rank] = index.type;
456                 indexesList[rank] = index;
457                 rank += 1;
458             }
459                 
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.
463
464             MethodInfo method = array.type.GetMethod("Get",
465                 BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, types, null);
466
467             // This should not happen, but we check anyway.
468             if (method == null)
469                 throw new InvalidOperationException(String.Format(
470                     "The method Get(...) is not defined for the type '{0}'.", array.type));
471     
472             return new MethodCallExpression(ExpressionType.Call, method, array, new ReadOnlyCollection<Expression>(indexesList));
473         }
474         #endregion
475         
476         #region ArrayLength
477         public static UnaryExpression ArrayLength(Expression array)
478         {
479             if (array == null)
480                 throw new ArgumentNullException ("array");
481             if (!array.type.IsArray)
482                 throw new ArgumentException ("Argument must be array");
483
484             return new UnaryExpression(ExpressionType.ArrayLength, array, typeof(Int32));        
485         }
486         #endregion
487         
488         #region Bind
489         public static MemberAssignment Bind (MemberInfo member, Expression expression)
490         {
491             if (member == null)
492                 throw new ArgumentNullException ("member");
493             if (expression == null)
494                 throw new ArgumentNullException ("expression");
495                 
496             Type memberType;
497             ValidateSettableFieldOrPropertyMember(member, out memberType);            
498         
499             return new MemberAssignment(member, expression);
500         }
501
502         public static MemberAssignment Bind (MethodInfo propertyAccessor, Expression expression)
503         {
504             if (propertyAccessor == null)
505                 throw new ArgumentNullException ("propertyAccessor");
506             if (expression == null)
507                 throw new ArgumentNullException ("expression");
508
509             return new MemberAssignment(GetProperty(propertyAccessor), expression);        
510         }
511         #endregion
512         
513         #region Call
514         public static MethodCallExpression Call(Expression instance, MethodInfo method)
515         {
516             if (method == null)
517                 throw new ArgumentNullException("method");
518             if (instance == null && !method.IsStatic)
519                 throw new ArgumentNullException("instance");
520                 
521             return Call(instance, method, (Expression[])null);
522         }
523
524         public static MethodCallExpression Call(Expression instance, MethodInfo method, params Expression[] arguments)
525         {
526             return Call(instance, method, (IEnumerable<Expression>)arguments);
527         }
528
529         public static MethodCallExpression Call(Expression instance, MethodInfo method, IEnumerable<Expression> arguments)
530         {
531             if (method == null)
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");
537                 
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();
544
545             ReadOnlyCollection<Expression> roArgs = Enumerable.ToReadOnlyCollection<Expression>(arguments);
546
547             ParameterInfo[] pars = method.GetParameters();
548             if (Enumerable.Count<Expression>(arguments) != pars.Length)
549                 throw new ArgumentException();
550
551             if (pars.Length > 0)
552             {
553                 //TODO: validate the parameters against the arguments...
554             }
555
556             return new MethodCallExpression(ExpressionType.Call, method, instance, roArgs);
557         }
558
559         public static MethodCallExpression Call (Expression instance, string methodName, Type [] typeArguments, params Expression [] arguments)
560         {
561             if (instance == null)
562                 throw new ArgumentNullException("instance");
563             if (arguments == null)
564                 throw new ArgumentNullException("arguments");
565
566             return Call (null, FindMethod (instance.type, methodName, typeArguments, arguments,
567                     BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance),
568                 (IEnumerable<Expression>)arguments);        
569         }
570         
571         public static MethodCallExpression Call(MethodInfo method, params Expression[] arguments)
572         {
573             return Call(null, method, (IEnumerable<Expression>)arguments);
574         }
575
576         public static MethodCallExpression Call (Type type, string methodName, Type [] typeArguments, params Expression [] arguments)
577         {
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?
580             //if (type == null)
581             //    throw new ArgumentNullException("type");
582             
583             if (methodName == null)
584                 throw new ArgumentNullException("methodName");
585             if (arguments == null)
586                 throw new ArgumentNullException("arguments");
587
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);
592         }
593         #endregion
594
595         // NOTE: CallVirtual is not implemented because it is already marked as Obsolete by MS.
596         
597         public static ConditionalExpression Condition(Expression test, Expression ifTrue, Expression ifFalse)
598         {
599             if (test == null)
600                 throw new ArgumentNullException("test");
601             if (ifTrue == null)
602                 throw new ArgumentNullException("ifTrue");
603             if (ifFalse == null)
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();
609
610             return new ConditionalExpression(test, ifTrue, ifFalse, ifTrue.type);
611         }
612
613         public static ConstantExpression Constant(object value, Type type)
614         {
615             if (type == null)
616                 throw new ArgumentNullException("type");
617             if (value == null && !IsNullableType(type))
618                 throw new ArgumentException("Argument types do not match");
619
620             return new ConstantExpression(value, type);
621         }
622
623         public static ConstantExpression Constant(object value)
624         {
625             if (value != null)
626                 return new ConstantExpression(value, value.GetType());
627             else
628                 return new ConstantExpression(null, typeof(object));
629         }
630
631         #region Divide
632         public static BinaryExpression Divide(Expression left, Expression right, MethodInfo method)
633         {
634             if (left == null)
635                 throw new ArgumentNullException ("left");
636             if (right == null)
637                 throw new ArgumentNullException ("right");
638
639             if (method != null)
640                 return new BinaryExpression(ExpressionType.Divide, left, right, method, method.ReturnType);
641             
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);
646
647             // Else we try for a user-defined operator.
648             return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Divide, "op_Division", left, right);
649         }
650
651         public static BinaryExpression Divide(Expression left, Expression right)
652         {
653             return Divide(left, right, null);
654         }
655         #endregion
656         
657         #region ExclusiveOr
658         public static BinaryExpression ExclusiveOr (Expression left, Expression right, System.Reflection.MethodInfo method)
659         {
660             if (left == null)
661                 throw new ArgumentNullException ("left");
662             if (right == null)
663                 throw new ArgumentNullException ("right");
664
665             if (method != null)
666                 return new BinaryExpression(ExpressionType.ExclusiveOr, left, right, method, method.ReturnType);
667             
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);
672
673             // Else we try for a user-defined operator.
674             return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.ExclusiveOr, "op_ExclusiveOr", left, right);
675         }
676         
677         public static BinaryExpression ExclusiveOr (Expression left, Expression right)
678         {
679             return ExclusiveOr (left, right, null);
680         }
681         #endregion
682         
683         public static MemberExpression Field(Expression expression, FieldInfo field)
684         {
685             if (field == null)
686                 throw new ArgumentNullException("field");
687
688             return new MemberExpression(expression, field, field.FieldType);
689         }
690
691         public static MemberExpression Field(Expression expression, string fieldName)
692         {
693             if (expression == null)
694                 throw new ArgumentNullException("expression");
695
696             FieldInfo field = expression.Type.GetField(fieldName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
697             if (field == null)
698                 throw new ArgumentException();
699
700             return Field(expression, field);
701         }
702
703         public static FuncletExpression Funclet(Funclet funclet, Type type)
704         {
705             if (funclet == null)
706                 throw new ArgumentNullException("funclet");
707             if (type == null)
708                 throw new ArgumentNullException("type");
709
710             return new FuncletExpression(funclet, type);
711         }
712
713         public static Type GetFuncType(params Type[] typeArgs)
714         {
715             if (typeArgs == null)
716                 throw new ArgumentNullException("typeArgs");
717             if (typeArgs.Length > 5)
718                 throw new ArgumentException();
719
720             return typeof(Func<,,,,>).MakeGenericType(typeArgs);
721         }
722
723         #region LeftShift
724         public static BinaryExpression LeftShift (Expression left, Expression right, MethodInfo method)
725         {
726             if (left == null)
727                 throw new ArgumentNullException ("left");
728             if (right == null)
729                 throw new ArgumentNullException ("right");
730
731             if (method != null)
732                 return new BinaryExpression(ExpressionType.LeftShift, left, right, method, method.ReturnType);
733             
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);
738
739             // Else we try for a user-defined operator.
740             return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.LeftShift, "op_LeftShift", left, right);
741         }
742
743         public static BinaryExpression LeftShift (Expression left, Expression right)
744         {
745             return LeftShift (left, right, null);
746         }
747         #endregion
748         
749         public static ListInitExpression ListInit(NewExpression newExpression, params Expression[] initializers)
750         {
751             if (initializers == null)
752                 throw new ArgumentNullException("inizializers");
753
754             return ListInit(newExpression, Enumerable.ToReadOnlyCollection<Expression>(initializers));
755         }
756
757         public static ListInitExpression ListInit(NewExpression newExpression, IEnumerable<Expression> initializers)
758         {
759             if (newExpression == null)
760                 throw new ArgumentNullException("newExpression");
761             if (initializers == null)
762                 throw new ArgumentNullException("inizializers");
763
764             return new ListInitExpression(newExpression, Enumerable.ToReadOnlyCollection<Expression>(initializers));
765         }
766
767         public static MemberInitExpression MemberInit(NewExpression newExpression, IEnumerable<MemberBinding> bindings)
768         {
769             if (newExpression == null)
770                 throw new ArgumentNullException("newExpression");
771
772             if (bindings == null)
773                 throw new ArgumentNullException("bindings");
774
775             return new MemberInitExpression(newExpression, Enumerable.ToReadOnlyCollection<MemberBinding>(bindings));
776         }
777
778         #region Modulo
779         public static BinaryExpression Modulo (Expression left, Expression right, MethodInfo method)
780         {
781             if (left == null)
782                 throw new ArgumentNullException ("left");
783             if (right == null)
784                 throw new ArgumentNullException ("right");
785
786             if (method != null)
787                 return new BinaryExpression(ExpressionType.Modulo, left, right, method, method.ReturnType);
788             
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);
793
794             // Else we try for a user-defined operator.
795             return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Modulo, "op_Modulus", left, right);
796         
797         }
798         
799         public static BinaryExpression Modulo (Expression left, Expression right)
800         {
801             return Modulo (left, right, null);        
802         }
803         #endregion
804         
805         #region Multiply
806         public static BinaryExpression Multiply (Expression left, Expression right, MethodInfo method)
807         {
808             if (left == null)
809                 throw new ArgumentNullException ("left");
810             if (right == null)
811                 throw new ArgumentNullException ("right");
812
813             if (method != null)
814                 return new BinaryExpression(ExpressionType.Multiply, left, right, method, method.ReturnType);
815             
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);
820
821             // Else we try for a user-defined operator.
822             return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Multiply, "op_Multiply", left, right);
823         
824         }
825         
826         public static BinaryExpression Multiply (Expression left, Expression right)
827         {
828             return Multiply (left, right, null);
829         }
830         #endregion
831         
832         #region MultiplyChecked
833         public static BinaryExpression MultiplyChecked (Expression left, Expression right, MethodInfo method)
834         {
835             if (left == null)
836                 throw new ArgumentNullException ("left");
837             if (right == null)
838                 throw new ArgumentNullException ("right");
839
840             if (method != null)
841                 return new BinaryExpression(ExpressionType.MultiplyChecked, left, right, method, method.ReturnType);
842
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);
847
848             method = GetUserDefinedBinaryOperator (left.type, right.type, "op_Multiply");
849             if (method == null)
850                 throw new InvalidOperationException(String.Format(
851                     "The binary operator MultiplyChecked is not defined for the types '{0}' and '{1}'.", left.type, right.type));
852             
853             Type retType = method.ReturnType;
854
855             return new BinaryExpression(ExpressionType.MultiplyChecked, left, right, method, retType);
856         }
857         
858         public static BinaryExpression MultiplyChecked (Expression left, Expression right)
859         {
860             return MultiplyChecked(left, right, null);
861         }
862         #endregion
863         
864         public static MemberExpression Property(Expression expression, PropertyInfo property)
865         {
866             if (property == null)
867                 throw new ArgumentNullException("property");
868
869             MethodInfo getMethod = property.GetGetMethod(true);
870             if (getMethod == null)
871                 throw new ArgumentException(); // to access the property we need to have
872                                                // a get method...
873
874             return new MemberExpression(expression, property, property.PropertyType);
875         }
876         
877         #region Or
878         public static BinaryExpression Or (Expression left, Expression right, MethodInfo method)
879         {
880             if (left == null)
881                 throw new ArgumentNullException ("left");
882             if (right == null)
883                 throw new ArgumentNullException ("right");
884
885             if (method != null)
886                 return new BinaryExpression(ExpressionType.Or, left, right, method, method.ReturnType);
887             
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);
892
893             // Else we try for a user-defined operator.
894             return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Or, "op_BitwiseOr", left, right);
895         
896         }
897
898         public static BinaryExpression Or (Expression left, Expression right)
899         {
900             return Or (left, right, null);
901         }
902         #endregion
903         
904         #region OrElse
905         public static BinaryExpression OrElse (Expression left, Expression right, MethodInfo method)
906         {
907             if (left == null)
908                 throw new ArgumentNullException ("left");
909             if (right == null)
910                 throw new ArgumentNullException ("right");
911
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);
916
917             // Else we must validate the method to make sure it has companion "true" and "false" operators.
918             if (method == null)
919                 method = GetUserDefinedBinaryOperator (left.type, right.type, "op_BitwiseOr");
920             if (method == null)
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);
924             
925             return new BinaryExpression(ExpressionType.OrElse, left, right, method, method.ReturnType);
926         }
927         
928         public static BinaryExpression OrElse (Expression left, Expression right)
929         {
930             return OrElse(left, right, null);
931         }
932         #endregion
933         
934         public static UnaryExpression Quote(Expression expression)
935         {
936             if (expression == null)
937                 throw new ArgumentNullException("expression");
938
939             return new UnaryExpression(ExpressionType.Quote, expression, expression.GetType());
940         }
941
942
943         public static MemberExpression Property(Expression expression, string propertyName)
944         {
945             if (expression == null)
946                 throw new ArgumentNullException("expression");
947
948             PropertyInfo property = expression.Type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
949
950             if (property == null)
951                 throw new ArgumentException();
952
953             return Property(expression, property);
954         }
955
956         public static MemberExpression PropertyOrField(Expression expression, string propertyOrFieldName)
957         {
958             if (expression == null)
959                 throw new ArgumentNullException("expression");
960
961             PropertyInfo property = expression.Type.GetProperty(propertyOrFieldName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
962             if (property != null)
963                 return Property(expression, property);
964
965             FieldInfo field = expression.Type.GetField(propertyOrFieldName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
966             if (field != null)
967                 return Field(expression, field);
968                 
969             //TODO: should we return <null> here?
970             // the name is not defined in the Type of the expression given...
971             throw new ArgumentException();
972         }
973
974         #region RightShift
975         public static BinaryExpression RightShift (Expression left, Expression right, MethodInfo method)
976         {
977             if (left == null)
978                 throw new ArgumentNullException ("left");
979             if (right == null)
980                 throw new ArgumentNullException ("right");
981
982             if (method != null)
983                 return new BinaryExpression(ExpressionType.RightShift, left, right, method, method.ReturnType);
984             
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);
989
990             // Else we try for a user-defined operator.
991             return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.RightShift, "op_RightShift", left, right);
992         }
993
994         public static BinaryExpression RightShift (Expression left, Expression right)
995         {
996             return RightShift (left, right, null);
997         }
998         #endregion
999
1000         #region Subtract
1001         public static BinaryExpression Subtract (Expression left, Expression right, MethodInfo method)
1002         {
1003             if (left == null)
1004                 throw new ArgumentNullException ("left");
1005             if (right == null)
1006                 throw new ArgumentNullException ("right");
1007
1008             if (method != null)
1009                 return new BinaryExpression(ExpressionType.Subtract, left, right, method, method.ReturnType);
1010             
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);
1015
1016             // Else we try for a user-defined operator.
1017             return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Subtract, "op_Subtraction", left, right);        
1018         }
1019         
1020         public static BinaryExpression Subtract (Expression left, Expression right)
1021         {
1022             return Subtract (left, right, null);        
1023         }
1024         #endregion
1025         
1026         #region SubtractChecked
1027         public static BinaryExpression SubtractChecked (Expression left, Expression right, MethodInfo method)
1028         {
1029             if (left == null)
1030                 throw new ArgumentNullException ("left");
1031             if (right == null)
1032                 throw new ArgumentNullException ("right");
1033
1034             if (method != null)
1035                 return new BinaryExpression(ExpressionType.SubtractChecked, left, right, method, method.ReturnType);
1036
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);
1041
1042             method = GetUserDefinedBinaryOperator (left.type, right.type, "op_Subtraction");
1043             if (method == null)
1044                 throw new InvalidOperationException(String.Format(
1045                     "The binary operator AddChecked is not defined for the types '{0}' and '{1}'.", left.type, right.type));
1046             
1047             Type retType = method.ReturnType;
1048
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.
1052
1053             return new BinaryExpression(ExpressionType.SubtractChecked, left, right, method, retType);
1054         }
1055         
1056         public static BinaryExpression SubtractChecked (Expression left, Expression right)
1057         {
1058             return SubtractChecked (left, right, null);
1059         }
1060         #endregion
1061
1062         #region TypeAs
1063         public static UnaryExpression TypeAs(Expression expression, Type type)
1064         {
1065             if (expression == null)
1066                 throw new ArgumentNullException("expression");
1067             if (type == null)
1068                 throw new ArgumentNullException("type");
1069
1070             return new UnaryExpression(ExpressionType.TypeAs, expression, type);
1071         }
1072         #endregion
1073
1074         #region TypeIs
1075         public static TypeBinaryExpression TypeIs(Expression expression, Type type)
1076         {
1077             if (expression == null)
1078                 throw new ArgumentNullException("expression");
1079             if (type == null)
1080                 throw new ArgumentNullException("type"); 
1081             
1082             return new TypeBinaryExpression(ExpressionType.TypeIs, expression, type, typeof(bool));
1083         }
1084         #endregion
1085     }
1086 }