Expression.cs 67 KB

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