Expression.cs 69 KB

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