Expression.cs 38 KB

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