Expression.cs 48 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137
  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 FuncletExpression Funclet(Funclet funclet, Type type)
  601. {
  602. if (funclet == null)
  603. throw new ArgumentNullException("funclet");
  604. if (type == null)
  605. throw new ArgumentNullException("type");
  606. return new FuncletExpression(funclet, type);
  607. }
  608. public static Type GetFuncType(params Type[] typeArgs)
  609. {
  610. if (typeArgs == null)
  611. throw new ArgumentNullException("typeArgs");
  612. if (typeArgs.Length > 5)
  613. throw new ArgumentException();
  614. return typeof(Func<,,,,>).MakeGenericType(typeArgs);
  615. }
  616. #region LeftShift
  617. public static BinaryExpression LeftShift (Expression left, Expression right, MethodInfo method)
  618. {
  619. if (left == null)
  620. throw new ArgumentNullException ("left");
  621. if (right == null)
  622. throw new ArgumentNullException ("right");
  623. if (method != null)
  624. return new BinaryExpression(ExpressionType.LeftShift, left, right, method, method.ReturnType);
  625. // If the left side is any kind of integer and the right is int32 we don't have
  626. // to look for the "op_Addition" method.
  627. if (IsInteger(left.type) && right.type == typeof(Int32))
  628. return new BinaryExpression(ExpressionType.LeftShift, left, right, left.type);
  629. // Else we try for a user-defined operator.
  630. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.LeftShift, "op_LeftShift", left, right);
  631. }
  632. public static BinaryExpression LeftShift (Expression left, Expression right)
  633. {
  634. return LeftShift (left, right, null);
  635. }
  636. #endregion
  637. public static ListInitExpression ListInit(NewExpression newExpression, params Expression[] initializers)
  638. {
  639. if (initializers == null)
  640. throw new ArgumentNullException("inizializers");
  641. return ListInit(newExpression, Enumerable.ToReadOnlyCollection<Expression>(initializers));
  642. }
  643. public static ListInitExpression ListInit(NewExpression newExpression, IEnumerable<Expression> initializers)
  644. {
  645. if (newExpression == null)
  646. throw new ArgumentNullException("newExpression");
  647. if (initializers == null)
  648. throw new ArgumentNullException("inizializers");
  649. return new ListInitExpression(newExpression, Enumerable.ToReadOnlyCollection<Expression>(initializers));
  650. }
  651. public static MemberInitExpression MemberInit(NewExpression newExpression, IEnumerable<MemberBinding> bindings)
  652. {
  653. if (newExpression == null)
  654. throw new ArgumentNullException("newExpression");
  655. if (bindings == null)
  656. throw new ArgumentNullException("bindings");
  657. return new MemberInitExpression(newExpression, Enumerable.ToReadOnlyCollection<MemberBinding>(bindings));
  658. }
  659. #region Modulo
  660. public static BinaryExpression Modulo (Expression left, Expression right, MethodInfo method)
  661. {
  662. if (left == null)
  663. throw new ArgumentNullException ("left");
  664. if (right == null)
  665. throw new ArgumentNullException ("right");
  666. if (method != null)
  667. return new BinaryExpression(ExpressionType.Modulo, left, right, method, method.ReturnType);
  668. // Since both the expressions define the same integer or boolean type we don't have
  669. // to look for the "op_BitwiseAnd" method.
  670. if (left.type == right.type && IsNumeric (left.type))
  671. return new BinaryExpression(ExpressionType.Modulo, left, right, left.type);
  672. // Else we try for a user-defined operator.
  673. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Modulo, "op_Modulus", left, right);
  674. }
  675. public static BinaryExpression Modulo (Expression left, Expression right)
  676. {
  677. return Modulo (left, right, null);
  678. }
  679. #endregion
  680. #region Multiply
  681. public static BinaryExpression Multiply (Expression left, Expression right, MethodInfo method)
  682. {
  683. if (left == null)
  684. throw new ArgumentNullException ("left");
  685. if (right == null)
  686. throw new ArgumentNullException ("right");
  687. if (method != null)
  688. return new BinaryExpression(ExpressionType.Multiply, left, right, method, method.ReturnType);
  689. // Since both the expressions define the same integer or boolean type we don't have
  690. // to look for the "op_BitwiseAnd" method.
  691. if (left.type == right.type && IsNumeric (left.type))
  692. return new BinaryExpression(ExpressionType.Multiply, left, right, left.type);
  693. // Else we try for a user-defined operator.
  694. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Multiply, "op_Multiply", left, right);
  695. }
  696. public static BinaryExpression Multiply (Expression left, Expression right)
  697. {
  698. return Multiply (left, right, null);
  699. }
  700. #endregion
  701. #region MultiplyChecked
  702. public static BinaryExpression MultiplyChecked (Expression left, Expression right, MethodInfo method)
  703. {
  704. if (left == null)
  705. throw new ArgumentNullException ("left");
  706. if (right == null)
  707. throw new ArgumentNullException ("right");
  708. if (method != null)
  709. return new BinaryExpression(ExpressionType.MultiplyChecked, left, right, method, method.ReturnType);
  710. // Since both the expressions define the same numeric type we don't have
  711. // to look for the "op_Addition" method.
  712. if (left.type == right.type && IsNumeric (left.type))
  713. return new BinaryExpression(ExpressionType.MultiplyChecked, left, right, left.type);
  714. method = GetUserDefinedBinaryOperator (left.type, right.type, "op_Multiply");
  715. if (method == null)
  716. throw new InvalidOperationException(String.Format(
  717. "The binary operator MultiplyChecked is not defined for the types '{0}' and '{1}'.", left.type, right.type));
  718. Type retType = method.ReturnType;
  719. return new BinaryExpression(ExpressionType.MultiplyChecked, left, right, method, retType);
  720. }
  721. public static BinaryExpression MultiplyChecked (Expression left, Expression right)
  722. {
  723. return MultiplyChecked(left, right, null);
  724. }
  725. #endregion
  726. #region Or
  727. public static BinaryExpression Or (Expression left, Expression right, MethodInfo method)
  728. {
  729. if (left == null)
  730. throw new ArgumentNullException ("left");
  731. if (right == null)
  732. throw new ArgumentNullException ("right");
  733. if (method != null)
  734. return new BinaryExpression(ExpressionType.Or, left, right, method, method.ReturnType);
  735. // Since both the expressions define the same integer or boolean type we don't have
  736. // to look for the "op_BitwiseOr" method.
  737. if (left.type == right.type && IsIntegerOrBool (left.type))
  738. return new BinaryExpression(ExpressionType.Or, left, right, left.type);
  739. // Else we try for a user-defined operator.
  740. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Or, "op_BitwiseOr", left, right);
  741. }
  742. public static BinaryExpression Or (Expression left, Expression right)
  743. {
  744. return Or (left, right, null);
  745. }
  746. #endregion
  747. #region OrElse
  748. public static BinaryExpression OrElse (Expression left, Expression right, MethodInfo method)
  749. {
  750. if (left == null)
  751. throw new ArgumentNullException ("left");
  752. if (right == null)
  753. throw new ArgumentNullException ("right");
  754. // Since both the expressions define the same boolean type we don't have
  755. // to look for the "op_BitwiseOr" method.
  756. if (left.type == right.type && left.type == typeof(bool))
  757. return new BinaryExpression(ExpressionType.OrElse, left, right, left.type);
  758. // Else we must validate the method to make sure it has companion "true" and "false" operators.
  759. if (method == null)
  760. method = GetUserDefinedBinaryOperator (left.type, right.type, "op_BitwiseOr");
  761. if (method == null)
  762. throw new InvalidOperationException(String.Format(
  763. "The binary operator OrElse is not defined for the types '{0}' and '{1}'.", left.type, right.type));
  764. ValidateUserDefinedConditionalLogicOperator(ExpressionType.OrElse, left.type, right.type, method);
  765. return new BinaryExpression(ExpressionType.OrElse, left, right, method, method.ReturnType);
  766. }
  767. public static BinaryExpression OrElse (Expression left, Expression right)
  768. {
  769. return OrElse(left, right, null);
  770. }
  771. #endregion
  772. public static UnaryExpression Quote(Expression expression)
  773. {
  774. if (expression == null)
  775. throw new ArgumentNullException("expression");
  776. return new UnaryExpression(ExpressionType.Quote, expression, expression.GetType());
  777. }
  778. #region Property
  779. public static MemberExpression Property (Expression expression, MethodInfo propertyAccessor)
  780. {
  781. if (propertyAccessor == null)
  782. throw new ArgumentNullException("propertyAccessor");
  783. return Property(expression, GetProperty(propertyAccessor));
  784. }
  785. public static MemberExpression Property (Expression expression, PropertyInfo property)
  786. {
  787. if (property == null)
  788. throw new ArgumentNullException("property");
  789. Type propertyType;
  790. ValidateGettableFieldOrPropertyMember(property, out propertyType);
  791. return new MemberExpression(expression, property, propertyType);
  792. }
  793. public static MemberExpression Property(Expression expression, string propertyName)
  794. {
  795. if (expression == null)
  796. throw new ArgumentNullException ("expression");
  797. if (propertyName == null)
  798. throw new ArgumentNullException ("propertyName");
  799. PropertyInfo property = expression.Type.GetProperty (propertyName,
  800. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
  801. if (property == null)
  802. throw new ArgumentException (String.Format ("{0} is not a member of type {1}",
  803. propertyName, expression.type.FullName));
  804. return Property (expression, property);
  805. }
  806. #endregion
  807. #region PropertyOrField
  808. public static MemberExpression PropertyOrField(Expression expression, string propertyOrFieldName)
  809. {
  810. if (expression == null)
  811. throw new ArgumentNullException ("expression");
  812. if (propertyOrFieldName == null)
  813. throw new ArgumentNullException ("propertyOrFieldName");
  814. PropertyInfo property = expression.type.GetProperty (propertyOrFieldName,
  815. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
  816. if (property != null)
  817. return Property (expression, property);
  818. FieldInfo field = expression.type.GetField (propertyOrFieldName,
  819. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
  820. if (field != null)
  821. return Field (expression, field);
  822. throw new ArgumentException (String.Format ("{0} is not a member of type {1}",
  823. propertyOrFieldName, expression.type.FullName));
  824. }
  825. #endregion
  826. #region Quote
  827. public static UnaryExpression QUote(Expression expression)
  828. {
  829. if (expression == null)
  830. throw new ArgumentNullException ("expression");
  831. return new UnaryExpression (ExpressionType.Quote, expression, expression.GetType());
  832. }
  833. #endregion
  834. #region RightShift
  835. public static BinaryExpression RightShift (Expression left, Expression right, MethodInfo method)
  836. {
  837. if (left == null)
  838. throw new ArgumentNullException ("left");
  839. if (right == null)
  840. throw new ArgumentNullException ("right");
  841. if (method != null)
  842. return new BinaryExpression (ExpressionType.RightShift, left, right, method, method.ReturnType);
  843. // If the left side is any kind of integer and the right is int32 we don't have
  844. // to look for the "op_Addition" method.
  845. if (IsInteger(left.type) && right.type == typeof(Int32))
  846. return new BinaryExpression (ExpressionType.RightShift, left, right, left.type);
  847. // Else we try for a user-defined operator.
  848. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.RightShift, "op_RightShift", left, right);
  849. }
  850. public static BinaryExpression RightShift (Expression left, Expression right)
  851. {
  852. return RightShift (left, right, null);
  853. }
  854. #endregion
  855. #region Subtract
  856. public static BinaryExpression Subtract (Expression left, Expression right, MethodInfo method)
  857. {
  858. if (left == null)
  859. throw new ArgumentNullException ("left");
  860. if (right == null)
  861. throw new ArgumentNullException ("right");
  862. if (method != null)
  863. return new BinaryExpression (ExpressionType.Subtract, left, right, method, method.ReturnType);
  864. // Since both the expressions define the same numeric type we don't have
  865. // to look for the "op_Addition" method.
  866. if (left.type == right.type && IsNumeric (left.type))
  867. return new BinaryExpression (ExpressionType.Subtract, left, right, left.type);
  868. // Else we try for a user-defined operator.
  869. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Subtract, "op_Subtraction", left, right);
  870. }
  871. public static BinaryExpression Subtract (Expression left, Expression right)
  872. {
  873. return Subtract (left, right, null);
  874. }
  875. #endregion
  876. #region SubtractChecked
  877. public static BinaryExpression SubtractChecked (Expression left, Expression right, MethodInfo method)
  878. {
  879. if (left == null)
  880. throw new ArgumentNullException ("left");
  881. if (right == null)
  882. throw new ArgumentNullException ("right");
  883. if (method != null)
  884. return new BinaryExpression (ExpressionType.SubtractChecked, left, right, method, method.ReturnType);
  885. // Since both the expressions define the same numeric type we don't have
  886. // to look for the "op_Addition" method.
  887. if (left.type == right.type && IsNumeric (left.type))
  888. return new BinaryExpression (ExpressionType.SubtractChecked, left, right, left.type);
  889. method = GetUserDefinedBinaryOperator (left.type, right.type, "op_Subtraction");
  890. if (method == null)
  891. throw new InvalidOperationException (String.Format (
  892. "The binary operator AddChecked is not defined for the types '{0}' and '{1}'.", left.type, right.type));
  893. Type retType = method.ReturnType;
  894. return new BinaryExpression (ExpressionType.SubtractChecked, left, right, method, retType);
  895. }
  896. public static BinaryExpression SubtractChecked (Expression left, Expression right)
  897. {
  898. return SubtractChecked (left, right, null);
  899. }
  900. #endregion
  901. #region TypeAs
  902. public static UnaryExpression TypeAs (Expression expression, Type type)
  903. {
  904. if (expression == null)
  905. throw new ArgumentNullException ("expression");
  906. if (type == null)
  907. throw new ArgumentNullException ("type");
  908. return new UnaryExpression (ExpressionType.TypeAs, expression, type);
  909. }
  910. #endregion
  911. #region TypeIs
  912. public static TypeBinaryExpression TypeIs (Expression expression, Type type)
  913. {
  914. if (expression == null)
  915. throw new ArgumentNullException ("expression");
  916. if (type == null)
  917. throw new ArgumentNullException ("type");
  918. return new TypeBinaryExpression (ExpressionType.TypeIs, expression, type, typeof(bool));
  919. }
  920. #endregion
  921. }
  922. }