Expression.cs 59 KB

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