Expression.cs 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560
  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 support 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 const BindingFlags opBindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
  77. private static MethodInfo GetUserDefinedBinaryOperator (Type leftType, Type rightType, string name)
  78. {
  79. Type[] types = new Type[2] { leftType, rightType };
  80. MethodInfo method = leftType.GetMethod (name, opBindingFlags, null, types, null);
  81. if (method != null) return method;
  82. method = rightType.GetMethod (name, opBindingFlags, null, types, null);
  83. if (method != null) return method;
  84. if (method == null && IsNullableType(leftType) && IsNullableType(rightType))
  85. return GetUserDefinedBinaryOperator(GetNonNullableType(leftType), GetNonNullableType(rightType), name);
  86. return null;
  87. }
  88. private static BinaryExpression GetUserDefinedBinaryOperatorOrThrow (ExpressionType nodeType, string name,
  89. Expression left, Expression right)
  90. {
  91. MethodInfo method = GetUserDefinedBinaryOperator(left.type, right.type, name);
  92. if (method != null)
  93. return new BinaryExpression (nodeType, left, right, method, method.ReturnType);
  94. else
  95. throw new InvalidOperationException(String.Format(
  96. "The binary operator Add is not defined for the types '{0}' and '{1}'.", left.type, right.type));
  97. // Note: here the code in ExpressionUtils has a series of checks to make sure that
  98. // the method is static, that its return type is not void and that the number of
  99. // parameters is 2 and they are of the right type, but we already know that! Or not?
  100. }
  101. private static void ValidateUserDefinedConditionalLogicOperator (ExpressionType nodeType, Type left, Type right, MethodInfo method)
  102. {
  103. // Conditional logic need the "definitely true" and "definitely false" operators.
  104. Type[] types = new Type[1] { left };
  105. MethodInfo opTrue = left.GetMethod ("op_True", opBindingFlags, null, types, null);
  106. MethodInfo opFalse = left.GetMethod ("op_False", opBindingFlags, null, types, null);
  107. if (opTrue == null || opFalse == null)
  108. throw new ArgumentException(String.Format(
  109. "The user-defined operator method '{0}' for operator '{1}' must have associated boolean True and False operators.",
  110. method.Name, nodeType));
  111. }
  112. #endregion
  113. #region ToString
  114. public override string ToString()
  115. {
  116. StringBuilder builder = new StringBuilder ();
  117. BuildString (builder);
  118. return builder.ToString ();
  119. }
  120. #endregion
  121. #region Add
  122. public static BinaryExpression Add(Expression left, Expression right, MethodInfo method)
  123. {
  124. if (left == null)
  125. throw new ArgumentNullException ("left");
  126. if (right == null)
  127. throw new ArgumentNullException ("right");
  128. if (method != null)
  129. return new BinaryExpression(ExpressionType.Add, left, right, method, method.ReturnType);
  130. // Since both the expressions define the same numeric type we don't have
  131. // to look for the "op_Addition" method.
  132. if (left.type == right.type && ExpressionUtil.IsNumber(left.type))
  133. return new BinaryExpression(ExpressionType.Add, left, right, left.type);
  134. // Else we try for a user-defined operator.
  135. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.Add, "op_Addition", left, right);
  136. }
  137. public static BinaryExpression Add(Expression left, Expression right)
  138. {
  139. return Add(left, right, null);
  140. }
  141. #endregion
  142. #region AddChecked
  143. public static BinaryExpression AddChecked(Expression left, Expression right, MethodInfo method)
  144. {
  145. if (left == null)
  146. throw new ArgumentNullException ("left");
  147. if (right == null)
  148. throw new ArgumentNullException ("right");
  149. if (method != null)
  150. return new BinaryExpression(ExpressionType.AddChecked, left, right, method, method.ReturnType);
  151. // Since both the expressions define the same numeric type we don't have
  152. // to look for the "op_Addition" method.
  153. if (left.type == right.type && ExpressionUtil.IsNumber(left.type))
  154. return new BinaryExpression(ExpressionType.AddChecked, left, right, left.type);
  155. method = GetUserDefinedBinaryOperator (left.type, right.type, "op_Addition");
  156. if (method == null)
  157. throw new InvalidOperationException(String.Format(
  158. "The binary operator AddChecked is not defined for the types '{0}' and '{1}'.", left.type, right.type));
  159. Type retType = method.ReturnType;
  160. // Note: here the code did some very strange checks for bool (but note that bool does
  161. // not define an addition operator) and created nullables for value types (but the new
  162. // MS code does not do that). All that has been removed.
  163. return new BinaryExpression(ExpressionType.AddChecked, left, right, method, retType);
  164. }
  165. public static BinaryExpression AddChecked(Expression left, Expression right)
  166. {
  167. return AddChecked(left, right, null);
  168. }
  169. #endregion
  170. #region And
  171. public static BinaryExpression And(Expression left, Expression right, MethodInfo method)
  172. {
  173. if (left == null)
  174. throw new ArgumentNullException ("left");
  175. if (right == null)
  176. throw new ArgumentNullException ("right");
  177. if (method != null)
  178. return new BinaryExpression(ExpressionType.And, left, right, method, method.ReturnType);
  179. // Since both the expressions define the same integer or boolean type we don't have
  180. // to look for the "op_BitwiseAnd" method.
  181. if (left.type == right.type && (ExpressionUtil.IsInteger(left.type) || left.type == typeof(bool)))
  182. return new BinaryExpression(ExpressionType.And, left, right, left.type);
  183. // Else we try for a user-defined operator.
  184. return GetUserDefinedBinaryOperatorOrThrow (ExpressionType.And, "op_BitwiseAnd", left, right);
  185. }
  186. public static BinaryExpression And(Expression left, Expression right)
  187. {
  188. return And(left, right, null);
  189. }
  190. #endregion
  191. #region AndAlso
  192. public static BinaryExpression AndAlso(Expression left, Expression right, MethodInfo method)
  193. {
  194. if (left == null)
  195. throw new ArgumentNullException ("left");
  196. if (right == null)
  197. throw new ArgumentNullException ("right");
  198. // Since both the expressions define the same integer or boolean type we don't have
  199. // to look for the "op_BitwiseAnd" method.
  200. if (left.type == right.type && left.type == typeof(bool))
  201. return new BinaryExpression(ExpressionType.AndAlso, left, right, left.type);
  202. // Else we must validate the method to make sure it has companion "true" and "false" operators.
  203. if (method == null)
  204. method = GetUserDefinedBinaryOperator (left.type, right.type, "op_BitwiseAnd");
  205. if (method == null)
  206. throw new InvalidOperationException(String.Format(
  207. "The binary operator AndAlso is not defined for the types '{0}' and '{1}'.", left.type, right.type));
  208. ValidateUserDefinedConditionalLogicOperator(ExpressionType.AndAlso, left.type, right.type, method);
  209. return new BinaryExpression(ExpressionType.AndAlso, left, right, method, method.ReturnType);
  210. }
  211. public static BinaryExpression AndAlso(Expression left, Expression right)
  212. {
  213. return AndAlso(left, right, null);
  214. }
  215. #endregion
  216. #region ArrayIndex
  217. public static MethodCallExpression ArrayIndex(Expression array, Expression index)
  218. {
  219. throw new NotImplementedException();
  220. }
  221. public static MethodCallExpression ArrayIndex(Expression array, params Expression[] indexes)
  222. {
  223. throw new NotImplementedException();
  224. }
  225. public static MethodCallExpression ArrayIndex(Expression array, IEnumerable<Expression> indexes)
  226. {
  227. throw new NotImplementedException();
  228. }
  229. #endregion
  230. public static MethodCallExpression Call(Expression instance, MethodInfo method)
  231. {
  232. return Call(instance, method, (Expression[])null);
  233. }
  234. public static MethodCallExpression Call(MethodInfo method, params Expression[] arguments)
  235. {
  236. return Call(null, method, Enumerable.ToReadOnlyCollection<Expression>(arguments));
  237. }
  238. public static MethodCallExpression Call(Expression instance, MethodInfo method, params Expression[] arguments)
  239. {
  240. return Call(instance, method, Enumerable.ToReadOnlyCollection<Expression>(arguments));
  241. }
  242. public static MethodCallExpression Call(Expression instance, MethodInfo method, IEnumerable<Expression> arguments)
  243. {
  244. if (arguments == null)
  245. throw new ArgumentNullException("arguments");
  246. if (method == null)
  247. throw new ArgumentNullException("method");
  248. if (method.IsGenericMethodDefinition)
  249. throw new ArgumentException();
  250. if (method.ContainsGenericParameters)
  251. throw new ArgumentException();
  252. if (!method.IsStatic && instance == null)
  253. throw new ArgumentNullException("instance");
  254. if (instance != null && !instance.type.IsAssignableFrom(method.DeclaringType))
  255. throw new ArgumentException();
  256. ReadOnlyCollection<Expression> roArgs = Enumerable.ToReadOnlyCollection<Expression>(arguments);
  257. ParameterInfo[] pars = method.GetParameters();
  258. if (Enumerable.Count<Expression>(arguments) != pars.Length)
  259. throw new ArgumentException();
  260. if (pars.Length > 0)
  261. {
  262. //TODO: validate the parameters against the arguments...
  263. }
  264. return new MethodCallExpression(ExpressionType.Call, method, instance, roArgs);
  265. }
  266. // NOTE: CallVirtual is not implemented because it is already marked as Obsolete by MS.
  267. public static ConditionalExpression Condition(Expression test, Expression ifTrue, Expression ifFalse)
  268. {
  269. if (test == null)
  270. throw new ArgumentNullException("test");
  271. if (ifTrue == null)
  272. throw new ArgumentNullException("ifTrue");
  273. if (ifFalse == null)
  274. throw new ArgumentNullException("ifFalse");
  275. if (test.type != typeof(bool))
  276. throw new ArgumentException();
  277. if (ifTrue.type != ifFalse.type)
  278. throw new ArgumentException();
  279. return new ConditionalExpression(test, ifTrue, ifFalse, ifTrue.type);
  280. }
  281. public static ConstantExpression Constant(object value, Type type)
  282. {
  283. if (type == null)
  284. throw new ArgumentNullException("type");
  285. if (value == null && !IsNullableType(type))
  286. throw new ArgumentException("Argument types do not match");
  287. return new ConstantExpression(value, type);
  288. }
  289. public static ConstantExpression Constant(object value)
  290. {
  291. if (value != null)
  292. return new ConstantExpression(value, value.GetType());
  293. else
  294. return new ConstantExpression(null, typeof(object));
  295. }
  296. public static BinaryExpression Divide(Expression left, Expression right)
  297. {
  298. return Divide(left, right, null);
  299. }
  300. public static BinaryExpression Divide(Expression left, Expression right, MethodInfo method)
  301. {
  302. if (left == null)
  303. throw new ArgumentNullException("left");
  304. if (right == null)
  305. throw new ArgumentNullException("right");
  306. // sine both the expressions define the same numeric type we don't have
  307. // to look for the "op_Division" method...
  308. if (left.type == right.type &&
  309. ExpressionUtil.IsNumber(left.type))
  310. return new BinaryExpression(ExpressionType.Divide, left, right, left.type);
  311. if (method == null)
  312. method = ExpressionUtil.GetOperatorMethod("op_Division", left.type, right.type);
  313. // ok if even op_Division is not defined we need to throw an exception...
  314. if (method == null)
  315. throw new InvalidOperationException();
  316. return new BinaryExpression(ExpressionType.Divide, left, right, method, method.ReturnType);
  317. }
  318. public static MemberExpression Field(Expression expression, FieldInfo field)
  319. {
  320. if (field == null)
  321. throw new ArgumentNullException("field");
  322. return new MemberExpression(expression, field, field.FieldType);
  323. }
  324. public static MemberExpression Field(Expression expression, string fieldName)
  325. {
  326. if (expression == null)
  327. throw new ArgumentNullException("expression");
  328. FieldInfo field = expression.Type.GetField(fieldName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
  329. if (field == null)
  330. throw new ArgumentException();
  331. return Field(expression, field);
  332. }
  333. public static FuncletExpression Funclet(Funclet funclet, Type type)
  334. {
  335. if (funclet == null)
  336. throw new ArgumentNullException("funclet");
  337. if (type == null)
  338. throw new ArgumentNullException("type");
  339. return new FuncletExpression(funclet, type);
  340. }
  341. public static Type GetFuncType(params Type[] typeArgs)
  342. {
  343. if (typeArgs == null)
  344. throw new ArgumentNullException("typeArgs");
  345. if (typeArgs.Length > 5)
  346. throw new ArgumentException();
  347. return typeof(Func<,,,,>).MakeGenericType(typeArgs);
  348. }
  349. public static BinaryExpression LeftShift(Expression left, Expression right, MethodInfo method)
  350. {
  351. if (left == null)
  352. throw new ArgumentNullException("left");
  353. if (right == null)
  354. throw new ArgumentNullException("right");
  355. // since the left expression is of an integer type and the right is of
  356. // an integer we don't have to look for the "op_LeftShift" method...
  357. if (ExpressionUtil.IsInteger(left.type) && right.type == typeof(int))
  358. return new BinaryExpression(ExpressionType.LeftShift, left, right, left.type);
  359. if (method == null)
  360. method = ExpressionUtil.GetOperatorMethod("op_LeftShift", left.type, right.type);
  361. // ok if even op_Division is not defined we need to throw an exception...
  362. if (method == null)
  363. throw new InvalidOperationException();
  364. return new BinaryExpression(ExpressionType.LeftShift, left, right, method, method.ReturnType);
  365. }
  366. public static BinaryExpression LeftShift(Expression left, Expression right)
  367. {
  368. return LeftShift(left, right, null);
  369. }
  370. public static ListInitExpression ListInit(NewExpression newExpression, params Expression[] initializers)
  371. {
  372. if (initializers == null)
  373. throw new ArgumentNullException("inizializers");
  374. return ListInit(newExpression, Enumerable.ToReadOnlyCollection<Expression>(initializers));
  375. }
  376. public static ListInitExpression ListInit(NewExpression newExpression, IEnumerable<Expression> initializers)
  377. {
  378. if (newExpression == null)
  379. throw new ArgumentNullException("newExpression");
  380. if (initializers == null)
  381. throw new ArgumentNullException("inizializers");
  382. return new ListInitExpression(newExpression, Enumerable.ToReadOnlyCollection<Expression>(initializers));
  383. }
  384. public static MemberInitExpression MemberInit(NewExpression newExpression, IEnumerable<MemberBinding> bindings)
  385. {
  386. if (newExpression == null)
  387. throw new ArgumentNullException("newExpression");
  388. if (bindings == null)
  389. throw new ArgumentNullException("bindings");
  390. return new MemberInitExpression(newExpression, Enumerable.ToReadOnlyCollection<MemberBinding>(bindings));
  391. }
  392. public static MemberExpression Property(Expression expression, PropertyInfo property)
  393. {
  394. if (property == null)
  395. throw new ArgumentNullException("property");
  396. MethodInfo getMethod = property.GetGetMethod(true);
  397. if (getMethod == null)
  398. throw new ArgumentException(); // to access the property we need to have
  399. // a get method...
  400. return new MemberExpression(expression, property, property.PropertyType);
  401. }
  402. public static UnaryExpression Quote(Expression expression)
  403. {
  404. if (expression == null)
  405. throw new ArgumentNullException("expression");
  406. return new UnaryExpression(ExpressionType.Quote, expression, expression.GetType());
  407. }
  408. public static MemberExpression Property(Expression expression, string propertyName)
  409. {
  410. if (expression == null)
  411. throw new ArgumentNullException("expression");
  412. PropertyInfo property = expression.Type.GetProperty(propertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
  413. if (property == null)
  414. throw new ArgumentException();
  415. return Property(expression, property);
  416. }
  417. public static MemberExpression PropertyOrField(Expression expression, string propertyOrFieldName)
  418. {
  419. if (expression == null)
  420. throw new ArgumentNullException("expression");
  421. PropertyInfo property = expression.Type.GetProperty(propertyOrFieldName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
  422. if (property != null)
  423. return Property(expression, property);
  424. FieldInfo field = expression.Type.GetField(propertyOrFieldName, BindingFlags.Public | BindingFlags.Instance | BindingFlags.NonPublic);
  425. if (field != null)
  426. return Field(expression, field);
  427. //TODO: should we return <null> here?
  428. // the name is not defined in the Type of the expression given...
  429. throw new ArgumentException();
  430. }
  431. public static TypeBinaryExpression TypeIs(Expression expression, Type type)
  432. {
  433. if (expression == null)
  434. throw new ArgumentNullException("expression");
  435. if (type == null)
  436. throw new ArgumentNullException("type");
  437. return new TypeBinaryExpression(ExpressionType.TypeIs, expression, type, typeof(bool));
  438. }
  439. public static UnaryExpression TypeAs(Expression expression, Type type)
  440. {
  441. if (expression == null)
  442. throw new ArgumentNullException("expression");
  443. if (type == null)
  444. throw new ArgumentNullException("type");
  445. return new UnaryExpression(ExpressionType.TypeAs, expression, type);
  446. }
  447. }
  448. }