Expression.cs 47 KB

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