Expression.cs 66 KB

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