Expression.cs 59 KB

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