Expression.cs 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162
  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. if (array.type.GetArrayRank () != 1)
  411. throw new ArgumentException ("Argument must be a single dimensional array");
  412. return new UnaryExpression (ExpressionType.ArrayLength, array, typeof (int));
  413. }
  414. #endregion
  415. #region Bind
  416. public static MemberAssignment Bind (MemberInfo member, Expression expression)
  417. {
  418. if (member == null)
  419. throw new ArgumentNullException ("member");
  420. if (expression == null)
  421. throw new ArgumentNullException ("expression");
  422. Type memberType;
  423. ValidateSettableFieldOrPropertyMember(member, out memberType);
  424. return new MemberAssignment(member, expression);
  425. }
  426. public static MemberAssignment Bind (MethodInfo propertyAccessor, Expression expression)
  427. {
  428. if (propertyAccessor == null)
  429. throw new ArgumentNullException ("propertyAccessor");
  430. if (expression == null)
  431. throw new ArgumentNullException ("expression");
  432. return new MemberAssignment(GetProperty(propertyAccessor), expression);
  433. }
  434. #endregion
  435. #region Call
  436. public static MethodCallExpression Call(Expression instance, MethodInfo method)
  437. {
  438. if (method == null)
  439. throw new ArgumentNullException("method");
  440. if (instance == null && !method.IsStatic)
  441. throw new ArgumentNullException("instance");
  442. return Call(instance, method, (Expression[])null);
  443. }
  444. public static MethodCallExpression Call(Expression instance, MethodInfo method, params Expression[] arguments)
  445. {
  446. return Call(instance, method, (IEnumerable<Expression>)arguments);
  447. }
  448. public static MethodCallExpression Call(Expression instance, MethodInfo method, IEnumerable<Expression> arguments)
  449. {
  450. if (method == null)
  451. throw new ArgumentNullException("method");
  452. if (arguments == null)
  453. throw new ArgumentNullException("arguments");
  454. if (instance == null && !method.IsStatic)
  455. throw new ArgumentNullException("instance");
  456. if (method.IsGenericMethodDefinition)
  457. throw new ArgumentException();
  458. if (method.ContainsGenericParameters)
  459. throw new ArgumentException();
  460. if (instance != null && !instance.type.IsAssignableFrom(method.DeclaringType))
  461. throw new ArgumentException();
  462. ReadOnlyCollection<Expression> roArgs = Enumerable.ToReadOnlyCollection<Expression>(arguments);
  463. ParameterInfo[] pars = method.GetParameters();
  464. if (Enumerable.Count<Expression>(arguments) != pars.Length)
  465. throw new ArgumentException();
  466. if (pars.Length > 0)
  467. {
  468. //TODO: validate the parameters against the arguments...
  469. }
  470. return new MethodCallExpression(ExpressionType.Call, method, instance, roArgs);
  471. }
  472. public static MethodCallExpression Call (Expression instance, string methodName, Type [] typeArguments, params Expression [] arguments)
  473. {
  474. if (instance == null)
  475. throw new ArgumentNullException("instance");
  476. if (arguments == null)
  477. throw new ArgumentNullException("arguments");
  478. return Call (null, FindMethod (instance.type, methodName, typeArguments, arguments,
  479. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance),
  480. (IEnumerable<Expression>)arguments);
  481. }
  482. public static MethodCallExpression Call(MethodInfo method, params Expression[] arguments)
  483. {
  484. return Call(null, method, (IEnumerable<Expression>)arguments);
  485. }
  486. public static MethodCallExpression Call (Type type, string methodName, Type [] typeArguments, params Expression [] arguments)
  487. {
  488. if (type == null)
  489. throw new ArgumentNullException ("type");
  490. if (methodName == null)
  491. throw new ArgumentNullException ("methodName");
  492. if (arguments == null)
  493. throw new ArgumentNullException ("arguments");
  494. // Note that we're looking for static methods only (this version of Call() doesn't take an instance).
  495. return Call (null, FindMethod (type, methodName, typeArguments, arguments,
  496. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static),
  497. (IEnumerable<Expression>)arguments);
  498. }
  499. #endregion
  500. // NOTE: CallVirtual is not implemented because it is already marked as Obsolete by MS.
  501. public static ConditionalExpression Condition(Expression test, Expression ifTrue, Expression ifFalse)
  502. {
  503. if (test == null)
  504. throw new ArgumentNullException("test");
  505. if (ifTrue == null)
  506. throw new ArgumentNullException("ifTrue");
  507. if (ifFalse == null)
  508. throw new ArgumentNullException("ifFalse");
  509. if (test.type != typeof(bool))
  510. throw new ArgumentException();
  511. if (ifTrue.type != ifFalse.type)
  512. throw new ArgumentException();
  513. return new ConditionalExpression(test, ifTrue, ifFalse, ifTrue.type);
  514. }
  515. public static ConstantExpression Constant(object value, Type type)
  516. {
  517. if (type == null)
  518. throw new ArgumentNullException("type");
  519. if (value == null && !IsNullableType(type))
  520. throw new ArgumentException("Argument types do not match");
  521. return new ConstantExpression(value, type);
  522. }
  523. public static ConstantExpression Constant(object value)
  524. {
  525. if (value != null)
  526. return new ConstantExpression(value, value.GetType());
  527. else
  528. return new ConstantExpression(null, typeof(object));
  529. }
  530. #region Divide
  531. public static BinaryExpression Divide(Expression left, Expression right, MethodInfo method)
  532. {
  533. if (left == null)
  534. throw new ArgumentNullException ("left");
  535. if (right == null)
  536. throw new ArgumentNullException ("right");
  537. if (method != null)
  538. return new BinaryExpression(ExpressionType.Divide, left, right, method, method.ReturnType);
  539. // Since both the expressions define the same numeric type we don't have
  540. // to look for the "op_Addition" method.
  541. if (left.type == right.type && IsNumeric (left.type))
  542. return new BinaryExpression(ExpressionType.Divide, left, right, left.type);
  543. // Else we try for a user-defined operator.
  544. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Divide, "op_Division", left, right);
  545. }
  546. public static BinaryExpression Divide(Expression left, Expression right)
  547. {
  548. return Divide(left, right, null);
  549. }
  550. #endregion
  551. #region ExclusiveOr
  552. public static BinaryExpression ExclusiveOr (Expression left, Expression right, System.Reflection.MethodInfo method)
  553. {
  554. if (left == null)
  555. throw new ArgumentNullException ("left");
  556. if (right == null)
  557. throw new ArgumentNullException ("right");
  558. if (method != null)
  559. return new BinaryExpression(ExpressionType.ExclusiveOr, left, right, method, method.ReturnType);
  560. // Since both the expressions define the same integer or boolean type we don't have
  561. // to look for the "op_BitwiseAnd" method.
  562. if (left.type == right.type && IsIntegerOrBool (left.type))
  563. return new BinaryExpression(ExpressionType.ExclusiveOr, left, right, left.type);
  564. // Else we try for a user-defined operator.
  565. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.ExclusiveOr, "op_ExclusiveOr", left, right);
  566. }
  567. public static BinaryExpression ExclusiveOr (Expression left, Expression right)
  568. {
  569. return ExclusiveOr (left, right, null);
  570. }
  571. #endregion
  572. #region Field
  573. public static MemberExpression Field (Expression expression, FieldInfo field)
  574. {
  575. // Note that expression can be (and should be) null when the access is to a static field.
  576. if (field == null)
  577. throw new ArgumentNullException("field");
  578. Type fieldType;
  579. ValidateGettableFieldOrPropertyMember(field, out fieldType);
  580. return new MemberExpression(expression, field, fieldType);
  581. }
  582. public static MemberExpression Field (Expression expression, string fieldName)
  583. {
  584. if (expression == null)
  585. throw new ArgumentNullException("expression");
  586. if (fieldName == null)
  587. throw new ArgumentNullException("fieldName");
  588. FieldInfo field = expression.Type.GetField(fieldName,
  589. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
  590. if (field == null)
  591. throw new ArgumentException (String.Format ("Field {0} is not defined for type {1}",
  592. fieldName, expression.type.FullName));
  593. return Field(expression, field);
  594. }
  595. #endregion
  596. public static Type GetActionType (params Type [] typeArgs)
  597. {
  598. if (typeArgs == null)
  599. throw new ArgumentNullException ("typeArgs");
  600. if (typeArgs.Length < 1 || typeArgs.Length > 4)
  601. throw new ArgumentException ("No Action type of this arity");
  602. Type action = null;
  603. switch (typeArgs.Length) {
  604. case 1:
  605. action = typeof (Action<>);
  606. break;
  607. case 2:
  608. action = typeof (Action<,>);
  609. break;
  610. case 3:
  611. action = typeof (Action<,,>);
  612. break;
  613. case 4:
  614. action = typeof (Action<,,,>);
  615. break;
  616. }
  617. return action.MakeGenericType (typeArgs);
  618. }
  619. public static Type GetFuncType (params Type [] typeArgs)
  620. {
  621. if (typeArgs == null)
  622. throw new ArgumentNullException ("typeArgs");
  623. if (typeArgs.Length < 1 || typeArgs.Length > 5)
  624. throw new ArgumentException ("No Func type of this arity");
  625. Type func = null;
  626. switch (typeArgs.Length) {
  627. case 1:
  628. func = typeof (Func<>);
  629. break;
  630. case 2:
  631. func = typeof (Func<,>);
  632. break;
  633. case 3:
  634. func = typeof (Func<,,>);
  635. break;
  636. case 4:
  637. func = typeof (Func<,,,>);
  638. break;
  639. case 5:
  640. func = typeof (Func<,,,,>);
  641. break;
  642. }
  643. return func.MakeGenericType (typeArgs);
  644. }
  645. #region LeftShift
  646. public static BinaryExpression LeftShift (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.LeftShift, left, right, method, method.ReturnType);
  654. // If the left side is any kind of integer and the right is int32 we don't have
  655. // to look for the "op_Addition" method.
  656. if (IsInteger(left.type) && right.type == typeof(Int32))
  657. return new BinaryExpression(ExpressionType.LeftShift, left, right, left.type);
  658. // Else we try for a user-defined operator.
  659. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.LeftShift, "op_LeftShift", left, right);
  660. }
  661. public static BinaryExpression LeftShift (Expression left, Expression right)
  662. {
  663. return LeftShift (left, right, null);
  664. }
  665. #endregion
  666. public static ListInitExpression ListInit(NewExpression newExpression, params ElementInit[] initializers)
  667. {
  668. if (initializers == null)
  669. throw new ArgumentNullException("inizializers");
  670. return ListInit(newExpression, Enumerable.ToReadOnlyCollection<ElementInit>(initializers));
  671. }
  672. public static ListInitExpression ListInit(NewExpression newExpression, IEnumerable<ElementInit> initializers)
  673. {
  674. if (newExpression == null)
  675. throw new ArgumentNullException("newExpression");
  676. if (initializers == null)
  677. throw new ArgumentNullException("inizializers");
  678. return new ListInitExpression(newExpression, Enumerable.ToReadOnlyCollection<ElementInit>(initializers));
  679. }
  680. public static MemberInitExpression MemberInit(NewExpression newExpression, IEnumerable<MemberBinding> bindings)
  681. {
  682. if (newExpression == null)
  683. throw new ArgumentNullException("newExpression");
  684. if (bindings == null)
  685. throw new ArgumentNullException("bindings");
  686. return new MemberInitExpression(newExpression, Enumerable.ToReadOnlyCollection<MemberBinding>(bindings));
  687. }
  688. #region Modulo
  689. public static BinaryExpression Modulo (Expression left, Expression right, MethodInfo method)
  690. {
  691. if (left == null)
  692. throw new ArgumentNullException ("left");
  693. if (right == null)
  694. throw new ArgumentNullException ("right");
  695. if (method != null)
  696. return new BinaryExpression(ExpressionType.Modulo, left, right, method, method.ReturnType);
  697. // Since both the expressions define the same integer or boolean type we don't have
  698. // to look for the "op_BitwiseAnd" method.
  699. if (left.type == right.type && IsNumeric (left.type))
  700. return new BinaryExpression(ExpressionType.Modulo, left, right, left.type);
  701. // Else we try for a user-defined operator.
  702. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Modulo, "op_Modulus", left, right);
  703. }
  704. public static BinaryExpression Modulo (Expression left, Expression right)
  705. {
  706. return Modulo (left, right, null);
  707. }
  708. #endregion
  709. #region Multiply
  710. public static BinaryExpression Multiply (Expression left, Expression right, MethodInfo method)
  711. {
  712. if (left == null)
  713. throw new ArgumentNullException ("left");
  714. if (right == null)
  715. throw new ArgumentNullException ("right");
  716. if (method != null)
  717. return new BinaryExpression(ExpressionType.Multiply, left, right, method, method.ReturnType);
  718. // Since both the expressions define the same integer or boolean type we don't have
  719. // to look for the "op_BitwiseAnd" method.
  720. if (left.type == right.type && IsNumeric (left.type))
  721. return new BinaryExpression(ExpressionType.Multiply, left, right, left.type);
  722. // Else we try for a user-defined operator.
  723. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Multiply, "op_Multiply", left, right);
  724. }
  725. public static BinaryExpression Multiply (Expression left, Expression right)
  726. {
  727. return Multiply (left, right, null);
  728. }
  729. #endregion
  730. #region MultiplyChecked
  731. public static BinaryExpression MultiplyChecked (Expression left, Expression right, MethodInfo method)
  732. {
  733. if (left == null)
  734. throw new ArgumentNullException ("left");
  735. if (right == null)
  736. throw new ArgumentNullException ("right");
  737. if (method != null)
  738. return new BinaryExpression(ExpressionType.MultiplyChecked, left, right, method, method.ReturnType);
  739. // Since both the expressions define the same numeric type we don't have
  740. // to look for the "op_Addition" method.
  741. if (left.type == right.type && IsNumeric (left.type))
  742. return new BinaryExpression(ExpressionType.MultiplyChecked, left, right, left.type);
  743. method = GetUserDefinedBinaryOperator (left.type, right.type, "op_Multiply");
  744. if (method == null)
  745. throw new InvalidOperationException(String.Format(
  746. "The binary operator MultiplyChecked is not defined for the types '{0}' and '{1}'.", left.type, right.type));
  747. Type retType = method.ReturnType;
  748. return new BinaryExpression(ExpressionType.MultiplyChecked, left, right, method, retType);
  749. }
  750. public static BinaryExpression MultiplyChecked (Expression left, Expression right)
  751. {
  752. return MultiplyChecked(left, right, null);
  753. }
  754. #endregion
  755. #region Or
  756. public static BinaryExpression Or (Expression left, Expression right, MethodInfo method)
  757. {
  758. if (left == null)
  759. throw new ArgumentNullException ("left");
  760. if (right == null)
  761. throw new ArgumentNullException ("right");
  762. if (method != null)
  763. return new BinaryExpression(ExpressionType.Or, left, right, method, method.ReturnType);
  764. // Since both the expressions define the same integer or boolean type we don't have
  765. // to look for the "op_BitwiseOr" method.
  766. if (left.type == right.type && IsIntegerOrBool (left.type))
  767. return new BinaryExpression(ExpressionType.Or, left, right, left.type);
  768. // Else we try for a user-defined operator.
  769. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Or, "op_BitwiseOr", left, right);
  770. }
  771. public static BinaryExpression Or (Expression left, Expression right)
  772. {
  773. return Or (left, right, null);
  774. }
  775. #endregion
  776. #region OrElse
  777. public static BinaryExpression OrElse (Expression left, Expression right, MethodInfo method)
  778. {
  779. if (left == null)
  780. throw new ArgumentNullException ("left");
  781. if (right == null)
  782. throw new ArgumentNullException ("right");
  783. // Since both the expressions define the same boolean type we don't have
  784. // to look for the "op_BitwiseOr" method.
  785. if (left.type == right.type && left.type == typeof(bool))
  786. return new BinaryExpression(ExpressionType.OrElse, left, right, left.type);
  787. // Else we must validate the method to make sure it has companion "true" and "false" operators.
  788. if (method == null)
  789. method = GetUserDefinedBinaryOperator (left.type, right.type, "op_BitwiseOr");
  790. if (method == null)
  791. throw new InvalidOperationException(String.Format(
  792. "The binary operator OrElse is not defined for the types '{0}' and '{1}'.", left.type, right.type));
  793. ValidateUserDefinedConditionalLogicOperator(ExpressionType.OrElse, left.type, right.type, method);
  794. return new BinaryExpression(ExpressionType.OrElse, left, right, method, method.ReturnType);
  795. }
  796. public static BinaryExpression OrElse (Expression left, Expression right)
  797. {
  798. return OrElse(left, right, null);
  799. }
  800. #endregion
  801. #region Property
  802. public static MemberExpression Property (Expression expression, MethodInfo propertyAccessor)
  803. {
  804. if (propertyAccessor == null)
  805. throw new ArgumentNullException("propertyAccessor");
  806. return Property(expression, GetProperty(propertyAccessor));
  807. }
  808. public static MemberExpression Property (Expression expression, PropertyInfo property)
  809. {
  810. if (property == null)
  811. throw new ArgumentNullException("property");
  812. Type propertyType;
  813. ValidateGettableFieldOrPropertyMember(property, out propertyType);
  814. return new MemberExpression(expression, property, propertyType);
  815. }
  816. public static MemberExpression Property(Expression expression, string propertyName)
  817. {
  818. if (expression == null)
  819. throw new ArgumentNullException ("expression");
  820. if (propertyName == null)
  821. throw new ArgumentNullException ("propertyName");
  822. PropertyInfo property = expression.Type.GetProperty (propertyName,
  823. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
  824. if (property == null)
  825. throw new ArgumentException (String.Format ("{0} is not a member of type {1}",
  826. propertyName, expression.type.FullName));
  827. return Property (expression, property);
  828. }
  829. #endregion
  830. #region PropertyOrField
  831. public static MemberExpression PropertyOrField(Expression expression, string propertyOrFieldName)
  832. {
  833. if (expression == null)
  834. throw new ArgumentNullException ("expression");
  835. if (propertyOrFieldName == null)
  836. throw new ArgumentNullException ("propertyOrFieldName");
  837. PropertyInfo property = expression.type.GetProperty (propertyOrFieldName,
  838. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
  839. if (property != null)
  840. return Property (expression, property);
  841. FieldInfo field = expression.type.GetField (propertyOrFieldName,
  842. BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
  843. if (field != null)
  844. return Field (expression, field);
  845. throw new ArgumentException (String.Format ("{0} is not a member of type {1}",
  846. propertyOrFieldName, expression.type.FullName));
  847. }
  848. #endregion
  849. #region Quote
  850. public static UnaryExpression Quote(Expression expression)
  851. {
  852. if (expression == null)
  853. throw new ArgumentNullException ("expression");
  854. return new UnaryExpression (ExpressionType.Quote, expression, expression.GetType());
  855. }
  856. #endregion
  857. #region RightShift
  858. public static BinaryExpression RightShift (Expression left, Expression right, MethodInfo method)
  859. {
  860. if (left == null)
  861. throw new ArgumentNullException ("left");
  862. if (right == null)
  863. throw new ArgumentNullException ("right");
  864. if (method != null)
  865. return new BinaryExpression (ExpressionType.RightShift, left, right, method, method.ReturnType);
  866. // If the left side is any kind of integer and the right is int32 we don't have
  867. // to look for the "op_Addition" method.
  868. if (IsInteger(left.type) && right.type == typeof(Int32))
  869. return new BinaryExpression (ExpressionType.RightShift, left, right, left.type);
  870. // Else we try for a user-defined operator.
  871. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.RightShift, "op_RightShift", left, right);
  872. }
  873. public static BinaryExpression RightShift (Expression left, Expression right)
  874. {
  875. return RightShift (left, right, null);
  876. }
  877. #endregion
  878. #region Subtract
  879. public static BinaryExpression Subtract (Expression left, Expression right, MethodInfo method)
  880. {
  881. if (left == null)
  882. throw new ArgumentNullException ("left");
  883. if (right == null)
  884. throw new ArgumentNullException ("right");
  885. if (method != null)
  886. return new BinaryExpression (ExpressionType.Subtract, left, right, method, method.ReturnType);
  887. // Since both the expressions define the same numeric type we don't have
  888. // to look for the "op_Addition" method.
  889. if (left.type == right.type && IsNumeric (left.type))
  890. return new BinaryExpression (ExpressionType.Subtract, left, right, left.type);
  891. // Else we try for a user-defined operator.
  892. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Subtract, "op_Subtraction", left, right);
  893. }
  894. public static BinaryExpression Subtract (Expression left, Expression right)
  895. {
  896. return Subtract (left, right, null);
  897. }
  898. #endregion
  899. #region SubtractChecked
  900. public static BinaryExpression SubtractChecked (Expression left, Expression right, MethodInfo method)
  901. {
  902. if (left == null)
  903. throw new ArgumentNullException ("left");
  904. if (right == null)
  905. throw new ArgumentNullException ("right");
  906. if (method != null)
  907. return new BinaryExpression (ExpressionType.SubtractChecked, left, right, method, method.ReturnType);
  908. // Since both the expressions define the same numeric type we don't have
  909. // to look for the "op_Addition" method.
  910. if (left.type == right.type && IsNumeric (left.type))
  911. return new BinaryExpression (ExpressionType.SubtractChecked, left, right, left.type);
  912. method = GetUserDefinedBinaryOperator (left.type, right.type, "op_Subtraction");
  913. if (method == null)
  914. throw new InvalidOperationException (String.Format (
  915. "The binary operator AddChecked is not defined for the types '{0}' and '{1}'.", left.type, right.type));
  916. Type retType = method.ReturnType;
  917. return new BinaryExpression (ExpressionType.SubtractChecked, left, right, method, retType);
  918. }
  919. public static BinaryExpression SubtractChecked (Expression left, Expression right)
  920. {
  921. return SubtractChecked (left, right, null);
  922. }
  923. #endregion
  924. #region TypeAs
  925. public static UnaryExpression TypeAs (Expression expression, Type type)
  926. {
  927. if (expression == null)
  928. throw new ArgumentNullException ("expression");
  929. if (type == null)
  930. throw new ArgumentNullException ("type");
  931. if (type.IsValueType && !IsNullableType (type))
  932. throw new ArgumentException ("Reference or nullable type expected");
  933. return new UnaryExpression (ExpressionType.TypeAs, expression, type);
  934. }
  935. #endregion
  936. #region TypeIs
  937. public static TypeBinaryExpression TypeIs (Expression expression, Type type)
  938. {
  939. if (expression == null)
  940. throw new ArgumentNullException ("expression");
  941. if (type == null)
  942. throw new ArgumentNullException ("type");
  943. return new TypeBinaryExpression (ExpressionType.TypeIs, expression, type, typeof(bool));
  944. }
  945. #endregion
  946. }
  947. }