Expression.cs 55 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791
  1. //
  2. // Expression.cs
  3. //
  4. // Author:
  5. // Jb Evain ([email protected])
  6. // Miguel de Icaza ([email protected])
  7. //
  8. // (C) 2008 Novell, Inc. (http://www.novell.com)
  9. //
  10. // Permission is hereby granted, free of charge, to any person obtaining
  11. // a copy of this software and associated documentation files (the
  12. // "Software"), to deal in the Software without restriction, including
  13. // without limitation the rights to use, copy, modify, merge, publish,
  14. // distribute, sublicense, and/or sell copies of the Software, and to
  15. // permit persons to whom the Software is furnished to do so, subject to
  16. // the following conditions:
  17. //
  18. // The above copyright notice and this permission notice shall be
  19. // included in all copies or substantial portions of the Software.
  20. //
  21. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  22. // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  23. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  24. // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  25. // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  26. // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  27. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  28. //
  29. using System;
  30. using System.Collections;
  31. using System.Collections.Generic;
  32. using System.Collections.ObjectModel;
  33. using System.Linq;
  34. using System.Reflection;
  35. namespace System.Linq.Expressions {
  36. public abstract class Expression {
  37. ExpressionType node_type;
  38. Type type;
  39. static BindingFlags PublicInstance = BindingFlags.Public | BindingFlags.Instance;
  40. static BindingFlags PublicStatic = BindingFlags.Public | BindingFlags.Static;
  41. static BindingFlags AllInstance = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
  42. static BindingFlags AllStatic = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
  43. static BindingFlags All = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;
  44. public ExpressionType NodeType {
  45. get { return node_type; }
  46. }
  47. public Type Type {
  48. get { return type; }
  49. }
  50. protected Expression (ExpressionType node_type, Type type)
  51. {
  52. this.node_type = node_type;
  53. this.type = type;
  54. }
  55. public override string ToString ()
  56. {
  57. return ExpressionPrinter.ToString (this);
  58. }
  59. static void CheckMethod (MethodInfo m)
  60. {
  61. }
  62. #region Binary Expressions
  63. static bool IsInt (Type t)
  64. {
  65. return t == typeof (byte) || t == typeof (sbyte) ||
  66. t == typeof (short) || t == typeof (ushort) ||
  67. t == typeof (int) || t == typeof (uint) ||
  68. t == typeof (long) || t == typeof (ulong);
  69. }
  70. static bool IsNumber (Type t)
  71. {
  72. if (IsInt (t))
  73. return true;
  74. return t == typeof (float) || t == typeof (double) || t == typeof (decimal);
  75. }
  76. static MethodInfo GetUnaryOperator (string oper_name, Type on_type, Expression expression)
  77. {
  78. var methods = on_type.GetMethods (PublicStatic);
  79. foreach (var method in methods) {
  80. if (method.Name != oper_name)
  81. continue;
  82. var parameters = method.GetParameters ();
  83. if (parameters.Length != 1)
  84. continue;
  85. if (!parameters [0].ParameterType.IsAssignableFrom (expression.Type))
  86. continue;
  87. return method;
  88. }
  89. return null;
  90. }
  91. static MethodInfo UnaryCoreCheck (string oper_name, Expression expression, MethodInfo method)
  92. {
  93. if (expression == null)
  94. throw new ArgumentNullException ("expression");
  95. if (method != null) {
  96. if (method.ReturnType == typeof (void))
  97. throw new ArgumentException ("Specified method must return a value", "method");
  98. if (!method.IsStatic)
  99. throw new ArgumentException ("Method must be static", "method");
  100. var parameters = method.GetParameters ();
  101. if (parameters.Length != 1)
  102. throw new ArgumentException ("Must have only one parameters", "method");
  103. if (!parameters [0].ParameterType.IsAssignableFrom (expression.Type))
  104. throw new InvalidOperationException ("left-side argument type does not match left expression type");
  105. return method;
  106. } else {
  107. if (IsNumber (expression.Type))
  108. return null;
  109. if (oper_name != null) {
  110. method = GetUnaryOperator (oper_name, expression.Type, expression);
  111. if (method != null)
  112. return method;
  113. }
  114. throw new InvalidOperationException (
  115. String.Format ("Operation {0} not defined for {1}", oper_name != null ? oper_name.Substring (3) : "is", expression.Type));
  116. }
  117. }
  118. static MethodInfo GetBinaryOperator (string oper_name, Type on_type, Expression left, Expression right)
  119. {
  120. MethodInfo [] methods = on_type.GetMethods (PublicStatic);
  121. foreach (MethodInfo m in methods){
  122. if (m.Name != oper_name)
  123. continue;
  124. ParameterInfo [] pi = m.GetParameters ();
  125. if (pi.Length != 2)
  126. continue;
  127. if (!pi [0].ParameterType.IsAssignableFrom (left.Type))
  128. continue;
  129. if (!pi [1].ParameterType.IsAssignableFrom (right.Type))
  130. continue;
  131. // Method has papers in order.
  132. return m;
  133. }
  134. return null;
  135. }
  136. //
  137. // Performs basic checks on the incoming expressions for binary expressions
  138. // and any provided MethodInfo.
  139. //
  140. static MethodInfo BinaryCoreCheck (string oper_name, Expression left, Expression right, MethodInfo method)
  141. {
  142. if (left == null)
  143. throw new ArgumentNullException ("left");
  144. if (right == null)
  145. throw new ArgumentNullException ("right");
  146. if (method != null){
  147. if (method.ReturnType == typeof (void))
  148. throw new ArgumentException ("Specified method must return a value", "method");
  149. if (!method.IsStatic)
  150. throw new ArgumentException ("Method must be static", "method");
  151. ParameterInfo [] pi = method.GetParameters ();
  152. if (pi.Length != 2)
  153. throw new ArgumentException ("Must have only two parameters", "method");
  154. Type ltype = left.Type.IsValueType && IsNullable (left.Type) ? GetNullableOf(left.Type) : left.Type;
  155. Type rtype = left.Type.IsValueType && IsNullable (right.Type) ? GetNullableOf(right.Type) :right.Type;
  156. if (ltype != pi [0].ParameterType)
  157. throw new InvalidOperationException ("left-side argument type does not match left expression type");
  158. if (rtype != pi [1].ParameterType)
  159. throw new InvalidOperationException ("right-side argument type does not match right expression type");
  160. return method;
  161. } else {
  162. Type ltype = left.Type;
  163. Type rtype = right.Type;
  164. Type ultype = left.Type;
  165. Type urtype = right.Type;
  166. if (IsNullable (ltype))
  167. ultype = GetNullableOf (ltype);
  168. if (IsNullable (rtype))
  169. urtype = GetNullableOf (rtype);
  170. if (oper_name == "op_BitwiseOr" || oper_name == "op_BitwiseAnd"){
  171. if (ultype == typeof (bool)){
  172. if (ultype == urtype && ltype == rtype)
  173. return null;
  174. }
  175. }
  176. // Use IsNumber to avoid expensive reflection.
  177. if (IsNumber (ultype)){
  178. if (ultype == urtype && ltype == rtype)
  179. return method;
  180. if (oper_name != null){
  181. method = GetBinaryOperator (oper_name, rtype, left, right);
  182. if (method != null)
  183. return method;
  184. }
  185. }
  186. if (oper_name != null){
  187. method = GetBinaryOperator (oper_name, ltype, left, right);
  188. if (method != null)
  189. return method;
  190. }
  191. //
  192. // == and != allow reference types without operators defined.
  193. //
  194. if (!ltype.IsValueType && !rtype.IsValueType &&
  195. (oper_name == "op_Equality" || oper_name == "op_Inequality"))
  196. return null;
  197. throw new InvalidOperationException (
  198. String.Format ("Operation {0} not defined for {1} and {2}", oper_name != null ? oper_name.Substring (3) : "is", ltype, rtype));
  199. }
  200. }
  201. //
  202. // This is like BinaryCoreCheck, but if no method is used adds the restriction that
  203. // only ints and bools are allowed
  204. //
  205. static MethodInfo BinaryBitwiseCoreCheck (string oper_name, Expression left, Expression right, MethodInfo method)
  206. {
  207. if (left == null)
  208. throw new ArgumentNullException ("left");
  209. if (right == null)
  210. throw new ArgumentNullException ("right");
  211. if (method == null){
  212. // avoid reflection shortcut and catches Ints/bools before we check Numbers in general
  213. if (left.Type == right.Type && (left.Type == typeof (bool) || IsInt (left.Type)))
  214. return method;
  215. }
  216. method = BinaryCoreCheck (oper_name, left, right, method);
  217. if (method == null){
  218. //
  219. // The check in BinaryCoreCheck allows a bit more than we do
  220. // (floats and doubles). Catch this here
  221. //
  222. if (left.Type == typeof(double) || left.Type == typeof(float))
  223. throw new InvalidOperationException ("Types not supported");
  224. }
  225. return method;
  226. }
  227. static BinaryExpression MakeSimpleBinary (ExpressionType et, Expression left, Expression right, MethodInfo method)
  228. {
  229. Type result = method == null ? left.Type : method.ReturnType;
  230. bool is_lifted;
  231. if (method == null){
  232. if (IsNullable (left.Type)){
  233. if (!IsNullable (right.Type))
  234. throw new Exception ("Assertion, internal error: left is nullable, requires right to be as well");
  235. is_lifted = true;
  236. } else
  237. is_lifted = false;
  238. } else {
  239. //
  240. // FIXME: implement
  241. //
  242. is_lifted = false;
  243. }
  244. return new BinaryExpression (et, result, left, right, false, is_lifted, method, null);
  245. }
  246. static UnaryExpression MakeSimpleUnary (ExpressionType et, Expression expression, MethodInfo method)
  247. {
  248. Type result = method == null ? expression.Type : method.ReturnType;
  249. return new UnaryExpression (et, expression, result, method);
  250. }
  251. static BinaryExpression MakeBoolBinary (ExpressionType et, Expression left, Expression right, bool liftToNull, MethodInfo method)
  252. {
  253. Type result;
  254. Type ltype = left.Type;
  255. Type rtype = right.Type;
  256. bool lnullable = IsNullable (ltype);
  257. bool rnullable = IsNullable (rtype);
  258. bool is_lifted;
  259. //
  260. // Implement the rules as described in "Expression.Equal" method.
  261. //
  262. if (method == null){
  263. if (lnullable == false && rnullable == false){
  264. is_lifted = false;
  265. result = typeof (bool);
  266. } else if (lnullable && rnullable){
  267. is_lifted = true;
  268. result = liftToNull ? typeof(bool?) : typeof (bool);
  269. } else
  270. throw new Exception ("Internal error: this should have been caught in BinaryCoreCheck");
  271. } else {
  272. ParameterInfo [] pi = method.GetParameters ();
  273. Type mltype = pi [0].ParameterType;
  274. Type mrtype = pi [1].ParameterType;
  275. if (ltype == mltype && rtype == mrtype){
  276. is_lifted = false;
  277. result = method.ReturnType;
  278. }
  279. else if (ltype.IsValueType && rtype.IsValueType &&
  280. ((lnullable && GetNullableOf (ltype) == mltype) ||
  281. (rnullable && GetNullableOf (rtype) == mrtype))){
  282. is_lifted = true;
  283. if (method.ReturnType == typeof(bool)){
  284. result = liftToNull ? typeof(bool?) : typeof(bool);
  285. } else {
  286. //
  287. // This behavior is not documented: what
  288. // happens if the result is not typeof(bool), but
  289. // the parameters are nullable: the result
  290. // becomes nullable<returntype>
  291. //
  292. // See:
  293. // https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=323139
  294. result = typeof (Nullable<>).MakeGenericType (method.ReturnType);
  295. //Type.GetType ("System.Nullable`1[" + method.ReturnType.ToString () + "]");
  296. }
  297. } else {
  298. is_lifted = false;
  299. result = method.ReturnType;
  300. }
  301. }
  302. return new BinaryExpression (et, result, left, right, liftToNull, is_lifted, method, null);
  303. }
  304. //
  305. // Arithmetic
  306. //
  307. public static BinaryExpression Add (Expression left, Expression right)
  308. {
  309. return Add (left, right, null);
  310. }
  311. public static BinaryExpression Add (Expression left, Expression right, MethodInfo method)
  312. {
  313. method = BinaryCoreCheck ("op_Addition", left, right, method);
  314. return MakeSimpleBinary (ExpressionType.Add, left, right, method);
  315. }
  316. public static BinaryExpression AddChecked (Expression left, Expression right)
  317. {
  318. return AddChecked (left, right, null);
  319. }
  320. public static BinaryExpression AddChecked (Expression left, Expression right, MethodInfo method)
  321. {
  322. method = BinaryCoreCheck ("op_Addition", left, right, method);
  323. //
  324. // The check in BinaryCoreCheck allows a bit more than we do
  325. // (byte, sbyte). Catch that here
  326. //
  327. if (method == null){
  328. Type ltype = left.Type;
  329. if (ltype == typeof (byte) || ltype == typeof (sbyte))
  330. throw new InvalidOperationException (String.Format ("AddChecked not defined for {0} and {1}", left.Type, right.Type));
  331. }
  332. return MakeSimpleBinary (ExpressionType.AddChecked, left, right, method);
  333. }
  334. public static BinaryExpression Subtract (Expression left, Expression right)
  335. {
  336. return Subtract (left, right, null);
  337. }
  338. public static BinaryExpression Subtract (Expression left, Expression right, MethodInfo method)
  339. {
  340. method = BinaryCoreCheck ("op_Subtraction", left, right, method);
  341. return MakeSimpleBinary (ExpressionType.Subtract, left, right, method);
  342. }
  343. public static BinaryExpression SubtractChecked (Expression left, Expression right)
  344. {
  345. return SubtractChecked (left, right, null);
  346. }
  347. public static BinaryExpression SubtractChecked (Expression left, Expression right, MethodInfo method)
  348. {
  349. method = BinaryCoreCheck ("op_Subtraction", left, right, method);
  350. //
  351. // The check in BinaryCoreCheck allows a bit more than we do
  352. // (byte, sbyte). Catch that here
  353. //
  354. if (method == null){
  355. Type ltype = left.Type;
  356. if (ltype == typeof (byte) || ltype == typeof (sbyte))
  357. throw new InvalidOperationException (String.Format ("SubtractChecked not defined for {0} and {1}", left.Type, right.Type));
  358. }
  359. return MakeSimpleBinary (ExpressionType.SubtractChecked, left, right, method);
  360. }
  361. public static BinaryExpression Modulo (Expression left, Expression right)
  362. {
  363. return Modulo (left, right, null);
  364. }
  365. public static BinaryExpression Modulo (Expression left, Expression right, MethodInfo method)
  366. {
  367. method = BinaryCoreCheck ("op_Modulus", left, right, method);
  368. return MakeSimpleBinary (ExpressionType.Modulo, left, right, method);
  369. }
  370. public static BinaryExpression Multiply (Expression left, Expression right)
  371. {
  372. return Multiply (left, right, null);
  373. }
  374. public static BinaryExpression Multiply (Expression left, Expression right, MethodInfo method)
  375. {
  376. method = BinaryCoreCheck ("op_Multiply", left, right, method);
  377. return MakeSimpleBinary (ExpressionType.Multiply, left, right, method);
  378. }
  379. public static BinaryExpression MultiplyChecked (Expression left, Expression right)
  380. {
  381. return MultiplyChecked (left, right, null);
  382. }
  383. public static BinaryExpression MultiplyChecked (Expression left, Expression right, MethodInfo method)
  384. {
  385. method = BinaryCoreCheck ("op_Multiply", left, right, method);
  386. return MakeSimpleBinary (ExpressionType.MultiplyChecked, left, right, method);
  387. }
  388. public static BinaryExpression Divide (Expression left, Expression right)
  389. {
  390. return Divide (left, right, null);
  391. }
  392. public static BinaryExpression Divide (Expression left, Expression right, MethodInfo method)
  393. {
  394. method = BinaryCoreCheck ("op_Division", left, right, method);
  395. return MakeSimpleBinary (ExpressionType.Divide, left, right, method);
  396. }
  397. public static BinaryExpression Power (Expression left, Expression right)
  398. {
  399. return Power (left, right, null);
  400. }
  401. public static BinaryExpression Power (Expression left, Expression right, MethodInfo method)
  402. {
  403. method = BinaryCoreCheck (null, left, right, method);
  404. if (left.Type != typeof (double))
  405. throw new InvalidOperationException ("Power only supports double arguments");
  406. return MakeSimpleBinary (ExpressionType.Power, left, right, method);
  407. }
  408. //
  409. // Bitwise
  410. //
  411. public static BinaryExpression And (Expression left, Expression right)
  412. {
  413. return And (left, right, null);
  414. }
  415. public static BinaryExpression And (Expression left, Expression right, MethodInfo method)
  416. {
  417. method = BinaryBitwiseCoreCheck ("op_BitwiseAnd", left, right, method);
  418. return MakeSimpleBinary (ExpressionType.And, left, right, method);
  419. }
  420. public static BinaryExpression Or (Expression left, Expression right)
  421. {
  422. return Or (left, right, null);
  423. }
  424. public static BinaryExpression Or (Expression left, Expression right, MethodInfo method)
  425. {
  426. method = BinaryBitwiseCoreCheck ("op_BitwiseOr", left, right, method);
  427. return MakeSimpleBinary (ExpressionType.Or, left, right, method);
  428. }
  429. public static BinaryExpression ExclusiveOr (Expression left, Expression right)
  430. {
  431. return ExclusiveOr (left, right, null);
  432. }
  433. public static BinaryExpression ExclusiveOr (Expression left, Expression right, MethodInfo method)
  434. {
  435. method = BinaryBitwiseCoreCheck ("op_ExclusiveOr", left, right, method);
  436. return MakeSimpleBinary (ExpressionType.ExclusiveOr, left, right, method);
  437. }
  438. public static BinaryExpression LeftShift (Expression left, Expression right)
  439. {
  440. return LeftShift (left, right, null);
  441. }
  442. public static BinaryExpression LeftShift (Expression left, Expression right, MethodInfo method)
  443. {
  444. method = BinaryBitwiseCoreCheck ("op_LeftShift", left, right, method);
  445. return MakeSimpleBinary (ExpressionType.LeftShift, left, right, method);
  446. }
  447. public static BinaryExpression RightShift (Expression left, Expression right)
  448. {
  449. return RightShift (left, right, null);
  450. }
  451. public static BinaryExpression RightShift (Expression left, Expression right, MethodInfo method)
  452. {
  453. method = BinaryCoreCheck ("op_RightShift", left, right, method);
  454. return MakeSimpleBinary (ExpressionType.RightShift, left, right, method);
  455. }
  456. //
  457. // Short-circuit
  458. //
  459. public static BinaryExpression AndAlso (Expression left, Expression right)
  460. {
  461. return AndAlso (left, right, null);
  462. }
  463. public static BinaryExpression AndAlso (Expression left, Expression right, MethodInfo method)
  464. {
  465. method = ConditionalBinaryCheck ("op_BitwiseAnd", left, right, method);
  466. return MakeBoolBinary (ExpressionType.AndAlso, left, right, false, method);
  467. }
  468. static MethodInfo ConditionalBinaryCheck (string oper, Expression left, Expression right, MethodInfo method)
  469. {
  470. method = BinaryCoreCheck (oper, left, right, method);
  471. if (method == null) {
  472. if (left.Type != typeof (bool))
  473. throw new InvalidOperationException ("Only booleans are allowed");
  474. } else {
  475. // The method should have identical parameter and return types.
  476. if (left.Type != right.Type || method.ReturnType != left.Type)
  477. throw new ArgumentException ("left, right and return type must match");
  478. }
  479. return method;
  480. }
  481. public static BinaryExpression OrElse (Expression left, Expression right)
  482. {
  483. return OrElse (left, right, null);
  484. }
  485. public static BinaryExpression OrElse (Expression left, Expression right, MethodInfo method)
  486. {
  487. method = ConditionalBinaryCheck ("op_BitwiseOr", left, right, method);
  488. return MakeBoolBinary (ExpressionType.OrElse, left, right, false, method);
  489. }
  490. //
  491. // Comparison
  492. //
  493. public static BinaryExpression Equal (Expression left, Expression right)
  494. {
  495. return Equal (left, right, false, null);
  496. }
  497. public static BinaryExpression Equal (Expression left, Expression right, bool liftToNull, MethodInfo method)
  498. {
  499. method = BinaryCoreCheck ("op_Equality", left, right, method);
  500. return MakeBoolBinary (ExpressionType.Equal, left, right, liftToNull, method);
  501. }
  502. public static BinaryExpression NotEqual (Expression left, Expression right)
  503. {
  504. return NotEqual (left, right, false, null);
  505. }
  506. public static BinaryExpression NotEqual (Expression left, Expression right, bool liftToNull, MethodInfo method)
  507. {
  508. method = BinaryCoreCheck ("op_Inequality", left, right, method);
  509. return MakeBoolBinary (ExpressionType.NotEqual, left, right, liftToNull, method);
  510. }
  511. public static BinaryExpression GreaterThan (Expression left, Expression right)
  512. {
  513. return GreaterThan (left, right, false, null);
  514. }
  515. public static BinaryExpression GreaterThan (Expression left, Expression right, bool liftToNull, MethodInfo method)
  516. {
  517. method = BinaryCoreCheck ("op_GreaterThan", left, right, method);
  518. return MakeBoolBinary (ExpressionType.GreaterThan, left, right, liftToNull, method);
  519. }
  520. public static BinaryExpression GreaterThanOrEqual (Expression left, Expression right)
  521. {
  522. return GreaterThanOrEqual (left, right, false, null);
  523. }
  524. public static BinaryExpression GreaterThanOrEqual (Expression left, Expression right, bool liftToNull, MethodInfo method)
  525. {
  526. method = BinaryCoreCheck ("op_GreaterThanOrEqual", left, right, method);
  527. return MakeBoolBinary (ExpressionType.GreaterThanOrEqual, left, right, liftToNull, method);
  528. }
  529. public static BinaryExpression LessThan (Expression left, Expression right)
  530. {
  531. return LessThan (left, right, false, null);
  532. }
  533. public static BinaryExpression LessThan (Expression left, Expression right, bool liftToNull, MethodInfo method)
  534. {
  535. method = BinaryCoreCheck ("op_LessThan", left, right, method);
  536. return MakeBoolBinary (ExpressionType.LessThan, left, right, liftToNull, method);
  537. }
  538. public static BinaryExpression LessThanOrEqual (Expression left, Expression right)
  539. {
  540. return LessThanOrEqual (left, right, false, null);
  541. }
  542. public static BinaryExpression LessThanOrEqual (Expression left, Expression right, bool liftToNull, MethodInfo method)
  543. {
  544. method = BinaryCoreCheck ("op_LessThanOrEqual", left, right, method);
  545. return MakeBoolBinary (ExpressionType.LessThanOrEqual, left, right, liftToNull, method);
  546. }
  547. //
  548. // Miscelaneous
  549. //
  550. static void ArrayCheck (Expression array)
  551. {
  552. if (array == null)
  553. throw new ArgumentNullException ("array");
  554. if (!array.Type.IsArray)
  555. throw new ArgumentException ("The array argument must be of type array");
  556. }
  557. public static BinaryExpression ArrayIndex (Expression array, Expression index)
  558. {
  559. ArrayCheck (array);
  560. if (index == null)
  561. throw new ArgumentNullException ("index");
  562. if (array.Type.GetArrayRank () != 1)
  563. throw new ArgumentException ("The array argument must be a single dimensional array");
  564. if (index.Type != typeof (int))
  565. throw new ArgumentException ("The index must be of type int");
  566. return new BinaryExpression (ExpressionType.ArrayIndex, array.Type.GetElementType (), array, index);
  567. }
  568. public static BinaryExpression Coalesce (Expression left, Expression right)
  569. {
  570. return Coalesce (left, right, null);
  571. }
  572. public static BinaryExpression Coalesce (Expression left, Expression right, LambdaExpression conversion)
  573. {
  574. if (left == null)
  575. throw new ArgumentNullException ("left");
  576. if (right == null)
  577. throw new ArgumentNullException ("right");
  578. //
  579. // First arg must ne nullable (either Nullable<T> or a reference type
  580. //
  581. if (left.Type.IsValueType && !IsNullable (left.Type))
  582. throw new InvalidOperationException ("Left expression can never be null");
  583. Type result = null;
  584. if (IsNullable (left.Type)){
  585. Type lbase = GetNullableOf (left.Type);
  586. if (!IsNullable (right.Type) && lbase.IsAssignableFrom (right.Type))
  587. result = lbase;
  588. }
  589. if (result == null && left.Type.IsAssignableFrom (right.Type))
  590. result = left.Type;
  591. if (result == null){
  592. if (IsNullable (left.Type) && right.Type.IsAssignableFrom (GetNullableOf (left.Type))){
  593. result = right.Type;
  594. }
  595. }
  596. if (result == null)
  597. throw new ArgumentException ("Incompatible argument types");
  598. //
  599. // FIXME: What do we do with "conversion"?
  600. //
  601. return new BinaryExpression (ExpressionType.Coalesce, result, left, right, false, false, null, conversion);
  602. }
  603. //
  604. // MakeBinary constructors
  605. //
  606. public static BinaryExpression MakeBinary (ExpressionType binaryType, Expression left, Expression right)
  607. {
  608. return MakeBinary (binaryType, left, right, false, null);
  609. }
  610. public static BinaryExpression MakeBinary (ExpressionType binaryType, Expression left, Expression right, bool liftToNull, MethodInfo method)
  611. {
  612. return MakeBinary (binaryType, left, right, liftToNull, method, null);
  613. }
  614. public static BinaryExpression MakeBinary (ExpressionType binaryType, Expression left, Expression right, bool liftToNull, MethodInfo method, LambdaExpression conversion)
  615. {
  616. switch (binaryType) {
  617. case ExpressionType.Add:
  618. return Add (left, right, method);
  619. case ExpressionType.AddChecked:
  620. return AddChecked (left, right, method);
  621. case ExpressionType.AndAlso:
  622. return AndAlso (left, right);
  623. case ExpressionType.Coalesce:
  624. return Coalesce (left, right, conversion);
  625. case ExpressionType.Divide:
  626. return Divide (left, right, method);
  627. case ExpressionType.Equal:
  628. return Equal (left, right, liftToNull, method);
  629. case ExpressionType.ExclusiveOr:
  630. return ExclusiveOr (left, right, method);
  631. case ExpressionType.GreaterThan:
  632. return GreaterThan (left, right, liftToNull, method);
  633. case ExpressionType.GreaterThanOrEqual:
  634. return GreaterThanOrEqual (left, right, liftToNull, method);
  635. case ExpressionType.LeftShift:
  636. return LeftShift (left, right, method);
  637. case ExpressionType.LessThan:
  638. return LessThan (left, right, liftToNull, method);
  639. case ExpressionType.LessThanOrEqual:
  640. return LessThanOrEqual (left, right, liftToNull, method);
  641. case ExpressionType.Modulo:
  642. return Modulo (left, right, method);
  643. case ExpressionType.Multiply:
  644. return Multiply (left, right, method);
  645. case ExpressionType.MultiplyChecked:
  646. return MultiplyChecked (left, right, method);
  647. case ExpressionType.NotEqual:
  648. return NotEqual (left, right, liftToNull, method);
  649. case ExpressionType.OrElse:
  650. return OrElse (left, right);
  651. case ExpressionType.Power:
  652. return Power (left, right, method);
  653. case ExpressionType.RightShift:
  654. return RightShift (left, right, method);
  655. case ExpressionType.Subtract:
  656. return Subtract (left, right, method);
  657. case ExpressionType.SubtractChecked:
  658. return SubtractChecked (left, right, method);
  659. case ExpressionType.And:
  660. return And (left, right, method);
  661. case ExpressionType.Or:
  662. return Or (left, right, method);
  663. }
  664. throw new ArgumentException ("MakeBinary expect a binary node type");
  665. }
  666. #endregion
  667. public static MethodCallExpression ArrayIndex (Expression array, params Expression [] indexes)
  668. {
  669. return ArrayIndex (array, indexes as IEnumerable<Expression>);
  670. }
  671. public static MethodCallExpression ArrayIndex (Expression array, IEnumerable<Expression> indexes)
  672. {
  673. ArrayCheck (array);
  674. if (indexes == null)
  675. throw new ArgumentNullException ("indexes");
  676. var args = indexes.ToReadOnlyCollection ();
  677. if (array.Type.GetArrayRank () != args.Count)
  678. throw new ArgumentException ("The number of arguments doesn't match the rank of the array");
  679. foreach (var arg in args)
  680. if (arg.Type != typeof (int))
  681. throw new ArgumentException ("The index must be of type int");
  682. return Call (array, array.Type.GetMethod ("Get", PublicInstance), args);
  683. }
  684. public static UnaryExpression ArrayLength (Expression array)
  685. {
  686. if (array == null)
  687. throw new ArgumentNullException ("array");
  688. if (!array.Type.IsArray)
  689. throw new ArgumentException ("The type of the expression must me Array");
  690. if (array.Type.GetArrayRank () != 1)
  691. throw new ArgumentException ("The array must be a single dimensional array");
  692. return new UnaryExpression (ExpressionType.ArrayLength, array, typeof (int));
  693. }
  694. public static MemberAssignment Bind (MemberInfo member, Expression expression)
  695. {
  696. if (member == null)
  697. throw new ArgumentNullException ("member");
  698. if (expression == null)
  699. throw new ArgumentNullException ("expression");
  700. Type type = null;
  701. var prop = member as PropertyInfo;
  702. if (prop != null && prop.GetSetMethod (true) != null)
  703. type = prop.PropertyType;
  704. var field = member as FieldInfo;
  705. if (field != null)
  706. type = field.FieldType;
  707. if (type == null)
  708. throw new ArgumentException ("member");
  709. if (!type.IsAssignableFrom (expression.Type))
  710. throw new ArgumentException ("member");
  711. return new MemberAssignment (member, expression);
  712. }
  713. public static MemberAssignment Bind (MethodInfo propertyAccessor, Expression expression)
  714. {
  715. if (propertyAccessor == null)
  716. throw new ArgumentNullException ("propertyAccessor");
  717. if (expression == null)
  718. throw new ArgumentNullException ("expression");
  719. var prop = GetAssociatedProperty (propertyAccessor);
  720. if (prop == null)
  721. throw new ArgumentException ("propertyAccessor");
  722. var setter = prop.GetSetMethod (true);
  723. if (setter == null)
  724. throw new ArgumentException ("setter");
  725. if (!prop.PropertyType.IsAssignableFrom (expression.Type))
  726. throw new ArgumentException ("member");
  727. return new MemberAssignment (prop, expression);
  728. }
  729. public static MethodCallExpression Call (Expression instance, MethodInfo method)
  730. {
  731. return Call (instance, method, null as IEnumerable<Expression>);
  732. }
  733. public static MethodCallExpression Call (MethodInfo method, params Expression [] arguments)
  734. {
  735. return Call (null, method, arguments as IEnumerable<Expression>);
  736. }
  737. public static MethodCallExpression Call (Expression instance, MethodInfo method, params Expression [] arguments)
  738. {
  739. return Call (instance, method, arguments as IEnumerable<Expression>);
  740. }
  741. public static MethodCallExpression Call (Expression instance, MethodInfo method, IEnumerable<Expression> arguments)
  742. {
  743. if (method == null)
  744. throw new ArgumentNullException ("method");
  745. if (instance == null && !method.IsStatic)
  746. throw new ArgumentNullException ("instance");
  747. if (instance != null && !method.DeclaringType.IsAssignableFrom (instance.Type))
  748. throw new ArgumentException ("Type is not assignable to the declaring type of the method");
  749. var args = arguments.ToReadOnlyCollection ();
  750. CheckMethodArguments (method, args);
  751. return new MethodCallExpression (instance, method, args);
  752. }
  753. public static MethodCallExpression Call (Expression instance, string methodName, Type [] typeArguments, params Expression [] arguments)
  754. {
  755. if (instance == null)
  756. throw new ArgumentNullException ("instance");
  757. if (methodName == null)
  758. throw new ArgumentNullException ("methodName");
  759. if (typeArguments == null)
  760. typeArguments = new Type [0];
  761. var method = instance.Type.GetMethod (methodName, AllInstance, null, typeArguments, null);
  762. if (method == null)
  763. throw new InvalidOperationException ("No such method");
  764. var args = arguments.ToReadOnlyCollection ();
  765. if (typeArguments.Length != args.Count)
  766. throw new InvalidOperationException ("Argument count doesn't match parameters length");
  767. return new MethodCallExpression (instance, method, args);
  768. }
  769. public static MethodCallExpression Call (Type type, string methodName, Type [] typeArguments, params Expression [] arguments)
  770. {
  771. if (type == null)
  772. throw new ArgumentNullException ("type");
  773. if (methodName == null)
  774. throw new ArgumentNullException ("methodName");
  775. if (typeArguments == null)
  776. typeArguments = new Type [0];
  777. var method = type.GetMethod (methodName, AllStatic, null, typeArguments, null);
  778. if (method == null)
  779. throw new InvalidOperationException ("No such method");
  780. var args = arguments.ToReadOnlyCollection ();
  781. if (typeArguments.Length != args.Count)
  782. throw new InvalidOperationException ("Argument count doesn't match parameters length");
  783. return new MethodCallExpression (method, args);
  784. }
  785. public static ConditionalExpression Condition (Expression test, Expression ifTrue, Expression ifFalse)
  786. {
  787. if (test == null)
  788. throw new ArgumentNullException ("test");
  789. if (ifTrue == null)
  790. throw new ArgumentNullException ("ifTrue");
  791. if (ifFalse == null)
  792. throw new ArgumentNullException ("ifFalse");
  793. if (test.Type != typeof (bool))
  794. throw new ArgumentException ("Test expression should be of type bool");
  795. if (ifTrue.Type != ifFalse.Type)
  796. throw new ArgumentException ("The ifTrue and ifFalse type do not match");
  797. return new ConditionalExpression (test, ifTrue, ifFalse);
  798. }
  799. public static ConstantExpression Constant (object value)
  800. {
  801. if (value == null)
  802. return new ConstantExpression (null, typeof (object));
  803. return Constant (value, value.GetType ());
  804. }
  805. public static ConstantExpression Constant (object value, Type type)
  806. {
  807. if (type == null)
  808. throw new ArgumentNullException ("type");
  809. //
  810. // value must be compatible with type, no conversions
  811. // are allowed
  812. //
  813. if (value == null){
  814. if (type.IsValueType && !IsNullable (type))
  815. throw new ArgumentException ();
  816. } else {
  817. if (!(type.IsValueType && IsNullable (type)) && value.GetType () != type)
  818. throw new ArgumentException ();
  819. }
  820. return new ConstantExpression (value, type);
  821. }
  822. [MonoTODO]
  823. public static UnaryExpression Convert (Expression expression, Type type)
  824. {
  825. throw new NotImplementedException ();
  826. }
  827. [MonoTODO]
  828. public static UnaryExpression Convert (Expression expression, Type type, MethodInfo method)
  829. {
  830. throw new NotImplementedException ();
  831. }
  832. [MonoTODO]
  833. public static UnaryExpression ConvertChecked (Expression expression, Type type)
  834. {
  835. throw new NotImplementedException ();
  836. }
  837. [MonoTODO]
  838. public static UnaryExpression ConvertChecked (Expression expression, Type type, MethodInfo method)
  839. {
  840. throw new NotImplementedException ();
  841. }
  842. public static ElementInit ElementInit (MethodInfo addMethod, params Expression [] arguments)
  843. {
  844. return ElementInit (addMethod, arguments as IEnumerable<Expression>);
  845. }
  846. public static ElementInit ElementInit (MethodInfo addMethod, IEnumerable<Expression> arguments)
  847. {
  848. if (addMethod == null)
  849. throw new ArgumentNullException ("addMethod");
  850. if (arguments == null)
  851. throw new ArgumentNullException ("arguments");
  852. if (addMethod.Name.ToLowerInvariant () != "add")
  853. throw new ArgumentException ("addMethod");
  854. if (addMethod.IsStatic)
  855. throw new ArgumentException ("addMethod must be an instance method", "addMethod");
  856. var args = arguments.ToReadOnlyCollection ();
  857. CheckMethodArguments (addMethod, args);
  858. return new ElementInit (addMethod, args);
  859. }
  860. public static MemberExpression Field (Expression expression, FieldInfo field)
  861. {
  862. if (field == null)
  863. throw new ArgumentNullException ("field");
  864. if (!field.IsStatic) {
  865. if (expression == null)
  866. throw new ArgumentNullException ("expression");
  867. if (!field.DeclaringType.IsAssignableFrom (expression.Type))
  868. throw new ArgumentException ("field");
  869. }
  870. return new MemberExpression (expression, field, field.FieldType);
  871. }
  872. public static MemberExpression Field (Expression expression, string fieldName)
  873. {
  874. if (expression == null)
  875. throw new ArgumentNullException ("expression");
  876. var field = expression.Type.GetField (fieldName, AllInstance);
  877. if (field == null)
  878. throw new ArgumentException (string.Format ("No field named {0} on {1}", fieldName, expression.Type));
  879. return new MemberExpression (expression, field, field.FieldType);
  880. }
  881. public static Type GetActionType (params Type [] typeArgs)
  882. {
  883. if (typeArgs == null)
  884. throw new ArgumentNullException ("typeArgs");
  885. if (typeArgs.Length > 4)
  886. throw new ArgumentException ("No Action type of this arity");
  887. if (typeArgs.Length == 0)
  888. return typeof (Action);
  889. Type action = null;
  890. switch (typeArgs.Length) {
  891. case 1:
  892. action = typeof (Action<>);
  893. break;
  894. case 2:
  895. action = typeof (Action<,>);
  896. break;
  897. case 3:
  898. action = typeof (Action<,,>);
  899. break;
  900. case 4:
  901. action = typeof (Action<,,,>);
  902. break;
  903. }
  904. return action.MakeGenericType (typeArgs);
  905. }
  906. public static Type GetFuncType (params Type [] typeArgs)
  907. {
  908. if (typeArgs == null)
  909. throw new ArgumentNullException ("typeArgs");
  910. if (typeArgs.Length < 1 || typeArgs.Length > 5)
  911. throw new ArgumentException ("No Func type of this arity");
  912. Type func = null;
  913. switch (typeArgs.Length) {
  914. case 1:
  915. func = typeof (Func<>);
  916. break;
  917. case 2:
  918. func = typeof (Func<,>);
  919. break;
  920. case 3:
  921. func = typeof (Func<,,>);
  922. break;
  923. case 4:
  924. func = typeof (Func<,,,>);
  925. break;
  926. case 5:
  927. func = typeof (Func<,,,,>);
  928. break;
  929. }
  930. return func.MakeGenericType (typeArgs);
  931. }
  932. public static InvocationExpression Invoke (Expression expression, params Expression [] arguments)
  933. {
  934. return Invoke (expression, arguments as IEnumerable<Expression>);
  935. }
  936. static Type GetInvokableType (Type t)
  937. {
  938. if (typeof (Delegate).IsAssignableFrom (t))
  939. return t;
  940. return GetGenericType (t, typeof (Expression<>));
  941. }
  942. static Type GetGenericType (Type t, Type def)
  943. {
  944. if (t == null)
  945. return null;
  946. if (t.IsGenericType && t.GetGenericTypeDefinition () == def)
  947. return t;
  948. return GetGenericType (t.BaseType, def);
  949. }
  950. public static InvocationExpression Invoke (Expression expression, IEnumerable<Expression> arguments)
  951. {
  952. if (expression == null)
  953. throw new ArgumentNullException ("expression");
  954. var type = GetInvokableType (expression.Type);
  955. if (type == null)
  956. throw new ArgumentException ("The type of the expression is not invokable");
  957. var args = arguments.ToReadOnlyCollection ();
  958. CheckForNull (args, "arguments");
  959. var invoke = type.GetMethod ("Invoke");
  960. if (invoke == null)
  961. throw new ArgumentException ("expression");
  962. if (invoke.GetParameters ().Length != args.Count)
  963. throw new InvalidOperationException ("Arguments count doesn't match parameters length");
  964. CheckMethodArguments (invoke, args);
  965. return new InvocationExpression (expression, invoke.ReturnType, args);
  966. }
  967. public static Expression<TDelegate> Lambda<TDelegate> (Expression body, params ParameterExpression [] parameters)
  968. {
  969. return Lambda<TDelegate> (body, parameters as IEnumerable<ParameterExpression>);
  970. }
  971. public static Expression<TDelegate> Lambda<TDelegate> (Expression body, IEnumerable<ParameterExpression> parameters)
  972. {
  973. if (body == null)
  974. throw new ArgumentNullException ("body");
  975. return new Expression<TDelegate> (body, parameters.ToReadOnlyCollection ());
  976. }
  977. public static LambdaExpression Lambda (Expression body, params ParameterExpression [] parameters)
  978. {
  979. if (body == null)
  980. throw new ArgumentNullException ("body");
  981. if (parameters.Length > 4)
  982. throw new ArgumentException ("Too many parameters");
  983. return Lambda (GetDelegateType (body.Type, parameters), body, parameters);
  984. }
  985. static Type GetDelegateType (Type return_type, ParameterExpression [] parameters)
  986. {
  987. if (parameters == null)
  988. parameters = new ParameterExpression [0];
  989. if (return_type == typeof (void))
  990. return GetActionType (parameters.Select (p => p.Type).ToArray ());
  991. var types = new Type [parameters.Length + 1];
  992. for (int i = 0; i < types.Length - 1; i++)
  993. types [i] = parameters [i].Type;
  994. types [types.Length - 1] = return_type;
  995. return GetFuncType (types);
  996. }
  997. public static LambdaExpression Lambda (Type delegateType, Expression body, params ParameterExpression [] parameters)
  998. {
  999. return Lambda (delegateType, body, parameters as IEnumerable<ParameterExpression>);
  1000. }
  1001. public static LambdaExpression Lambda (Type delegateType, Expression body, IEnumerable<ParameterExpression> parameters)
  1002. {
  1003. if (delegateType == null)
  1004. throw new ArgumentNullException ("delegateType");
  1005. if (body == null)
  1006. throw new ArgumentNullException ("body");
  1007. return new LambdaExpression (delegateType, body, parameters.ToReadOnlyCollection ());
  1008. }
  1009. public static MemberListBinding ListBind (MemberInfo member, params ElementInit [] initializers)
  1010. {
  1011. return ListBind (member, initializers as IEnumerable<ElementInit>);
  1012. }
  1013. static void CheckIsAssignableToIEnumerable (Type t)
  1014. {
  1015. if (!typeof (IEnumerable).IsAssignableFrom (t))
  1016. throw new ArgumentException (string.Format ("Type {0} doesn't implemen IEnumerable", t));
  1017. }
  1018. public static MemberListBinding ListBind (MemberInfo member, IEnumerable<ElementInit> initializers)
  1019. {
  1020. if (member == null)
  1021. throw new ArgumentNullException ("member");
  1022. var inits = initializers.ToReadOnlyCollection ();
  1023. CheckForNull (inits, "initializers");
  1024. switch (member.MemberType) {
  1025. case MemberTypes.Field:
  1026. CheckIsAssignableToIEnumerable ((member as FieldInfo).FieldType);
  1027. break;
  1028. case MemberTypes.Property:
  1029. CheckIsAssignableToIEnumerable ((member as PropertyInfo).PropertyType);
  1030. break;
  1031. default:
  1032. throw new ArgumentException ("member");
  1033. }
  1034. return new MemberListBinding (member, inits);
  1035. }
  1036. public static MemberListBinding ListBind (MethodInfo propertyAccessor, params ElementInit [] initializers)
  1037. {
  1038. return ListBind (propertyAccessor, initializers as IEnumerable<ElementInit>);
  1039. }
  1040. static void CheckForNull<T> (ReadOnlyCollection<T> collection, string name) where T : class
  1041. {
  1042. foreach (var t in collection)
  1043. if (t == null)
  1044. throw new ArgumentNullException (name);
  1045. }
  1046. public static MemberListBinding ListBind (MethodInfo propertyAccessor, IEnumerable<ElementInit> initializers)
  1047. {
  1048. if (propertyAccessor == null)
  1049. throw new ArgumentNullException ("propertyAccessor");
  1050. var inits = initializers.ToReadOnlyCollection ();
  1051. CheckForNull (inits, "initializers");
  1052. var prop = GetAssociatedProperty (propertyAccessor);
  1053. if (prop == null)
  1054. throw new ArgumentException ("propertyAccessor");
  1055. CheckIsAssignableToIEnumerable (prop.PropertyType);
  1056. return new MemberListBinding (prop, inits);
  1057. }
  1058. [MonoTODO]
  1059. public static ListInitExpression ListInit (NewExpression newExpression, params ElementInit [] initializers)
  1060. {
  1061. throw new NotImplementedException ();
  1062. }
  1063. [MonoTODO]
  1064. public static ListInitExpression ListInit (NewExpression newExpression, IEnumerable<ElementInit> initializers)
  1065. {
  1066. throw new NotImplementedException ();
  1067. }
  1068. [MonoTODO]
  1069. public static ListInitExpression ListInit (NewExpression newExpression, params Expression [] initializers)
  1070. {
  1071. throw new NotImplementedException ();
  1072. }
  1073. [MonoTODO]
  1074. public static ListInitExpression ListInit (NewExpression newExpression, IEnumerable<Expression> initializers)
  1075. {
  1076. throw new NotImplementedException ();
  1077. }
  1078. [MonoTODO]
  1079. public static ListInitExpression ListInit (NewExpression newExpression, MethodInfo addMethod, params Expression [] initializers)
  1080. {
  1081. throw new NotImplementedException ();
  1082. }
  1083. [MonoTODO]
  1084. public static ListInitExpression ListInit (NewExpression newExpression, MethodInfo addMethod, IEnumerable<Expression> initializers)
  1085. {
  1086. throw new NotImplementedException ();
  1087. }
  1088. public static MemberExpression MakeMemberAccess (Expression expression, MemberInfo member)
  1089. {
  1090. if (expression == null)
  1091. throw new ArgumentNullException ("expression");
  1092. if (member == null)
  1093. throw new ArgumentNullException ("member");
  1094. var field = member as FieldInfo;
  1095. if (field != null)
  1096. return Field (expression, field);
  1097. var property = member as PropertyInfo;
  1098. if (property != null)
  1099. return Property (expression, property);
  1100. throw new ArgumentException ("Member should either be a field or a property");
  1101. }
  1102. public static UnaryExpression MakeUnary (ExpressionType unaryType, Expression operand, Type type)
  1103. {
  1104. return MakeUnary (unaryType, operand, type, null);
  1105. }
  1106. public static UnaryExpression MakeUnary (ExpressionType unaryType, Expression operand, Type type, MethodInfo method)
  1107. {
  1108. switch (unaryType) {
  1109. case ExpressionType.ArrayLength:
  1110. return ArrayLength (operand);
  1111. case ExpressionType.Convert:
  1112. return Convert (operand, type, method);
  1113. case ExpressionType.ConvertChecked:
  1114. return ConvertChecked (operand, type, method);
  1115. case ExpressionType.Negate:
  1116. return Negate (operand, method);
  1117. case ExpressionType.NegateChecked:
  1118. return NegateChecked (operand, method);
  1119. case ExpressionType.Not:
  1120. return Not (operand, method);
  1121. case ExpressionType.Quote:
  1122. return Quote (operand);
  1123. case ExpressionType.TypeAs:
  1124. return TypeAs (operand, type);
  1125. case ExpressionType.UnaryPlus:
  1126. return UnaryPlus (operand, method);
  1127. }
  1128. throw new ArgumentException ("MakeUnary expect an unary operator");
  1129. }
  1130. [MonoTODO]
  1131. public static MemberMemberBinding MemberBind (MemberInfo member, params MemberBinding [] binding)
  1132. {
  1133. throw new NotImplementedException ();
  1134. }
  1135. [MonoTODO]
  1136. public static MemberMemberBinding MemberBind (MemberInfo member, IEnumerable<MemberBinding> binding)
  1137. {
  1138. throw new NotImplementedException ();
  1139. }
  1140. [MonoTODO]
  1141. public static MemberMemberBinding MemberBind (MethodInfo propertyAccessor, params MemberBinding [] binding)
  1142. {
  1143. throw new NotImplementedException ();
  1144. }
  1145. [MonoTODO]
  1146. public static MemberMemberBinding MemberBind (MethodInfo propertyAccessor, IEnumerable<MemberBinding> binding)
  1147. {
  1148. throw new NotImplementedException ();
  1149. }
  1150. [MonoTODO]
  1151. public static MemberInitExpression MemberInit (NewExpression newExpression, params MemberBinding [] binding)
  1152. {
  1153. throw new NotImplementedException ();
  1154. }
  1155. [MonoTODO]
  1156. public static MemberInitExpression MemberInit (NewExpression newExpression, IEnumerable<MemberBinding> binding)
  1157. {
  1158. throw new NotImplementedException ();
  1159. }
  1160. public static UnaryExpression Negate (Expression expression)
  1161. {
  1162. return Negate (expression, null);
  1163. }
  1164. public static UnaryExpression Negate (Expression expression, MethodInfo method)
  1165. {
  1166. method = UnaryCoreCheck ("op_UnaryNegation", expression, method);
  1167. return MakeSimpleUnary (ExpressionType.Negate, expression, method);
  1168. }
  1169. public static UnaryExpression NegateChecked (Expression expression)
  1170. {
  1171. return NegateChecked (expression, null);
  1172. }
  1173. public static UnaryExpression NegateChecked (Expression expression, MethodInfo method)
  1174. {
  1175. method = UnaryCoreCheck ("op_UnaryNegation", expression, method);
  1176. return MakeSimpleUnary (ExpressionType.Negate, expression, method);
  1177. }
  1178. public static NewExpression New (ConstructorInfo constructor)
  1179. {
  1180. if (constructor == null)
  1181. throw new ArgumentNullException ("constructor");
  1182. if (constructor.GetParameters ().Length > 0)
  1183. throw new ArgumentException ("Constructor must be parameter less");
  1184. return new NewExpression (constructor, (null as IEnumerable<Expression>).ToReadOnlyCollection (), null);
  1185. }
  1186. public static NewExpression New (Type type)
  1187. {
  1188. if (type == null)
  1189. throw new ArgumentNullException ("type");
  1190. var ctor = type.GetConstructor (Type.EmptyTypes);
  1191. if (ctor == null)
  1192. throw new ArgumentException ("Type doesn't have a parameter less constructor");
  1193. return new NewExpression (ctor, (null as IEnumerable<Expression>).ToReadOnlyCollection (), null);
  1194. }
  1195. public static NewExpression New (ConstructorInfo constructor, params Expression [] arguments)
  1196. {
  1197. return New (constructor, arguments as IEnumerable<Expression>);
  1198. }
  1199. public static NewExpression New (ConstructorInfo constructor, IEnumerable<Expression> arguments)
  1200. {
  1201. if (constructor == null)
  1202. throw new ArgumentNullException ("constructor");
  1203. var args = arguments.ToReadOnlyCollection ();
  1204. CheckMethodArguments (constructor, args);
  1205. return new NewExpression (constructor, args, null);
  1206. }
  1207. static void CheckMethodArguments (MethodBase method, ReadOnlyCollection<Expression> arguments)
  1208. {
  1209. var parameters = method.GetParameters ();
  1210. if (arguments.Count != parameters.Length)
  1211. throw new ArgumentException ("The number of arguments doesn't match the number of parameters");
  1212. for (int i = 0; i < parameters.Length; i++) {
  1213. if (arguments [i] == null)
  1214. throw new ArgumentNullException ("arguments");
  1215. if (!parameters [i].ParameterType.IsAssignableFrom (arguments [i].Type))
  1216. throw new ArgumentException ("arguments");
  1217. }
  1218. }
  1219. public static NewExpression New (ConstructorInfo constructor, IEnumerable<Expression> arguments, params MemberInfo [] members)
  1220. {
  1221. return New (constructor, arguments, members as IEnumerable<MemberInfo>);
  1222. }
  1223. public static NewExpression New (ConstructorInfo constructor, IEnumerable<Expression> arguments, IEnumerable<MemberInfo> members)
  1224. {
  1225. if (constructor == null)
  1226. throw new ArgumentNullException ("constructor");
  1227. var args = arguments.ToReadOnlyCollection ();
  1228. var mmbs = members.ToReadOnlyCollection ();
  1229. CheckForNull (args, "arguments");
  1230. CheckForNull (mmbs, "members");
  1231. CheckMethodArguments (constructor, args);
  1232. if (args.Count != mmbs.Count)
  1233. throw new ArgumentException ("Arguments count does not match members count");
  1234. for (int i = 0; i < mmbs.Count; i++) {
  1235. var member = mmbs [i];
  1236. Type type = null;
  1237. switch (member.MemberType) {
  1238. case MemberTypes.Field:
  1239. type = (member as FieldInfo).FieldType;
  1240. break;
  1241. case MemberTypes.Method:
  1242. type = (member as MethodInfo).ReturnType;
  1243. break;
  1244. case MemberTypes.Property:
  1245. var prop = member as PropertyInfo;
  1246. if (prop.GetGetMethod (true) == null)
  1247. throw new ArgumentException ("Property must have a getter");
  1248. type = (member as PropertyInfo).PropertyType;
  1249. break;
  1250. default:
  1251. throw new ArgumentException ("Member type not allowed");
  1252. }
  1253. if (!type.IsAssignableFrom (args [i].Type))
  1254. throw new ArgumentException ("Argument type not assignable to member type");
  1255. }
  1256. return new NewExpression (constructor, args, mmbs);
  1257. }
  1258. public static NewArrayExpression NewArrayBounds (Type type, params Expression [] bounds)
  1259. {
  1260. return NewArrayBounds (type, bounds as IEnumerable<Expression>);
  1261. }
  1262. public static NewArrayExpression NewArrayBounds (Type type, IEnumerable<Expression> bounds)
  1263. {
  1264. if (type == null)
  1265. throw new ArgumentNullException ("type");
  1266. if (bounds == null)
  1267. throw new ArgumentNullException ("bounds");
  1268. var array_bounds = bounds.ToReadOnlyCollection ();
  1269. foreach (var expression in array_bounds)
  1270. if (!IsInt (expression.Type))
  1271. throw new ArgumentException ("The bounds collection can only contain expression of integers types");
  1272. return new NewArrayExpression (ExpressionType.NewArrayBounds, type.MakeArrayType (array_bounds.Count), array_bounds);
  1273. }
  1274. public static NewArrayExpression NewArrayInit (Type type, params Expression [] initializers)
  1275. {
  1276. return NewArrayInit (type, initializers as IEnumerable<Expression>);
  1277. }
  1278. public static NewArrayExpression NewArrayInit (Type type, IEnumerable<Expression> initializers)
  1279. {
  1280. if (type == null)
  1281. throw new ArgumentNullException ("type");
  1282. if (initializers == null)
  1283. throw new ArgumentNullException ("initializers");
  1284. var array_initializers = initializers.ToReadOnlyCollection ();
  1285. foreach (var expression in initializers) {
  1286. if (expression == null)
  1287. throw new ArgumentNullException ("initializers");
  1288. if (!type.IsAssignableFrom (expression.Type))
  1289. throw new InvalidOperationException ();
  1290. // TODO: Quote elements if type == typeof (Expression)
  1291. }
  1292. return new NewArrayExpression (ExpressionType.NewArrayInit, type.MakeArrayType (), array_initializers);
  1293. }
  1294. public static UnaryExpression Not (Expression expression)
  1295. {
  1296. return Not (expression, null);
  1297. }
  1298. public static UnaryExpression Not (Expression expression, MethodInfo method)
  1299. {
  1300. method = UnaryCoreCheck ("op_LogicalNot", expression, method);
  1301. return MakeSimpleUnary (ExpressionType.Not, expression, method);
  1302. }
  1303. public static ParameterExpression Parameter (Type type, string name)
  1304. {
  1305. if (type == null)
  1306. throw new ArgumentNullException ("type");
  1307. return new ParameterExpression (type, name);
  1308. }
  1309. public static MemberExpression Property (Expression expression, MethodInfo propertyAccessor)
  1310. {
  1311. if (propertyAccessor == null)
  1312. throw new ArgumentNullException ("propertyAccessor");
  1313. if (!propertyAccessor.IsStatic) {
  1314. if (expression == null)
  1315. throw new ArgumentNullException ("expression");
  1316. if (!propertyAccessor.DeclaringType.IsAssignableFrom (expression.Type))
  1317. throw new ArgumentException ("expression");
  1318. }
  1319. var prop = GetAssociatedProperty (propertyAccessor);
  1320. if (prop == null)
  1321. throw new ArgumentException (string.Format ("Method {0} has no associated property", propertyAccessor));
  1322. return new MemberExpression (expression, prop, prop.PropertyType);
  1323. }
  1324. static PropertyInfo GetAssociatedProperty (MethodInfo method)
  1325. {
  1326. foreach (var prop in method.DeclaringType.GetProperties (All)) {
  1327. if (prop.GetGetMethod (true) == method)
  1328. return prop;
  1329. if (prop.GetSetMethod (true) == method)
  1330. return prop;
  1331. }
  1332. return null;
  1333. }
  1334. public static MemberExpression Property (Expression expression, PropertyInfo property)
  1335. {
  1336. if (property == null)
  1337. throw new ArgumentNullException ("property");
  1338. var getter = property.GetGetMethod (true);
  1339. if (getter == null)
  1340. throw new ArgumentException ("getter");
  1341. if (!getter.IsStatic) {
  1342. if (expression == null)
  1343. throw new ArgumentNullException ("expression");
  1344. if (!property.DeclaringType.IsAssignableFrom (expression.Type))
  1345. throw new ArgumentException ("expression");
  1346. }
  1347. return new MemberExpression (expression, property, property.PropertyType);
  1348. }
  1349. public static MemberExpression Property (Expression expression, string propertyName)
  1350. {
  1351. if (expression == null)
  1352. throw new ArgumentNullException ("expression");
  1353. var prop = expression.Type.GetProperty (propertyName, AllInstance);
  1354. if (prop == null)
  1355. throw new ArgumentException (string.Format ("No property named {0} on {1}", propertyName, expression.Type));
  1356. return new MemberExpression (expression, prop, prop.PropertyType);
  1357. }
  1358. public static MemberExpression PropertyOrField (Expression expression, string propertyOrFieldName)
  1359. {
  1360. if (expression == null)
  1361. throw new ArgumentNullException ("expression");
  1362. if (propertyOrFieldName == null)
  1363. throw new ArgumentNullException ("propertyOrFieldName");
  1364. var prop = expression.Type.GetProperty (propertyOrFieldName, AllInstance);
  1365. if (prop != null)
  1366. return new MemberExpression (expression, prop, prop.PropertyType);
  1367. var field = expression.Type.GetField (propertyOrFieldName, AllInstance);
  1368. if (field != null)
  1369. return new MemberExpression (expression, field, field.FieldType);
  1370. throw new ArgumentException (string.Format ("No field or property named {0} on {1}", propertyOrFieldName, expression.Type));
  1371. }
  1372. public static UnaryExpression Quote (Expression expression)
  1373. {
  1374. if (expression == null)
  1375. throw new ArgumentNullException ("expression");
  1376. return new UnaryExpression (ExpressionType.Quote, expression, expression.GetType ());
  1377. }
  1378. public static UnaryExpression TypeAs (Expression expression, Type type)
  1379. {
  1380. if (expression == null)
  1381. throw new ArgumentNullException ("expression");
  1382. if (type == null)
  1383. throw new ArgumentNullException ("type");
  1384. if (type.IsValueType && !IsNullable (type))
  1385. throw new ArgumentException ("TypeAs expect a reference or a nullable type");
  1386. return new UnaryExpression (ExpressionType.TypeAs, expression, type);
  1387. }
  1388. public static TypeBinaryExpression TypeIs (Expression expression, Type type)
  1389. {
  1390. if (expression == null)
  1391. throw new ArgumentNullException ("expression");
  1392. if (type == null)
  1393. throw new ArgumentNullException ("type");
  1394. return new TypeBinaryExpression (ExpressionType.TypeIs, expression, type, typeof (bool));
  1395. }
  1396. public static UnaryExpression UnaryPlus (Expression expression)
  1397. {
  1398. return UnaryPlus (expression, null);
  1399. }
  1400. public static UnaryExpression UnaryPlus (Expression expression, MethodInfo method)
  1401. {
  1402. method = UnaryCoreCheck ("op_UnaryPlus", expression, method);
  1403. return MakeSimpleUnary (ExpressionType.UnaryPlus, expression, method);
  1404. }
  1405. internal static bool IsNullable (Type type)
  1406. {
  1407. return type.IsGenericType && type.GetGenericTypeDefinition () == typeof (Nullable<>);
  1408. }
  1409. internal static bool IsUnsigned (Type t)
  1410. {
  1411. if (t.IsPointer)
  1412. return IsUnsigned (t.GetElementType ());
  1413. return t == typeof (ushort) || t == typeof (uint) || t == typeof (ulong) || t == typeof (byte);
  1414. }
  1415. //
  1416. // returns the T in a a Nullable<T> type.
  1417. //
  1418. internal static Type GetNullableOf (Type type)
  1419. {
  1420. return type.GetGenericArguments () [0];
  1421. }
  1422. //
  1423. // This method must be overwritten by derived classes to
  1424. // compile the expression
  1425. //
  1426. internal abstract void Emit (EmitContext ec);
  1427. }
  1428. }