Expression.cs 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061
  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 ([email protected])
  21. // Antonello Provenzano <[email protected]>
  22. // Federico Di Gregorio <[email protected]>
  23. using System.Collections.Generic;
  24. using System.Collections.ObjectModel;
  25. using System.Reflection;
  26. using System.Text;
  27. namespace System.Linq.Expressions
  28. {
  29. public abstract class Expression
  30. {
  31. #region .ctor
  32. protected Expression (ExpressionType nodeType, Type type)
  33. {
  34. this.nodeType = nodeType;
  35. this.type = type;
  36. }
  37. #endregion
  38. #region Fields
  39. private Type type;
  40. private ExpressionType nodeType;
  41. #endregion
  42. #region Properties
  43. public Type Type {
  44. get { return type; }
  45. }
  46. public ExpressionType NodeType {
  47. get { return nodeType; }
  48. }
  49. #endregion
  50. #region Internal methods
  51. internal virtual void BuildString (StringBuilder builder)
  52. {
  53. builder.Append ("[").Append (nodeType).Append ("]");
  54. }
  55. internal static Type GetNonNullableType(Type type)
  56. {
  57. // The Nullable<> class takes a single generic type so we can directly return
  58. // the first element of the array (if the type is nullable.)
  59. if (IsNullableType (type))
  60. return type.GetGenericArguments ()[0];
  61. else
  62. return type;
  63. }
  64. internal static bool IsNullableType(Type type)
  65. {
  66. if (type == null)
  67. throw new ArgumentNullException("type");
  68. if (type.IsGenericType) {
  69. Type genType = type.GetGenericTypeDefinition();
  70. return typeof(Nullable<>).IsAssignableFrom(genType);
  71. }
  72. return false;
  73. }
  74. #endregion
  75. #region Private support methods
  76. private static int IsWhat(Type type)
  77. {
  78. // This method return a "type code" that can be easily compared to a bitmask
  79. // to determine the bread type (integer, boolean, floating-point) of the given type.
  80. // It is used by the three methods below.
  81. if (IsNullableType (type))
  82. type = GetNonNullableType (type);
  83. switch (Type.GetTypeCode (type)) {
  84. case TypeCode.Byte: case TypeCode.SByte:
  85. case TypeCode.Int16: case TypeCode.UInt16:
  86. case TypeCode.Int32: case TypeCode.UInt32:
  87. case TypeCode.Int64: case TypeCode.UInt64:
  88. return 1;
  89. case TypeCode.Boolean:
  90. return 2;
  91. case TypeCode.Single:
  92. case TypeCode.Double:
  93. case TypeCode.Decimal:
  94. return 4;
  95. default:
  96. return 0;
  97. }
  98. }
  99. private static bool IsInteger (Type type)
  100. {
  101. return (IsWhat(type) & 1) != 0;
  102. }
  103. private static bool IsIntegerOrBool (Type type)
  104. {
  105. return (IsWhat(type) & 3) != 0;
  106. }
  107. private static bool IsNumeric (Type type)
  108. {
  109. return (IsWhat(type) & 5) != 0;
  110. }
  111. private const BindingFlags opBindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
  112. private static MethodInfo GetUserDefinedBinaryOperator (Type leftType, Type rightType, string name)
  113. {
  114. Type[] types = new Type[2] { leftType, rightType };
  115. MethodInfo method;
  116. method = leftType.GetMethod (name, opBindingFlags, null, types, null);
  117. if (method != null) return method;
  118. method = rightType.GetMethod (name, opBindingFlags, null, types, null);
  119. if (method != null) return method;
  120. if (method == null && IsNullableType (leftType) && IsNullableType (rightType))
  121. return GetUserDefinedBinaryOperator (GetNonNullableType (leftType), GetNonNullableType( rightType), name);
  122. return null;
  123. }
  124. private static BinaryExpression GetUserDefinedBinaryOperatorOrThrow (ExpressionType nodeType, string name,
  125. Expression left, Expression right)
  126. {
  127. MethodInfo method = GetUserDefinedBinaryOperator(left.type, right.type, name);
  128. if (method != null)
  129. return new BinaryExpression (nodeType, left, right, method, method.ReturnType);
  130. else
  131. throw new InvalidOperationException (String.Format (
  132. "The binary operator Add is not defined for the types '{0}' and '{1}'.", left.type, right.type));
  133. // Note: here the code in ExpressionUtils has a series of checks to make sure that
  134. // the method is static, that its return type is not void and that the number of
  135. // parameters is 2 and they are of the right type, but we already know that! Or not?
  136. }
  137. private static MethodInfo FindMethod (Type type, string methodName, Type [] typeArgs, Expression [] args, BindingFlags flags)
  138. {
  139. MemberInfo[] members = type.FindMembers(MemberTypes.Method, flags,
  140. delegate(MemberInfo mi, object obj) { return mi.Name == (String)obj; },
  141. methodName);
  142. if (members.Length == 0)
  143. throw new InvalidOperationException (String.Format (
  144. "No method '{0}' exists on type '{1}'.", methodName, type.FullName));
  145. MethodInfo methodDefinition = null;
  146. MethodInfo method = null;
  147. int methodCount = 1;
  148. foreach (MemberInfo member in members) {
  149. MethodInfo mi = (MethodInfo)member;
  150. if (mi.IsGenericMethodDefinition) {
  151. // If the generic method definition matches we save it away to be able to make the
  152. // correct closed method later on.
  153. Type[] genericArgs = mi.GetGenericArguments();
  154. if (genericArgs.Length != typeArgs.Length) goto next;
  155. methodDefinition = mi;
  156. goto next;
  157. }
  158. // If there is a discrepancy between method's generic types and the given types or if
  159. // the method is open we simply discard it and go on.
  160. if ((mi.IsGenericMethod && (typeArgs == null || mi.ContainsGenericParameters))
  161. || (!mi.IsGenericMethod && typeArgs != null))
  162. goto next;
  163. // If the method is a closed generic we try to match the generic types.
  164. if (mi.IsGenericMethod) {
  165. Type[] genericArgs = mi.GetGenericArguments();
  166. if (genericArgs.Length != typeArgs.Length) goto next;
  167. for (int i=0 ; i < genericArgs.Length ; i++)
  168. if (genericArgs[i] != typeArgs[i]) goto next;
  169. }
  170. // Finally we test for the method's parameters.
  171. ParameterInfo[] parameters = mi.GetParameters ();
  172. if (parameters.Length != args.Length) goto next;
  173. for (int i=0 ; i < parameters.Length ; i++)
  174. if (parameters[i].ParameterType != args[i].type) goto next;
  175. method = mi;
  176. break;
  177. next:
  178. continue;
  179. }
  180. if (method != null)
  181. return method;
  182. else
  183. throw new InvalidOperationException(String.Format(
  184. "No method '{0}' on type '{1}' is compatible with the supplied arguments.", methodName, type.FullName));
  185. }
  186. private static PropertyInfo GetProperty (MethodInfo mi)
  187. {
  188. // If the method has the hidebysig and specialname attributes it can be a property accessor;
  189. // if that's the case we try to extract the type of the property and then we use it and the
  190. // property name (derived from the method name) to find the right ProprtyInfo.
  191. if (mi.IsHideBySig && mi.IsSpecialName) {
  192. Type propertyType = null;
  193. if (mi.Name.StartsWith("set_")) {
  194. ParameterInfo[] parameters = mi.GetParameters();
  195. if (parameters.Length == 1)
  196. propertyType = parameters[0].ParameterType;
  197. }
  198. else if (mi.Name.StartsWith("get_")) {
  199. propertyType = mi.ReturnType;
  200. }
  201. if (propertyType != null) {
  202. PropertyInfo pi = mi.DeclaringType.GetProperty(mi.Name.Substring(4),
  203. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance,
  204. null, propertyType, new Type[0], null);
  205. if (pi != null) return pi;
  206. }
  207. }
  208. throw new ArgumentException (String.Format(
  209. "The method '{0}.{1}' is not a property accessor", mi.DeclaringType.FullName, mi.Name));
  210. }
  211. private static void ValidateUserDefinedConditionalLogicOperator (ExpressionType nodeType, Type left, Type right, MethodInfo method)
  212. {
  213. // Conditional logic need the "definitely true" and "definitely false" operators.
  214. Type[] types = new Type[1] { left };
  215. MethodInfo opTrue = left.GetMethod ("op_True", opBindingFlags, null, types, null);
  216. MethodInfo opFalse = left.GetMethod ("op_False", opBindingFlags, null, types, null);
  217. if (opTrue == null || opFalse == null)
  218. throw new ArgumentException (String.Format (
  219. "The user-defined operator method '{0}' for operator '{1}' must have associated boolean True and False operators.",
  220. method.Name, nodeType));
  221. }
  222. private static void ValidateSettableFieldOrPropertyMember (MemberInfo member, out Type memberType)
  223. {
  224. if (member.MemberType == MemberTypes.Field) {
  225. memberType = typeof (FieldInfo);
  226. }
  227. else if (member.MemberType == MemberTypes.Property) {
  228. PropertyInfo pi = (PropertyInfo)member;
  229. if (!pi.CanWrite)
  230. throw new ArgumentException (String.Format ("The property '{0}' has no 'set' accessor", pi));
  231. memberType = typeof (PropertyInfo);
  232. }
  233. else {
  234. throw new ArgumentException ("Argument must be either a FieldInfo or PropertyInfo");
  235. }
  236. }
  237. #endregion
  238. #region ToString
  239. public override string ToString()
  240. {
  241. StringBuilder builder = new StringBuilder ();
  242. BuildString (builder);
  243. return builder.ToString ();
  244. }
  245. #endregion
  246. #region Add
  247. public static BinaryExpression Add(Expression left, Expression right, MethodInfo method)
  248. {
  249. if (left == null)
  250. throw new ArgumentNullException ("left");
  251. if (right == null)
  252. throw new ArgumentNullException ("right");
  253. if (method != null)
  254. return new BinaryExpression(ExpressionType.Add, left, right, method, method.ReturnType);
  255. // Since both the expressions define the same numeric type we don't have
  256. // to look for the "op_Addition" method.
  257. if (left.type == right.type && IsNumeric (left.type))
  258. return new BinaryExpression(ExpressionType.Add, left, right, left.type);
  259. // Else we try for a user-defined operator.
  260. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Add, "op_Addition", left, right);
  261. }
  262. public static BinaryExpression Add(Expression left, Expression right)
  263. {
  264. return Add(left, right, null);
  265. }
  266. #endregion
  267. #region AddChecked
  268. public static BinaryExpression AddChecked(Expression left, Expression right, MethodInfo method)
  269. {
  270. if (left == null)
  271. throw new ArgumentNullException ("left");
  272. if (right == null)
  273. throw new ArgumentNullException ("right");
  274. if (method != null)
  275. return new BinaryExpression(ExpressionType.AddChecked, left, right, method, method.ReturnType);
  276. // Since both the expressions define the same numeric type we don't have
  277. // to look for the "op_Addition" method.
  278. if (left.type == right.type && IsNumeric (left.type))
  279. return new BinaryExpression(ExpressionType.AddChecked, left, right, left.type);
  280. method = GetUserDefinedBinaryOperator (left.type, right.type, "op_Addition");
  281. if (method == null)
  282. throw new InvalidOperationException(String.Format(
  283. "The binary operator AddChecked is not defined for the types '{0}' and '{1}'.", left.type, right.type));
  284. Type retType = method.ReturnType;
  285. // Note: here the code did some very strange checks for bool (but note that bool does
  286. // not define an addition operator) and created nullables for value types (but the new
  287. // MS code does not do that). All that has been removed.
  288. return new BinaryExpression(ExpressionType.AddChecked, left, right, method, retType);
  289. }
  290. public static BinaryExpression AddChecked(Expression left, Expression right)
  291. {
  292. return AddChecked(left, right, null);
  293. }
  294. #endregion
  295. #region And
  296. public static BinaryExpression And(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. if (method != null)
  303. return new BinaryExpression(ExpressionType.And, left, right, method, method.ReturnType);
  304. // Since both the expressions define the same integer or boolean type we don't have
  305. // to look for the "op_BitwiseAnd" method.
  306. if (left.type == right.type && IsIntegerOrBool (left.type))
  307. return new BinaryExpression(ExpressionType.And, left, right, left.type);
  308. // Else we try for a user-defined operator.
  309. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.And, "op_BitwiseAnd", left, right);
  310. }
  311. public static BinaryExpression And(Expression left, Expression right)
  312. {
  313. return And(left, right, null);
  314. }
  315. #endregion
  316. #region AndAlso
  317. public static BinaryExpression AndAlso(Expression left, Expression right, MethodInfo method)
  318. {
  319. if (left == null)
  320. throw new ArgumentNullException ("left");
  321. if (right == null)
  322. throw new ArgumentNullException ("right");
  323. // Since both the expressions define the same boolean type we don't have
  324. // to look for the "op_BitwiseAnd" method.
  325. if (left.type == right.type && left.type == typeof(bool))
  326. return new BinaryExpression(ExpressionType.AndAlso, left, right, left.type);
  327. // Else we must validate the method to make sure it has companion "true" and "false" operators.
  328. if (method == null)
  329. method = GetUserDefinedBinaryOperator (left.type, right.type, "op_BitwiseAnd");
  330. if (method == null)
  331. throw new InvalidOperationException(String.Format(
  332. "The binary operator AndAlso is not defined for the types '{0}' and '{1}'.", left.type, right.type));
  333. ValidateUserDefinedConditionalLogicOperator(ExpressionType.AndAlso, left.type, right.type, method);
  334. return new BinaryExpression(ExpressionType.AndAlso, left, right, method, method.ReturnType);
  335. }
  336. public static BinaryExpression AndAlso(Expression left, Expression right)
  337. {
  338. return AndAlso(left, right, null);
  339. }
  340. #endregion
  341. #region ArrayIndex
  342. public static BinaryExpression ArrayIndex(Expression array, Expression index)
  343. {
  344. if (array == null)
  345. throw new ArgumentNullException ("array");
  346. if (index == null)
  347. throw new ArgumentNullException ("index");
  348. if (!array.type.IsArray)
  349. throw new ArgumentException ("Argument must be array");
  350. if (index.type != typeof(int))
  351. throw new ArgumentException ("Argument for array index must be of type Int32");
  352. return new BinaryExpression(ExpressionType.ArrayIndex, array, index, array.type.GetElementType());
  353. }
  354. public static MethodCallExpression ArrayIndex(Expression array, params Expression[] indexes)
  355. {
  356. return ArrayIndex(array, (IEnumerable<Expression>)indexes);
  357. }
  358. public static MethodCallExpression ArrayIndex(Expression array, IEnumerable<Expression> indexes)
  359. {
  360. if (array == null)
  361. throw new ArgumentNullException ("array");
  362. if (indexes == null)
  363. throw new ArgumentNullException ("indexes");
  364. if (!array.type.IsArray)
  365. throw new ArgumentException ("Argument must be array");
  366. // We'll need an array of typeof(Type) elements long as the array's rank later
  367. // and also a generic List to hold the indexes (ReadOnlyCollection wants that.)
  368. Type[] types = (Type[])Array.CreateInstance(typeof(Type), array.type.GetArrayRank());
  369. Expression[] indexesList = new Expression[array.type.GetArrayRank()];
  370. int rank = 0;
  371. foreach (Expression index in indexes) {
  372. if (index.type != typeof(int))
  373. throw new ArgumentException ("Argument for array index must be of type Int32");
  374. if (rank == array.type.GetArrayRank())
  375. throw new ArgumentException ("Incorrect number of indexes");
  376. types[rank] = index.type;
  377. indexesList[rank] = index;
  378. rank += 1;
  379. }
  380. // If the array's rank is equalto the number of given indexes we can go on and
  381. // look for a Get(Int32, ...) method with "rank" parameters to generate the
  382. // MethodCallExpression.
  383. MethodInfo method = array.type.GetMethod("Get",
  384. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, types, null);
  385. // This should not happen, but we check anyway.
  386. if (method == null)
  387. throw new InvalidOperationException(String.Format(
  388. "The method Get(...) is not defined for the type '{0}'.", array.type));
  389. return new MethodCallExpression(ExpressionType.Call, method, array, new ReadOnlyCollection<Expression>(indexesList));
  390. }
  391. #endregion
  392. #region ArrayLength
  393. public static UnaryExpression ArrayLength(Expression array)
  394. {
  395. if (array == null)
  396. throw new ArgumentNullException ("array");
  397. if (!array.type.IsArray)
  398. throw new ArgumentException ("Argument must be array");
  399. return new UnaryExpression(ExpressionType.ArrayLength, array, typeof(Int32));
  400. }
  401. #endregion
  402. #region Bind
  403. public static MemberAssignment Bind (MemberInfo member, Expression expression)
  404. {
  405. if (member == null)
  406. throw new ArgumentNullException ("member");
  407. if (expression == null)
  408. throw new ArgumentNullException ("expression");
  409. Type memberType;
  410. ValidateSettableFieldOrPropertyMember(member, out memberType);
  411. return new MemberAssignment(member, expression);
  412. }
  413. public static MemberAssignment Bind (MethodInfo propertyAccessor, Expression expression)
  414. {
  415. if (propertyAccessor == null)
  416. throw new ArgumentNullException ("propertyAccessor");
  417. if (expression == null)
  418. throw new ArgumentNullException ("expression");
  419. return new MemberAssignment(GetProperty(propertyAccessor), expression);
  420. }
  421. #endregion
  422. #region Call
  423. public static MethodCallExpression Call(Expression instance, MethodInfo method)
  424. {
  425. if (method == null)
  426. throw new ArgumentNullException("method");
  427. if (instance == null && !method.IsStatic)
  428. throw new ArgumentNullException("instance");
  429. return Call(instance, method, (Expression[])null);
  430. }
  431. public static MethodCallExpression Call(Expression instance, MethodInfo method, params Expression[] arguments)
  432. {
  433. return Call(instance, method, (IEnumerable<Expression>)arguments);
  434. }
  435. public static MethodCallExpression Call(Expression instance, MethodInfo method, IEnumerable<Expression> arguments)
  436. {
  437. if (method == null)
  438. throw new ArgumentNullException("method");
  439. if (arguments == null)
  440. throw new ArgumentNullException("arguments");
  441. if (instance == null && !method.IsStatic)
  442. throw new ArgumentNullException("instance");
  443. if (method.IsGenericMethodDefinition)
  444. throw new ArgumentException();
  445. if (method.ContainsGenericParameters)
  446. throw new ArgumentException();
  447. if (instance != null && !instance.type.IsAssignableFrom(method.DeclaringType))
  448. throw new ArgumentException();
  449. ReadOnlyCollection<Expression> roArgs = Enumerable.ToReadOnlyCollection<Expression>(arguments);
  450. ParameterInfo[] pars = method.GetParameters();
  451. if (Enumerable.Count<Expression>(arguments) != pars.Length)
  452. throw new ArgumentException();
  453. if (pars.Length > 0)
  454. {
  455. //TODO: validate the parameters against the arguments...
  456. }
  457. return new MethodCallExpression(ExpressionType.Call, method, instance, roArgs);
  458. }
  459. public static MethodCallExpression Call (Expression instance, string methodName, Type [] typeArguments, params Expression [] arguments)
  460. {
  461. if (instance == null)
  462. throw new ArgumentNullException("instance");
  463. if (arguments == null)
  464. throw new ArgumentNullException("arguments");
  465. return Call (null, FindMethod (instance.type, methodName, typeArguments, arguments,
  466. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance),
  467. (IEnumerable<Expression>)arguments);
  468. }
  469. public static MethodCallExpression Call(MethodInfo method, params Expression[] arguments)
  470. {
  471. return Call(null, method, (IEnumerable<Expression>)arguments);
  472. }
  473. public static MethodCallExpression Call (Type type, string methodName, Type [] typeArguments, params Expression [] arguments)
  474. {
  475. // FIXME: MS implementation does not check for type here and simply lets FindMethod() raise
  476. // a NullReferenceException. Shall we do the same or raise the correct exception here?
  477. //if (type == null)
  478. // throw new ArgumentNullException("type");
  479. if (methodName == null)
  480. throw new ArgumentNullException("methodName");
  481. if (arguments == null)
  482. throw new ArgumentNullException("arguments");
  483. // Note that we're looking for static methods only because this version of Call() doesn't take an instance.
  484. return Call (null, FindMethod (type, methodName, typeArguments, arguments,
  485. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static),
  486. (IEnumerable<Expression>)arguments);
  487. }
  488. #endregion
  489. // NOTE: CallVirtual is not implemented because it is already marked as Obsolete by MS.
  490. public static ConditionalExpression Condition(Expression test, Expression ifTrue, Expression ifFalse)
  491. {
  492. if (test == null)
  493. throw new ArgumentNullException("test");
  494. if (ifTrue == null)
  495. throw new ArgumentNullException("ifTrue");
  496. if (ifFalse == null)
  497. throw new ArgumentNullException("ifFalse");
  498. if (test.type != typeof(bool))
  499. throw new ArgumentException();
  500. if (ifTrue.type != ifFalse.type)
  501. throw new ArgumentException();
  502. return new ConditionalExpression(test, ifTrue, ifFalse, ifTrue.type);
  503. }
  504. public static ConstantExpression Constant(object value, Type type)
  505. {
  506. if (type == null)
  507. throw new ArgumentNullException("type");
  508. if (value == null && !IsNullableType(type))
  509. throw new ArgumentException("Argument types do not match");
  510. return new ConstantExpression(value, type);
  511. }
  512. public static ConstantExpression Constant(object value)
  513. {
  514. if (value != null)
  515. return new ConstantExpression(value, value.GetType());
  516. else
  517. return new ConstantExpression(null, typeof(object));
  518. }
  519. #region Divide
  520. public static BinaryExpression Divide(Expression left, Expression right, MethodInfo method)
  521. {
  522. if (left == null)
  523. throw new ArgumentNullException ("left");
  524. if (right == null)
  525. throw new ArgumentNullException ("right");
  526. if (method != null)
  527. return new BinaryExpression(ExpressionType.Divide, left, right, method, method.ReturnType);
  528. // Since both the expressions define the same numeric type we don't have
  529. // to look for the "op_Addition" method.
  530. if (left.type == right.type && IsNumeric (left.type))
  531. return new BinaryExpression(ExpressionType.Divide, left, right, left.type);
  532. // Else we try for a user-defined operator.
  533. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Divide, "op_Division", left, right);
  534. }
  535. public static BinaryExpression Divide(Expression left, Expression right)
  536. {
  537. return Divide(left, right, null);
  538. }
  539. #endregion
  540. #region ExclusiveOr
  541. public static BinaryExpression ExclusiveOr (Expression left, Expression right, System.Reflection.MethodInfo method)
  542. {
  543. if (left == null)
  544. throw new ArgumentNullException ("left");
  545. if (right == null)
  546. throw new ArgumentNullException ("right");
  547. if (method != null)
  548. return new BinaryExpression(ExpressionType.ExclusiveOr, left, right, method, method.ReturnType);
  549. // Since both the expressions define the same integer or boolean type we don't have
  550. // to look for the "op_BitwiseAnd" method.
  551. if (left.type == right.type && IsIntegerOrBool (left.type))
  552. return new BinaryExpression(ExpressionType.ExclusiveOr, left, right, left.type);
  553. // Else we try for a user-defined operator.
  554. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.ExclusiveOr, "op_ExclusiveOr", left, right);
  555. }
  556. public static BinaryExpression ExclusiveOr (Expression left, Expression right)
  557. {
  558. return ExclusiveOr (left, right, null);
  559. }
  560. #endregion
  561. public static MemberExpression Field(Expression expression, FieldInfo field)
  562. {
  563. if (field == null)
  564. throw new ArgumentNullException("field");
  565. return new MemberExpression(expression, field, field.FieldType);
  566. }
  567. public static MemberExpression Field(Expression expression, string fieldName)
  568. {
  569. if (expression == null)
  570. throw new ArgumentNullException("expression");
  571. FieldInfo field = expression.Type.GetField(fieldName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
  572. if (field == null)
  573. throw new ArgumentException();
  574. return Field(expression, field);
  575. }
  576. public static FuncletExpression Funclet(Funclet funclet, Type type)
  577. {
  578. if (funclet == null)
  579. throw new ArgumentNullException("funclet");
  580. if (type == null)
  581. throw new ArgumentNullException("type");
  582. return new FuncletExpression(funclet, type);
  583. }
  584. public static Type GetFuncType(params Type[] typeArgs)
  585. {
  586. if (typeArgs == null)
  587. throw new ArgumentNullException("typeArgs");
  588. if (typeArgs.Length > 5)
  589. throw new ArgumentException();
  590. return typeof(Func<,,,,>).MakeGenericType(typeArgs);
  591. }
  592. public static BinaryExpression LeftShift(Expression left, Expression right, MethodInfo method)
  593. {
  594. if (left == null)
  595. throw new ArgumentNullException("left");
  596. if (right == null)
  597. throw new ArgumentNullException("right");
  598. // since the left expression is of an integer type and the right is of
  599. // an integer we don't have to look for the "op_LeftShift" method...
  600. if (ExpressionUtil.IsInteger (left.type) && right.type == typeof(int))
  601. return new BinaryExpression(ExpressionType.LeftShift, left, right, left.type);
  602. if (method == null)
  603. method = ExpressionUtil.GetOperatorMethod("op_LeftShift", left.type, right.type);
  604. // ok if even op_Division is not defined we need to throw an exception...
  605. if (method == null)
  606. throw new InvalidOperationException();
  607. return new BinaryExpression(ExpressionType.LeftShift, left, right, method, method.ReturnType);
  608. }
  609. public static BinaryExpression LeftShift(Expression left, Expression right)
  610. {
  611. return LeftShift(left, right, null);
  612. }
  613. public static ListInitExpression ListInit(NewExpression newExpression, params Expression[] initializers)
  614. {
  615. if (initializers == null)
  616. throw new ArgumentNullException("inizializers");
  617. return ListInit(newExpression, Enumerable.ToReadOnlyCollection<Expression>(initializers));
  618. }
  619. public static ListInitExpression ListInit(NewExpression newExpression, IEnumerable<Expression> initializers)
  620. {
  621. if (newExpression == null)
  622. throw new ArgumentNullException("newExpression");
  623. if (initializers == null)
  624. throw new ArgumentNullException("inizializers");
  625. return new ListInitExpression(newExpression, Enumerable.ToReadOnlyCollection<Expression>(initializers));
  626. }
  627. public static MemberInitExpression MemberInit(NewExpression newExpression, IEnumerable<MemberBinding> bindings)
  628. {
  629. if (newExpression == null)
  630. throw new ArgumentNullException("newExpression");
  631. if (bindings == null)
  632. throw new ArgumentNullException("bindings");
  633. return new MemberInitExpression(newExpression, Enumerable.ToReadOnlyCollection<MemberBinding>(bindings));
  634. }
  635. #region Modulo
  636. public static BinaryExpression Modulo (Expression left, Expression right, MethodInfo method)
  637. {
  638. if (left == null)
  639. throw new ArgumentNullException ("left");
  640. if (right == null)
  641. throw new ArgumentNullException ("right");
  642. if (method != null)
  643. return new BinaryExpression(ExpressionType.Modulo, left, right, method, method.ReturnType);
  644. // Since both the expressions define the same integer or boolean type we don't have
  645. // to look for the "op_BitwiseAnd" method.
  646. if (left.type == right.type && IsNumeric (left.type))
  647. return new BinaryExpression(ExpressionType.Modulo, left, right, left.type);
  648. // Else we try for a user-defined operator.
  649. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Modulo, "op_Modulus", left, right);
  650. }
  651. public static BinaryExpression Modulo (Expression left, Expression right)
  652. {
  653. return Modulo (left, right, null);
  654. }
  655. #endregion
  656. #region Multiply
  657. public static BinaryExpression Multiply (Expression left, Expression right, MethodInfo method)
  658. {
  659. if (left == null)
  660. throw new ArgumentNullException ("left");
  661. if (right == null)
  662. throw new ArgumentNullException ("right");
  663. if (method != null)
  664. return new BinaryExpression(ExpressionType.Multiply, left, right, method, method.ReturnType);
  665. // Since both the expressions define the same integer or boolean type we don't have
  666. // to look for the "op_BitwiseAnd" method.
  667. if (left.type == right.type && IsNumeric (left.type))
  668. return new BinaryExpression(ExpressionType.Multiply, left, right, left.type);
  669. // Else we try for a user-defined operator.
  670. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Multiply, "op_Multiply", left, right);
  671. }
  672. public static BinaryExpression Multiply (Expression left, Expression right)
  673. {
  674. return Multiply (left, right, null);
  675. }
  676. #endregion
  677. #region MultiplyChecked
  678. public static BinaryExpression MultiplyChecked (Expression left, Expression right, MethodInfo method)
  679. {
  680. if (left == null)
  681. throw new ArgumentNullException ("left");
  682. if (right == null)
  683. throw new ArgumentNullException ("right");
  684. if (method != null)
  685. return new BinaryExpression(ExpressionType.MultiplyChecked, left, right, method, method.ReturnType);
  686. // Since both the expressions define the same numeric type we don't have
  687. // to look for the "op_Addition" method.
  688. if (left.type == right.type && IsNumeric (left.type))
  689. return new BinaryExpression(ExpressionType.MultiplyChecked, left, right, left.type);
  690. method = GetUserDefinedBinaryOperator (left.type, right.type, "op_Multiply");
  691. if (method == null)
  692. throw new InvalidOperationException(String.Format(
  693. "The binary operator MultiplyChecked is not defined for the types '{0}' and '{1}'.", left.type, right.type));
  694. Type retType = method.ReturnType;
  695. return new BinaryExpression(ExpressionType.MultiplyChecked, left, right, method, retType);
  696. }
  697. public static BinaryExpression MultiplyChecked (Expression left, Expression right)
  698. {
  699. return MultiplyChecked(left, right, null);
  700. }
  701. #endregion
  702. public static MemberExpression Property(Expression expression, PropertyInfo property)
  703. {
  704. if (property == null)
  705. throw new ArgumentNullException("property");
  706. MethodInfo getMethod = property.GetGetMethod(true);
  707. if (getMethod == null)
  708. throw new ArgumentException(); // to access the property we need to have
  709. // a get method...
  710. return new MemberExpression(expression, property, property.PropertyType);
  711. }
  712. #region Or
  713. public static BinaryExpression Or (Expression left, Expression right, MethodInfo method)
  714. {
  715. if (left == null)
  716. throw new ArgumentNullException ("left");
  717. if (right == null)
  718. throw new ArgumentNullException ("right");
  719. if (method != null)
  720. return new BinaryExpression(ExpressionType.Or, left, right, method, method.ReturnType);
  721. // Since both the expressions define the same integer or boolean type we don't have
  722. // to look for the "op_BitwiseOr" method.
  723. if (left.type == right.type && IsIntegerOrBool (left.type))
  724. return new BinaryExpression(ExpressionType.Or, left, right, left.type);
  725. // Else we try for a user-defined operator.
  726. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Or, "op_BitwiseOr", left, right);
  727. }
  728. public static BinaryExpression Or (Expression left, Expression right)
  729. {
  730. return Or (left, right, null);
  731. }
  732. #endregion
  733. #region OrElse
  734. public static BinaryExpression OrElse (Expression left, Expression right, MethodInfo method)
  735. {
  736. if (left == null)
  737. throw new ArgumentNullException ("left");
  738. if (right == null)
  739. throw new ArgumentNullException ("right");
  740. // Since both the expressions define the same boolean type we don't have
  741. // to look for the "op_BitwiseOr" method.
  742. if (left.type == right.type && left.type == typeof(bool))
  743. return new BinaryExpression(ExpressionType.OrElse, left, right, left.type);
  744. // Else we must validate the method to make sure it has companion "true" and "false" operators.
  745. if (method == null)
  746. method = GetUserDefinedBinaryOperator (left.type, right.type, "op_BitwiseOr");
  747. if (method == null)
  748. throw new InvalidOperationException(String.Format(
  749. "The binary operator OrElse is not defined for the types '{0}' and '{1}'.", left.type, right.type));
  750. ValidateUserDefinedConditionalLogicOperator(ExpressionType.OrElse, left.type, right.type, method);
  751. return new BinaryExpression(ExpressionType.OrElse, left, right, method, method.ReturnType);
  752. }
  753. public static BinaryExpression OrElse (Expression left, Expression right)
  754. {
  755. return OrElse(left, right, null);
  756. }
  757. #endregion
  758. public static UnaryExpression Quote(Expression expression)
  759. {
  760. if (expression == null)
  761. throw new ArgumentNullException("expression");
  762. return new UnaryExpression(ExpressionType.Quote, expression, expression.GetType());
  763. }
  764. public static MemberExpression Property(Expression expression, string propertyName)
  765. {
  766. if (expression == null)
  767. throw new ArgumentNullException("expression");
  768. PropertyInfo property = expression.Type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
  769. if (property == null)
  770. throw new ArgumentException();
  771. return Property(expression, property);
  772. }
  773. public static MemberExpression PropertyOrField(Expression expression, string propertyOrFieldName)
  774. {
  775. if (expression == null)
  776. throw new ArgumentNullException("expression");
  777. PropertyInfo property = expression.Type.GetProperty(propertyOrFieldName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
  778. if (property != null)
  779. return Property(expression, property);
  780. FieldInfo field = expression.Type.GetField(propertyOrFieldName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
  781. if (field != null)
  782. return Field(expression, field);
  783. //TODO: should we return <null> here?
  784. // the name is not defined in the Type of the expression given...
  785. throw new ArgumentException();
  786. }
  787. #region Subtract
  788. public static BinaryExpression Subtract (Expression left, Expression right, MethodInfo method)
  789. {
  790. if (left == null)
  791. throw new ArgumentNullException ("left");
  792. if (right == null)
  793. throw new ArgumentNullException ("right");
  794. if (method != null)
  795. return new BinaryExpression(ExpressionType.Subtract, left, right, method, method.ReturnType);
  796. // Since both the expressions define the same numeric type we don't have
  797. // to look for the "op_Addition" method.
  798. if (left.type == right.type && IsNumeric (left.type))
  799. return new BinaryExpression(ExpressionType.Subtract, left, right, left.type);
  800. // Else we try for a user-defined operator.
  801. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Subtract, "op_Subtraction", left, right);
  802. }
  803. public static BinaryExpression Subtract (Expression left, Expression right)
  804. {
  805. return Subtract (left, right, null);
  806. }
  807. #endregion
  808. #region SubtractChecked
  809. public static BinaryExpression SubtractChecked (Expression left, Expression right, MethodInfo method)
  810. {
  811. if (left == null)
  812. throw new ArgumentNullException ("left");
  813. if (right == null)
  814. throw new ArgumentNullException ("right");
  815. if (method != null)
  816. return new BinaryExpression(ExpressionType.SubtractChecked, left, right, method, method.ReturnType);
  817. // Since both the expressions define the same numeric type we don't have
  818. // to look for the "op_Addition" method.
  819. if (left.type == right.type && IsNumeric (left.type))
  820. return new BinaryExpression(ExpressionType.SubtractChecked, left, right, left.type);
  821. method = GetUserDefinedBinaryOperator (left.type, right.type, "op_Subtraction");
  822. if (method == null)
  823. throw new InvalidOperationException(String.Format(
  824. "The binary operator AddChecked is not defined for the types '{0}' and '{1}'.", left.type, right.type));
  825. Type retType = method.ReturnType;
  826. // Note: here the code did some very strange checks for bool (but note that bool does
  827. // not define an addition operator) and created nullables for value types (but the new
  828. // MS code does not do that). All that has been removed.
  829. return new BinaryExpression(ExpressionType.SubtractChecked, left, right, method, retType);
  830. }
  831. public static BinaryExpression SubtractChecked (Expression left, Expression right)
  832. {
  833. return SubtractChecked (left, right, null);
  834. }
  835. #endregion
  836. #region TypeAs
  837. public static UnaryExpression TypeAs(Expression expression, Type type)
  838. {
  839. if (expression == null)
  840. throw new ArgumentNullException("expression");
  841. if (type == null)
  842. throw new ArgumentNullException("type");
  843. return new UnaryExpression(ExpressionType.TypeAs, expression, type);
  844. }
  845. #endregion
  846. #region TypeIs
  847. public static TypeBinaryExpression TypeIs(Expression expression, Type type)
  848. {
  849. if (expression == null)
  850. throw new ArgumentNullException("expression");
  851. if (type == null)
  852. throw new ArgumentNullException("type");
  853. return new TypeBinaryExpression(ExpressionType.TypeIs, expression, type, typeof(bool));
  854. }
  855. #endregion
  856. }
  857. }