Expression.cs 64 KB

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