Expression.cs 67 KB

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