Expression.cs 71 KB

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