Expression.cs 47 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119
  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 "broad 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 PropertyInfo.
  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 = (member as FieldInfo).FieldType;
  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 = (member as PropertyInfo).PropertyType;
  232. }
  233. else {
  234. throw new ArgumentException ("Argument must be either a FieldInfo or PropertyInfo");
  235. }
  236. }
  237. private static void ValidateGettableFieldOrPropertyMember (MemberInfo member, out Type memberType)
  238. {
  239. if (member.MemberType == MemberTypes.Field) {
  240. memberType = (member as FieldInfo).FieldType;
  241. }
  242. else if (member.MemberType == MemberTypes.Property) {
  243. PropertyInfo pi = (PropertyInfo)member;
  244. if (!pi.CanRead)
  245. throw new ArgumentException (String.Format ("The property '{0}' has no 'get' accessor", pi));
  246. memberType = (member as PropertyInfo).PropertyType;
  247. }
  248. else {
  249. throw new ArgumentException ("Argument must be either a FieldInfo or PropertyInfo");
  250. }
  251. }
  252. #endregion
  253. #region ToString
  254. public override string ToString()
  255. {
  256. StringBuilder builder = new StringBuilder ();
  257. BuildString (builder);
  258. return builder.ToString ();
  259. }
  260. #endregion
  261. #region Add
  262. public static BinaryExpression Add(Expression left, Expression right, MethodInfo method)
  263. {
  264. if (left == null)
  265. throw new ArgumentNullException ("left");
  266. if (right == null)
  267. throw new ArgumentNullException ("right");
  268. if (method != null)
  269. return new BinaryExpression(ExpressionType.Add, left, right, method, method.ReturnType);
  270. // Since both the expressions define the same numeric type we don't have
  271. // to look for the "op_Addition" method.
  272. if (left.type == right.type && IsNumeric (left.type))
  273. return new BinaryExpression(ExpressionType.Add, left, right, left.type);
  274. // Else we try for a user-defined operator.
  275. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Add, "op_Addition", left, right);
  276. }
  277. public static BinaryExpression Add(Expression left, Expression right)
  278. {
  279. return Add(left, right, null);
  280. }
  281. #endregion
  282. #region AddChecked
  283. public static BinaryExpression AddChecked(Expression left, Expression right, MethodInfo method)
  284. {
  285. if (left == null)
  286. throw new ArgumentNullException ("left");
  287. if (right == null)
  288. throw new ArgumentNullException ("right");
  289. if (method != null)
  290. return new BinaryExpression(ExpressionType.AddChecked, left, right, method, method.ReturnType);
  291. // Since both the expressions define the same numeric type we don't have
  292. // to look for the "op_Addition" method.
  293. if (left.type == right.type && IsNumeric (left.type))
  294. return new BinaryExpression(ExpressionType.AddChecked, left, right, left.type);
  295. method = GetUserDefinedBinaryOperator (left.type, right.type, "op_Addition");
  296. if (method == null)
  297. throw new InvalidOperationException(String.Format(
  298. "The binary operator AddChecked is not defined for the types '{0}' and '{1}'.", left.type, right.type));
  299. Type retType = method.ReturnType;
  300. // Note: here the code did some very strange checks for bool (but note that bool does
  301. // not define an addition operator) and created nullables for value types (but the new
  302. // MS code does not do that). All that has been removed.
  303. return new BinaryExpression(ExpressionType.AddChecked, left, right, method, retType);
  304. }
  305. public static BinaryExpression AddChecked(Expression left, Expression right)
  306. {
  307. return AddChecked(left, right, null);
  308. }
  309. #endregion
  310. #region And
  311. public static BinaryExpression And(Expression left, Expression right, MethodInfo method)
  312. {
  313. if (left == null)
  314. throw new ArgumentNullException ("left");
  315. if (right == null)
  316. throw new ArgumentNullException ("right");
  317. if (method != null)
  318. return new BinaryExpression(ExpressionType.And, left, right, method, method.ReturnType);
  319. // Since both the expressions define the same integer or boolean type we don't have
  320. // to look for the "op_BitwiseAnd" method.
  321. if (left.type == right.type && IsIntegerOrBool (left.type))
  322. return new BinaryExpression(ExpressionType.And, left, right, left.type);
  323. // Else we try for a user-defined operator.
  324. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.And, "op_BitwiseAnd", left, right);
  325. }
  326. public static BinaryExpression And(Expression left, Expression right)
  327. {
  328. return And(left, right, null);
  329. }
  330. #endregion
  331. #region AndAlso
  332. public static BinaryExpression AndAlso(Expression left, Expression right, MethodInfo method)
  333. {
  334. if (left == null)
  335. throw new ArgumentNullException ("left");
  336. if (right == null)
  337. throw new ArgumentNullException ("right");
  338. // Since both the expressions define the same boolean type we don't have
  339. // to look for the "op_BitwiseAnd" method.
  340. if (left.type == right.type && left.type == typeof(bool))
  341. return new BinaryExpression(ExpressionType.AndAlso, left, right, left.type);
  342. // Else we must validate the method to make sure it has companion "true" and "false" operators.
  343. if (method == null)
  344. method = GetUserDefinedBinaryOperator (left.type, right.type, "op_BitwiseAnd");
  345. if (method == null)
  346. throw new InvalidOperationException(String.Format(
  347. "The binary operator AndAlso is not defined for the types '{0}' and '{1}'.", left.type, right.type));
  348. ValidateUserDefinedConditionalLogicOperator(ExpressionType.AndAlso, left.type, right.type, method);
  349. return new BinaryExpression(ExpressionType.AndAlso, left, right, method, method.ReturnType);
  350. }
  351. public static BinaryExpression AndAlso(Expression left, Expression right)
  352. {
  353. return AndAlso(left, right, null);
  354. }
  355. #endregion
  356. #region ArrayIndex
  357. public static BinaryExpression ArrayIndex(Expression array, Expression index)
  358. {
  359. if (array == null)
  360. throw new ArgumentNullException ("array");
  361. if (index == null)
  362. throw new ArgumentNullException ("index");
  363. if (!array.type.IsArray)
  364. throw new ArgumentException ("Argument must be array");
  365. if (index.type != typeof(int))
  366. throw new ArgumentException ("Argument for array index must be of type Int32");
  367. return new BinaryExpression(ExpressionType.ArrayIndex, array, index, array.type.GetElementType());
  368. }
  369. public static MethodCallExpression ArrayIndex(Expression array, params Expression[] indexes)
  370. {
  371. return ArrayIndex(array, (IEnumerable<Expression>)indexes);
  372. }
  373. public static MethodCallExpression ArrayIndex(Expression array, IEnumerable<Expression> indexes)
  374. {
  375. if (array == null)
  376. throw new ArgumentNullException ("array");
  377. if (indexes == null)
  378. throw new ArgumentNullException ("indexes");
  379. if (!array.type.IsArray)
  380. throw new ArgumentException ("Argument must be array");
  381. // We'll need an array of typeof(Type) elements long as the array's rank later
  382. // and also a generic List to hold the indexes (ReadOnlyCollection wants that.)
  383. Type[] types = (Type[])Array.CreateInstance(typeof(Type), array.type.GetArrayRank());
  384. Expression[] indexesList = new Expression[array.type.GetArrayRank()];
  385. int rank = 0;
  386. foreach (Expression index in indexes) {
  387. if (index.type != typeof(int))
  388. throw new ArgumentException ("Argument for array index must be of type Int32");
  389. if (rank == array.type.GetArrayRank())
  390. throw new ArgumentException ("Incorrect number of indexes");
  391. types[rank] = index.type;
  392. indexesList[rank] = index;
  393. rank += 1;
  394. }
  395. // If the array's rank is equalto the number of given indexes we can go on and
  396. // look for a Get(Int32, ...) method with "rank" parameters to generate the
  397. // MethodCallExpression.
  398. MethodInfo method = array.type.GetMethod("Get",
  399. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance, null, types, null);
  400. // This should not happen, but we check anyway.
  401. if (method == null)
  402. throw new InvalidOperationException(String.Format(
  403. "The method Get(...) is not defined for the type '{0}'.", array.type));
  404. return new MethodCallExpression(ExpressionType.Call, method, array, new ReadOnlyCollection<Expression>(indexesList));
  405. }
  406. #endregion
  407. #region ArrayLength
  408. public static UnaryExpression ArrayLength(Expression array)
  409. {
  410. if (array == null)
  411. throw new ArgumentNullException ("array");
  412. if (!array.type.IsArray)
  413. throw new ArgumentException ("Argument must be array");
  414. return new UnaryExpression(ExpressionType.ArrayLength, array, typeof(Int32));
  415. }
  416. #endregion
  417. #region Bind
  418. public static MemberAssignment Bind (MemberInfo member, Expression expression)
  419. {
  420. if (member == null)
  421. throw new ArgumentNullException ("member");
  422. if (expression == null)
  423. throw new ArgumentNullException ("expression");
  424. Type memberType;
  425. ValidateSettableFieldOrPropertyMember(member, out memberType);
  426. return new MemberAssignment(member, expression);
  427. }
  428. public static MemberAssignment Bind (MethodInfo propertyAccessor, Expression expression)
  429. {
  430. if (propertyAccessor == null)
  431. throw new ArgumentNullException ("propertyAccessor");
  432. if (expression == null)
  433. throw new ArgumentNullException ("expression");
  434. return new MemberAssignment(GetProperty(propertyAccessor), expression);
  435. }
  436. #endregion
  437. #region Call
  438. public static MethodCallExpression Call(Expression instance, MethodInfo method)
  439. {
  440. if (method == null)
  441. throw new ArgumentNullException("method");
  442. if (instance == null && !method.IsStatic)
  443. throw new ArgumentNullException("instance");
  444. return Call(instance, method, (Expression[])null);
  445. }
  446. public static MethodCallExpression Call(Expression instance, MethodInfo method, params Expression[] arguments)
  447. {
  448. return Call(instance, method, (IEnumerable<Expression>)arguments);
  449. }
  450. public static MethodCallExpression Call(Expression instance, MethodInfo method, IEnumerable<Expression> arguments)
  451. {
  452. if (method == null)
  453. throw new ArgumentNullException("method");
  454. if (arguments == null)
  455. throw new ArgumentNullException("arguments");
  456. if (instance == null && !method.IsStatic)
  457. throw new ArgumentNullException("instance");
  458. if (method.IsGenericMethodDefinition)
  459. throw new ArgumentException();
  460. if (method.ContainsGenericParameters)
  461. throw new ArgumentException();
  462. if (instance != null && !instance.type.IsAssignableFrom(method.DeclaringType))
  463. throw new ArgumentException();
  464. ReadOnlyCollection<Expression> roArgs = Enumerable.ToReadOnlyCollection<Expression>(arguments);
  465. ParameterInfo[] pars = method.GetParameters();
  466. if (Enumerable.Count<Expression>(arguments) != pars.Length)
  467. throw new ArgumentException();
  468. if (pars.Length > 0)
  469. {
  470. //TODO: validate the parameters against the arguments...
  471. }
  472. return new MethodCallExpression(ExpressionType.Call, method, instance, roArgs);
  473. }
  474. public static MethodCallExpression Call (Expression instance, string methodName, Type [] typeArguments, params Expression [] arguments)
  475. {
  476. if (instance == null)
  477. throw new ArgumentNullException("instance");
  478. if (arguments == null)
  479. throw new ArgumentNullException("arguments");
  480. return Call (null, FindMethod (instance.type, methodName, typeArguments, arguments,
  481. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance),
  482. (IEnumerable<Expression>)arguments);
  483. }
  484. public static MethodCallExpression Call(MethodInfo method, params Expression[] arguments)
  485. {
  486. return Call(null, method, (IEnumerable<Expression>)arguments);
  487. }
  488. public static MethodCallExpression Call (Type type, string methodName, Type [] typeArguments, params Expression [] arguments)
  489. {
  490. // FIXME: MS implementation does not check for type here and simply lets FindMethod() raise
  491. // a NullReferenceException. Shall we do the same or raise the correct exception here?
  492. //if (type == null)
  493. // throw new ArgumentNullException("type");
  494. if (methodName == null)
  495. throw new ArgumentNullException("methodName");
  496. if (arguments == null)
  497. throw new ArgumentNullException("arguments");
  498. // Note that we're looking for static methods only (this version of Call() doesn't take an instance).
  499. return Call (null, FindMethod (type, methodName, typeArguments, arguments,
  500. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static),
  501. (IEnumerable<Expression>)arguments);
  502. }
  503. #endregion
  504. // NOTE: CallVirtual is not implemented because it is already marked as Obsolete by MS.
  505. public static ConditionalExpression Condition(Expression test, Expression ifTrue, Expression ifFalse)
  506. {
  507. if (test == null)
  508. throw new ArgumentNullException("test");
  509. if (ifTrue == null)
  510. throw new ArgumentNullException("ifTrue");
  511. if (ifFalse == null)
  512. throw new ArgumentNullException("ifFalse");
  513. if (test.type != typeof(bool))
  514. throw new ArgumentException();
  515. if (ifTrue.type != ifFalse.type)
  516. throw new ArgumentException();
  517. return new ConditionalExpression(test, ifTrue, ifFalse, ifTrue.type);
  518. }
  519. public static ConstantExpression Constant(object value, Type type)
  520. {
  521. if (type == null)
  522. throw new ArgumentNullException("type");
  523. if (value == null && !IsNullableType(type))
  524. throw new ArgumentException("Argument types do not match");
  525. return new ConstantExpression(value, type);
  526. }
  527. public static ConstantExpression Constant(object value)
  528. {
  529. if (value != null)
  530. return new ConstantExpression(value, value.GetType());
  531. else
  532. return new ConstantExpression(null, typeof(object));
  533. }
  534. #region Divide
  535. public static BinaryExpression Divide(Expression left, Expression right, MethodInfo method)
  536. {
  537. if (left == null)
  538. throw new ArgumentNullException ("left");
  539. if (right == null)
  540. throw new ArgumentNullException ("right");
  541. if (method != null)
  542. return new BinaryExpression(ExpressionType.Divide, left, right, method, method.ReturnType);
  543. // Since both the expressions define the same numeric type we don't have
  544. // to look for the "op_Addition" method.
  545. if (left.type == right.type && IsNumeric (left.type))
  546. return new BinaryExpression(ExpressionType.Divide, left, right, left.type);
  547. // Else we try for a user-defined operator.
  548. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Divide, "op_Division", left, right);
  549. }
  550. public static BinaryExpression Divide(Expression left, Expression right)
  551. {
  552. return Divide(left, right, null);
  553. }
  554. #endregion
  555. #region ExclusiveOr
  556. public static BinaryExpression ExclusiveOr (Expression left, Expression right, System.Reflection.MethodInfo method)
  557. {
  558. if (left == null)
  559. throw new ArgumentNullException ("left");
  560. if (right == null)
  561. throw new ArgumentNullException ("right");
  562. if (method != null)
  563. return new BinaryExpression(ExpressionType.ExclusiveOr, left, right, method, method.ReturnType);
  564. // Since both the expressions define the same integer or boolean type we don't have
  565. // to look for the "op_BitwiseAnd" method.
  566. if (left.type == right.type && IsIntegerOrBool (left.type))
  567. return new BinaryExpression(ExpressionType.ExclusiveOr, left, right, left.type);
  568. // Else we try for a user-defined operator.
  569. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.ExclusiveOr, "op_ExclusiveOr", left, right);
  570. }
  571. public static BinaryExpression ExclusiveOr (Expression left, Expression right)
  572. {
  573. return ExclusiveOr (left, right, null);
  574. }
  575. #endregion
  576. #region Field
  577. public static MemberExpression Field (Expression expression, FieldInfo field)
  578. {
  579. // Note that expression can be (and should be) null when the access is to a static field.
  580. if (field == null)
  581. throw new ArgumentNullException("field");
  582. Type fieldType;
  583. ValidateGettableFieldOrPropertyMember(field, out fieldType);
  584. return new MemberExpression(expression, field, fieldType);
  585. }
  586. public static MemberExpression Field (Expression expression, string fieldName)
  587. {
  588. if (expression == null)
  589. throw new ArgumentNullException("expression");
  590. if (fieldName == null)
  591. throw new ArgumentNullException("fieldName");
  592. FieldInfo field = expression.Type.GetField(fieldName,
  593. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
  594. if (field == null)
  595. throw new ArgumentException (String.Format ("Field {0} is not defined for type {1}",
  596. fieldName, expression.type.FullName));
  597. return Field(expression, field);
  598. }
  599. #endregion
  600. public static Type GetFuncType(params Type[] typeArgs)
  601. {
  602. if (typeArgs == null)
  603. throw new ArgumentNullException("typeArgs");
  604. if (typeArgs.Length > 5)
  605. throw new ArgumentException();
  606. return typeof(Func<,,,,>).MakeGenericType(typeArgs);
  607. }
  608. #region LeftShift
  609. public static BinaryExpression LeftShift (Expression left, Expression right, MethodInfo method)
  610. {
  611. if (left == null)
  612. throw new ArgumentNullException ("left");
  613. if (right == null)
  614. throw new ArgumentNullException ("right");
  615. if (method != null)
  616. return new BinaryExpression(ExpressionType.LeftShift, left, right, method, method.ReturnType);
  617. // If the left side is any kind of integer and the right is int32 we don't have
  618. // to look for the "op_Addition" method.
  619. if (IsInteger(left.type) && right.type == typeof(Int32))
  620. return new BinaryExpression(ExpressionType.LeftShift, left, right, left.type);
  621. // Else we try for a user-defined operator.
  622. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.LeftShift, "op_LeftShift", left, right);
  623. }
  624. public static BinaryExpression LeftShift (Expression left, Expression right)
  625. {
  626. return LeftShift (left, right, null);
  627. }
  628. #endregion
  629. public static ListInitExpression ListInit(NewExpression newExpression, params ElementInit[] initializers)
  630. {
  631. if (initializers == null)
  632. throw new ArgumentNullException("inizializers");
  633. return ListInit(newExpression, Enumerable.ToReadOnlyCollection<ElementInit>(initializers));
  634. }
  635. public static ListInitExpression ListInit(NewExpression newExpression, IEnumerable<ElementInit> initializers)
  636. {
  637. if (newExpression == null)
  638. throw new ArgumentNullException("newExpression");
  639. if (initializers == null)
  640. throw new ArgumentNullException("inizializers");
  641. return new ListInitExpression(newExpression, Enumerable.ToReadOnlyCollection<ElementInit>(initializers));
  642. }
  643. public static MemberInitExpression MemberInit(NewExpression newExpression, IEnumerable<MemberBinding> bindings)
  644. {
  645. if (newExpression == null)
  646. throw new ArgumentNullException("newExpression");
  647. if (bindings == null)
  648. throw new ArgumentNullException("bindings");
  649. return new MemberInitExpression(newExpression, Enumerable.ToReadOnlyCollection<MemberBinding>(bindings));
  650. }
  651. #region Modulo
  652. public static BinaryExpression Modulo (Expression left, Expression right, MethodInfo method)
  653. {
  654. if (left == null)
  655. throw new ArgumentNullException ("left");
  656. if (right == null)
  657. throw new ArgumentNullException ("right");
  658. if (method != null)
  659. return new BinaryExpression(ExpressionType.Modulo, left, right, method, method.ReturnType);
  660. // Since both the expressions define the same integer or boolean type we don't have
  661. // to look for the "op_BitwiseAnd" method.
  662. if (left.type == right.type && IsNumeric (left.type))
  663. return new BinaryExpression(ExpressionType.Modulo, left, right, left.type);
  664. // Else we try for a user-defined operator.
  665. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Modulo, "op_Modulus", left, right);
  666. }
  667. public static BinaryExpression Modulo (Expression left, Expression right)
  668. {
  669. return Modulo (left, right, null);
  670. }
  671. #endregion
  672. #region Multiply
  673. public static BinaryExpression Multiply (Expression left, Expression right, MethodInfo method)
  674. {
  675. if (left == null)
  676. throw new ArgumentNullException ("left");
  677. if (right == null)
  678. throw new ArgumentNullException ("right");
  679. if (method != null)
  680. return new BinaryExpression(ExpressionType.Multiply, left, right, method, method.ReturnType);
  681. // Since both the expressions define the same integer or boolean type we don't have
  682. // to look for the "op_BitwiseAnd" method.
  683. if (left.type == right.type && IsNumeric (left.type))
  684. return new BinaryExpression(ExpressionType.Multiply, left, right, left.type);
  685. // Else we try for a user-defined operator.
  686. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Multiply, "op_Multiply", left, right);
  687. }
  688. public static BinaryExpression Multiply (Expression left, Expression right)
  689. {
  690. return Multiply (left, right, null);
  691. }
  692. #endregion
  693. #region MultiplyChecked
  694. public static BinaryExpression MultiplyChecked (Expression left, Expression right, MethodInfo method)
  695. {
  696. if (left == null)
  697. throw new ArgumentNullException ("left");
  698. if (right == null)
  699. throw new ArgumentNullException ("right");
  700. if (method != null)
  701. return new BinaryExpression(ExpressionType.MultiplyChecked, left, right, method, method.ReturnType);
  702. // Since both the expressions define the same numeric type we don't have
  703. // to look for the "op_Addition" method.
  704. if (left.type == right.type && IsNumeric (left.type))
  705. return new BinaryExpression(ExpressionType.MultiplyChecked, left, right, left.type);
  706. method = GetUserDefinedBinaryOperator (left.type, right.type, "op_Multiply");
  707. if (method == null)
  708. throw new InvalidOperationException(String.Format(
  709. "The binary operator MultiplyChecked is not defined for the types '{0}' and '{1}'.", left.type, right.type));
  710. Type retType = method.ReturnType;
  711. return new BinaryExpression(ExpressionType.MultiplyChecked, left, right, method, retType);
  712. }
  713. public static BinaryExpression MultiplyChecked (Expression left, Expression right)
  714. {
  715. return MultiplyChecked(left, right, null);
  716. }
  717. #endregion
  718. #region Or
  719. public static BinaryExpression Or (Expression left, Expression right, MethodInfo method)
  720. {
  721. if (left == null)
  722. throw new ArgumentNullException ("left");
  723. if (right == null)
  724. throw new ArgumentNullException ("right");
  725. if (method != null)
  726. return new BinaryExpression(ExpressionType.Or, left, right, method, method.ReturnType);
  727. // Since both the expressions define the same integer or boolean type we don't have
  728. // to look for the "op_BitwiseOr" method.
  729. if (left.type == right.type && IsIntegerOrBool (left.type))
  730. return new BinaryExpression(ExpressionType.Or, left, right, left.type);
  731. // Else we try for a user-defined operator.
  732. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Or, "op_BitwiseOr", left, right);
  733. }
  734. public static BinaryExpression Or (Expression left, Expression right)
  735. {
  736. return Or (left, right, null);
  737. }
  738. #endregion
  739. #region OrElse
  740. public static BinaryExpression OrElse (Expression left, Expression right, MethodInfo method)
  741. {
  742. if (left == null)
  743. throw new ArgumentNullException ("left");
  744. if (right == null)
  745. throw new ArgumentNullException ("right");
  746. // Since both the expressions define the same boolean type we don't have
  747. // to look for the "op_BitwiseOr" method.
  748. if (left.type == right.type && left.type == typeof(bool))
  749. return new BinaryExpression(ExpressionType.OrElse, left, right, left.type);
  750. // Else we must validate the method to make sure it has companion "true" and "false" operators.
  751. if (method == null)
  752. method = GetUserDefinedBinaryOperator (left.type, right.type, "op_BitwiseOr");
  753. if (method == null)
  754. throw new InvalidOperationException(String.Format(
  755. "The binary operator OrElse is not defined for the types '{0}' and '{1}'.", left.type, right.type));
  756. ValidateUserDefinedConditionalLogicOperator(ExpressionType.OrElse, left.type, right.type, method);
  757. return new BinaryExpression(ExpressionType.OrElse, left, right, method, method.ReturnType);
  758. }
  759. public static BinaryExpression OrElse (Expression left, Expression right)
  760. {
  761. return OrElse(left, right, null);
  762. }
  763. #endregion
  764. #region Property
  765. public static MemberExpression Property (Expression expression, MethodInfo propertyAccessor)
  766. {
  767. if (propertyAccessor == null)
  768. throw new ArgumentNullException("propertyAccessor");
  769. return Property(expression, GetProperty(propertyAccessor));
  770. }
  771. public static MemberExpression Property (Expression expression, PropertyInfo property)
  772. {
  773. if (property == null)
  774. throw new ArgumentNullException("property");
  775. Type propertyType;
  776. ValidateGettableFieldOrPropertyMember(property, out propertyType);
  777. return new MemberExpression(expression, property, propertyType);
  778. }
  779. public static MemberExpression Property(Expression expression, string propertyName)
  780. {
  781. if (expression == null)
  782. throw new ArgumentNullException ("expression");
  783. if (propertyName == null)
  784. throw new ArgumentNullException ("propertyName");
  785. PropertyInfo property = expression.Type.GetProperty (propertyName,
  786. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
  787. if (property == null)
  788. throw new ArgumentException (String.Format ("{0} is not a member of type {1}",
  789. propertyName, expression.type.FullName));
  790. return Property (expression, property);
  791. }
  792. #endregion
  793. #region PropertyOrField
  794. public static MemberExpression PropertyOrField(Expression expression, string propertyOrFieldName)
  795. {
  796. if (expression == null)
  797. throw new ArgumentNullException ("expression");
  798. if (propertyOrFieldName == null)
  799. throw new ArgumentNullException ("propertyOrFieldName");
  800. PropertyInfo property = expression.type.GetProperty (propertyOrFieldName,
  801. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
  802. if (property != null)
  803. return Property (expression, property);
  804. FieldInfo field = expression.type.GetField (propertyOrFieldName,
  805. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
  806. if (field != null)
  807. return Field (expression, field);
  808. throw new ArgumentException (String.Format ("{0} is not a member of type {1}",
  809. propertyOrFieldName, expression.type.FullName));
  810. }
  811. #endregion
  812. #region Quote
  813. public static UnaryExpression Quote(Expression expression)
  814. {
  815. if (expression == null)
  816. throw new ArgumentNullException ("expression");
  817. return new UnaryExpression (ExpressionType.Quote, expression, expression.GetType());
  818. }
  819. #endregion
  820. #region RightShift
  821. public static BinaryExpression RightShift (Expression left, Expression right, MethodInfo method)
  822. {
  823. if (left == null)
  824. throw new ArgumentNullException ("left");
  825. if (right == null)
  826. throw new ArgumentNullException ("right");
  827. if (method != null)
  828. return new BinaryExpression (ExpressionType.RightShift, left, right, method, method.ReturnType);
  829. // If the left side is any kind of integer and the right is int32 we don't have
  830. // to look for the "op_Addition" method.
  831. if (IsInteger(left.type) && right.type == typeof(Int32))
  832. return new BinaryExpression (ExpressionType.RightShift, left, right, left.type);
  833. // Else we try for a user-defined operator.
  834. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.RightShift, "op_RightShift", left, right);
  835. }
  836. public static BinaryExpression RightShift (Expression left, Expression right)
  837. {
  838. return RightShift (left, right, null);
  839. }
  840. #endregion
  841. #region Subtract
  842. public static BinaryExpression Subtract (Expression left, Expression right, MethodInfo method)
  843. {
  844. if (left == null)
  845. throw new ArgumentNullException ("left");
  846. if (right == null)
  847. throw new ArgumentNullException ("right");
  848. if (method != null)
  849. return new BinaryExpression (ExpressionType.Subtract, left, right, method, method.ReturnType);
  850. // Since both the expressions define the same numeric type we don't have
  851. // to look for the "op_Addition" method.
  852. if (left.type == right.type && IsNumeric (left.type))
  853. return new BinaryExpression (ExpressionType.Subtract, left, right, left.type);
  854. // Else we try for a user-defined operator.
  855. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Subtract, "op_Subtraction", left, right);
  856. }
  857. public static BinaryExpression Subtract (Expression left, Expression right)
  858. {
  859. return Subtract (left, right, null);
  860. }
  861. #endregion
  862. #region SubtractChecked
  863. public static BinaryExpression SubtractChecked (Expression left, Expression right, MethodInfo method)
  864. {
  865. if (left == null)
  866. throw new ArgumentNullException ("left");
  867. if (right == null)
  868. throw new ArgumentNullException ("right");
  869. if (method != null)
  870. return new BinaryExpression (ExpressionType.SubtractChecked, left, right, method, method.ReturnType);
  871. // Since both the expressions define the same numeric type we don't have
  872. // to look for the "op_Addition" method.
  873. if (left.type == right.type && IsNumeric (left.type))
  874. return new BinaryExpression (ExpressionType.SubtractChecked, left, right, left.type);
  875. method = GetUserDefinedBinaryOperator (left.type, right.type, "op_Subtraction");
  876. if (method == null)
  877. throw new InvalidOperationException (String.Format (
  878. "The binary operator AddChecked is not defined for the types '{0}' and '{1}'.", left.type, right.type));
  879. Type retType = method.ReturnType;
  880. return new BinaryExpression (ExpressionType.SubtractChecked, left, right, method, retType);
  881. }
  882. public static BinaryExpression SubtractChecked (Expression left, Expression right)
  883. {
  884. return SubtractChecked (left, right, null);
  885. }
  886. #endregion
  887. #region TypeAs
  888. public static UnaryExpression TypeAs (Expression expression, Type type)
  889. {
  890. if (expression == null)
  891. throw new ArgumentNullException ("expression");
  892. if (type == null)
  893. throw new ArgumentNullException ("type");
  894. return new UnaryExpression (ExpressionType.TypeAs, expression, type);
  895. }
  896. #endregion
  897. #region TypeIs
  898. public static TypeBinaryExpression TypeIs (Expression expression, Type type)
  899. {
  900. if (expression == null)
  901. throw new ArgumentNullException ("expression");
  902. if (type == null)
  903. throw new ArgumentNullException ("type");
  904. return new TypeBinaryExpression (ExpressionType.TypeIs, expression, type, typeof(bool));
  905. }
  906. #endregion
  907. }
  908. }