Expression.cs 70 KB

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