Expression.cs 39 KB

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