Expression.cs 60 KB

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