Expression.cs 71 KB

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