Expression.cs 70 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257
  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)
  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. }
  853. for (int i = 0; i < parameters.Length; i++)
  854. if (!IsAssignableToParameterType (parameterTypes [i], parameters [i]))
  855. return false;
  856. return true;
  857. }
  858. static MethodInfo TryGetMethod (Type type, string methodName, BindingFlags flags, Type [] parameterTypes, Type [] argumentTypes)
  859. {
  860. var methods = from meth in type.GetMethods (flags)
  861. where MethodMatch (meth, methodName, parameterTypes, argumentTypes)
  862. select meth;
  863. if (methods.Count () > 1)
  864. throw new InvalidOperationException ("Too much method candidates");
  865. var method = TryMakeGeneric (methods.FirstOrDefault (), argumentTypes);
  866. if (method != null)
  867. return method;
  868. throw new InvalidOperationException ("No such method");
  869. }
  870. public static MethodCallExpression Call (Type type, string methodName, Type [] typeArguments, params Expression [] arguments)
  871. {
  872. if (type == null)
  873. throw new ArgumentNullException ("type");
  874. if (methodName == null)
  875. throw new ArgumentNullException ("methodName");
  876. var method = TryGetMethod (type, methodName, AllStatic,
  877. CollectTypes (arguments), typeArguments);
  878. var args = CheckMethodArguments (method, arguments);
  879. return new MethodCallExpression (method, args);
  880. }
  881. public static ConditionalExpression Condition (Expression test, Expression ifTrue, Expression ifFalse)
  882. {
  883. if (test == null)
  884. throw new ArgumentNullException ("test");
  885. if (ifTrue == null)
  886. throw new ArgumentNullException ("ifTrue");
  887. if (ifFalse == null)
  888. throw new ArgumentNullException ("ifFalse");
  889. if (test.Type != typeof (bool))
  890. throw new ArgumentException ("Test expression should be of type bool");
  891. if (ifTrue.Type != ifFalse.Type)
  892. throw new ArgumentException ("The ifTrue and ifFalse type do not match");
  893. return new ConditionalExpression (test, ifTrue, ifFalse);
  894. }
  895. public static ConstantExpression Constant (object value)
  896. {
  897. if (value == null)
  898. return new ConstantExpression (null, typeof (object));
  899. return Constant (value, value.GetType ());
  900. }
  901. public static ConstantExpression Constant (object value, Type type)
  902. {
  903. if (type == null)
  904. throw new ArgumentNullException ("type");
  905. //
  906. // value must be compatible with type, no conversions
  907. // are allowed
  908. //
  909. if (value == null){
  910. if (type.IsValueType && !type.IsNullable ())
  911. throw new ArgumentException ();
  912. } else {
  913. if (!(type.IsValueType && type.IsNullable ()) && !value.GetType ().IsAssignableTo (type))
  914. throw new ArgumentException ();
  915. }
  916. return new ConstantExpression (value, type);
  917. }
  918. static bool IsConvertiblePrimitive (Type type)
  919. {
  920. var t = type.GetNotNullableType ();
  921. if (t == typeof (bool))
  922. return false;
  923. if (t.IsEnum)
  924. return true;
  925. return t.IsPrimitive;
  926. }
  927. internal static bool IsPrimitiveConversion (Type type, Type target)
  928. {
  929. if (type == target)
  930. return true;
  931. if (type.IsNullable () && target == type.GetNotNullableType ())
  932. return true;
  933. if (target.IsNullable () && type == target.GetNotNullableType ())
  934. return true;
  935. if (IsConvertiblePrimitive (type) && IsConvertiblePrimitive (target))
  936. return true;
  937. return false;
  938. }
  939. internal static bool IsReferenceConversion (Type type, Type target)
  940. {
  941. if (type == target)
  942. return true;
  943. if (type == typeof (object) || target == typeof (object))
  944. return true;
  945. if (type.IsInterface || target.IsInterface)
  946. return true;
  947. if (type.IsValueType || target.IsValueType)
  948. return false;
  949. if (type.IsAssignableTo (target) || target.IsAssignableTo (type))
  950. return true;
  951. return false;
  952. }
  953. public static UnaryExpression Convert (Expression expression, Type type)
  954. {
  955. return Convert (expression, type, null);
  956. }
  957. static MethodInfo GetUserConversionMethod (Type type, Type target)
  958. {
  959. var method = GetUnaryOperator ("op_Explicit", type, type, target);
  960. if (method == null)
  961. method = GetUnaryOperator ("op_Implicit", type, type, target);
  962. if (method == null)
  963. method = GetUnaryOperator ("op_Explicit", target, type, target);
  964. if (method == null)
  965. method = GetUnaryOperator ("op_Implicit", target, type, target);
  966. if (method == null)
  967. throw new InvalidOperationException ();
  968. return method;
  969. }
  970. public static UnaryExpression Convert (Expression expression, Type type, MethodInfo method)
  971. {
  972. if (expression == null)
  973. throw new ArgumentNullException ("expression");
  974. if (type == null)
  975. throw new ArgumentNullException ("type");
  976. var et = expression.Type;
  977. if (method != null)
  978. CheckUnaryMethod (method, et);
  979. else if (!IsPrimitiveConversion (et, type) && !IsReferenceConversion (et, type))
  980. method = GetUserConversionMethod (et, type);
  981. return new UnaryExpression (ExpressionType.Convert,
  982. expression, type, method,
  983. IsConvertNodeLifted (method, expression, type));
  984. }
  985. static bool IsConvertNodeLifted (MethodInfo method, Expression operand, Type target)
  986. {
  987. if (method == null)
  988. return operand.Type.IsNullable () || target.IsNullable ();
  989. if (operand.Type.IsNullable () && !ParameterMatch (method, operand.Type))
  990. return true;
  991. if (target.IsNullable () && !ReturnTypeMatch (method, target))
  992. return true;
  993. return false;
  994. }
  995. static bool ParameterMatch (MethodInfo method, Type type)
  996. {
  997. return method.GetParameters () [0].ParameterType == type;
  998. }
  999. static bool ReturnTypeMatch (MethodInfo method, Type type)
  1000. {
  1001. return method.ReturnType == type;
  1002. }
  1003. public static UnaryExpression ConvertChecked (Expression expression, Type type)
  1004. {
  1005. return ConvertChecked (expression, type, null);
  1006. }
  1007. public static UnaryExpression ConvertChecked (Expression expression, Type type, MethodInfo method)
  1008. {
  1009. if (expression == null)
  1010. throw new ArgumentNullException ("expression");
  1011. if (type == null)
  1012. throw new ArgumentNullException ("type");
  1013. var et = expression.Type;
  1014. if (method != null)
  1015. CheckUnaryMethod (method, et);
  1016. else if (IsReferenceConversion (et, type))
  1017. return Convert (expression, type, method);
  1018. else if (!IsPrimitiveConversion (et, type))
  1019. method = GetUserConversionMethod (et, type);
  1020. return new UnaryExpression (ExpressionType.ConvertChecked,
  1021. expression, type, method,
  1022. IsConvertNodeLifted (method, expression, type));
  1023. }
  1024. public static ElementInit ElementInit (MethodInfo addMethod, params Expression [] arguments)
  1025. {
  1026. return ElementInit (addMethod, arguments as IEnumerable<Expression>);
  1027. }
  1028. public static ElementInit ElementInit (MethodInfo addMethod, IEnumerable<Expression> arguments)
  1029. {
  1030. if (addMethod == null)
  1031. throw new ArgumentNullException ("addMethod");
  1032. if (arguments == null)
  1033. throw new ArgumentNullException ("arguments");
  1034. if (addMethod.Name.ToLower (CultureInfo.InvariantCulture) != "add")
  1035. throw new ArgumentException ("addMethod");
  1036. if (addMethod.IsStatic)
  1037. throw new ArgumentException ("addMethod must be an instance method", "addMethod");
  1038. var args = CheckMethodArguments (addMethod, arguments);
  1039. return new ElementInit (addMethod, args);
  1040. }
  1041. public static MemberExpression Field (Expression expression, FieldInfo field)
  1042. {
  1043. if (field == null)
  1044. throw new ArgumentNullException ("field");
  1045. if (!field.IsStatic) {
  1046. if (expression == null)
  1047. throw new ArgumentNullException ("expression");
  1048. if (!expression.Type.IsAssignableTo (field.DeclaringType))
  1049. throw new ArgumentException ("field");
  1050. } else if (expression != null)
  1051. throw new ArgumentException ("expression");
  1052. return new MemberExpression (expression, field, field.FieldType);
  1053. }
  1054. public static MemberExpression Field (Expression expression, string fieldName)
  1055. {
  1056. if (expression == null)
  1057. throw new ArgumentNullException ("expression");
  1058. var field = expression.Type.GetField (fieldName, AllInstance);
  1059. if (field == null)
  1060. throw new ArgumentException (string.Format ("No field named {0} on {1}", fieldName, expression.Type));
  1061. return new MemberExpression (expression, field, field.FieldType);
  1062. }
  1063. public static Type GetActionType (params Type [] typeArgs)
  1064. {
  1065. if (typeArgs == null)
  1066. throw new ArgumentNullException ("typeArgs");
  1067. if (typeArgs.Length > 4)
  1068. throw new ArgumentException ("No Action type of this arity");
  1069. if (typeArgs.Length == 0)
  1070. return typeof (Action);
  1071. Type action = null;
  1072. switch (typeArgs.Length) {
  1073. case 1:
  1074. action = typeof (Action<>);
  1075. break;
  1076. case 2:
  1077. action = typeof (Action<,>);
  1078. break;
  1079. case 3:
  1080. action = typeof (Action<,,>);
  1081. break;
  1082. case 4:
  1083. action = typeof (Action<,,,>);
  1084. break;
  1085. }
  1086. return action.MakeGenericType (typeArgs);
  1087. }
  1088. public static Type GetFuncType (params Type [] typeArgs)
  1089. {
  1090. if (typeArgs == null)
  1091. throw new ArgumentNullException ("typeArgs");
  1092. if (typeArgs.Length < 1 || typeArgs.Length > 5)
  1093. throw new ArgumentException ("No Func type of this arity");
  1094. Type func = null;
  1095. switch (typeArgs.Length) {
  1096. case 1:
  1097. func = typeof (Func<>);
  1098. break;
  1099. case 2:
  1100. func = typeof (Func<,>);
  1101. break;
  1102. case 3:
  1103. func = typeof (Func<,,>);
  1104. break;
  1105. case 4:
  1106. func = typeof (Func<,,,>);
  1107. break;
  1108. case 5:
  1109. func = typeof (Func<,,,,>);
  1110. break;
  1111. }
  1112. return func.MakeGenericType (typeArgs);
  1113. }
  1114. public static InvocationExpression Invoke (Expression expression, params Expression [] arguments)
  1115. {
  1116. return Invoke (expression, arguments as IEnumerable<Expression>);
  1117. }
  1118. static Type GetInvokableType (Type t)
  1119. {
  1120. if (t.IsAssignableTo (typeof (Delegate)))
  1121. return t;
  1122. return GetGenericType (t, typeof (Expression<>));
  1123. }
  1124. static Type GetGenericType (Type t, Type def)
  1125. {
  1126. if (t == null)
  1127. return null;
  1128. if (t.IsGenericType && t.GetGenericTypeDefinition () == def)
  1129. return t;
  1130. return GetGenericType (t.BaseType, def);
  1131. }
  1132. public static InvocationExpression Invoke (Expression expression, IEnumerable<Expression> arguments)
  1133. {
  1134. if (expression == null)
  1135. throw new ArgumentNullException ("expression");
  1136. var type = GetInvokableType (expression.Type);
  1137. if (type == null)
  1138. throw new ArgumentException ("The type of the expression is not invokable");
  1139. var args = arguments.ToReadOnlyCollection ();
  1140. CheckForNull (args, "arguments");
  1141. var invoke = type.GetInvokeMethod ();
  1142. if (invoke == null)
  1143. throw new ArgumentException ("expression");
  1144. if (invoke.GetParameters ().Length != args.Count)
  1145. throw new InvalidOperationException ("Arguments count doesn't match parameters length");
  1146. args = CheckMethodArguments (invoke, args);
  1147. return new InvocationExpression (expression, invoke.ReturnType, args);
  1148. }
  1149. static bool CanAssign (Type target, Type source)
  1150. {
  1151. // This catches object and value type mixage, type compatibility is handled later
  1152. if (target.IsValueType ^ source.IsValueType)
  1153. return false;
  1154. return source.IsAssignableTo (target);
  1155. }
  1156. static Expression CheckLambda (Type delegateType, Expression body, ReadOnlyCollection<ParameterExpression> parameters)
  1157. {
  1158. if (!delegateType.IsSubclassOf (typeof (System.Delegate)))
  1159. throw new ArgumentException ("delegateType");
  1160. var invoke = delegateType.GetInvokeMethod ();
  1161. if (invoke == null)
  1162. throw new ArgumentException ("delegate must contain an Invoke method", "delegateType");
  1163. var invoke_parameters = invoke.GetParameters ();
  1164. if (invoke_parameters.Length != parameters.Count)
  1165. throw new ArgumentException (string.Format ("Different number of arguments in delegate {0}", delegateType), "delegateType");
  1166. for (int i = 0; i < invoke_parameters.Length; i++) {
  1167. var parameter = parameters [i];
  1168. if (parameter == null)
  1169. throw new ArgumentNullException ("parameters");
  1170. if (!CanAssign (parameter.Type, invoke_parameters [i].ParameterType))
  1171. throw new ArgumentException (String.Format ("Can not assign a {0} to a {1}", invoke_parameters [i].ParameterType, parameter.Type));
  1172. }
  1173. if (invoke.ReturnType != typeof (void)) {
  1174. if (!CanAssign (invoke.ReturnType, body.Type)) {
  1175. if (invoke.ReturnType.IsExpression ())
  1176. return Expression.Quote (body);
  1177. throw new ArgumentException (String.Format ("body type {0} can not be assigned to {1}", body.Type, invoke.ReturnType));
  1178. }
  1179. }
  1180. return body;
  1181. }
  1182. public static Expression<TDelegate> Lambda<TDelegate> (Expression body, params ParameterExpression [] parameters)
  1183. {
  1184. return Lambda<TDelegate> (body, parameters as IEnumerable<ParameterExpression>);
  1185. }
  1186. public static Expression<TDelegate> Lambda<TDelegate> (Expression body, IEnumerable<ParameterExpression> parameters)
  1187. {
  1188. if (body == null)
  1189. throw new ArgumentNullException ("body");
  1190. var ps = parameters.ToReadOnlyCollection ();
  1191. body = CheckLambda (typeof (TDelegate), body, ps);
  1192. return new Expression<TDelegate> (body, ps);
  1193. }
  1194. public static LambdaExpression Lambda (Expression body, params ParameterExpression [] parameters)
  1195. {
  1196. if (body == null)
  1197. throw new ArgumentNullException ("body");
  1198. if (parameters.Length > 4)
  1199. throw new ArgumentException ("Too many parameters");
  1200. return Lambda (GetDelegateType (body.Type, parameters), body, parameters);
  1201. }
  1202. static Type GetDelegateType (Type return_type, ParameterExpression [] parameters)
  1203. {
  1204. if (parameters == null)
  1205. parameters = new ParameterExpression [0];
  1206. if (return_type == typeof (void))
  1207. return GetActionType (parameters.Select (p => p.Type).ToArray ());
  1208. var types = new Type [parameters.Length + 1];
  1209. for (int i = 0; i < types.Length - 1; i++)
  1210. types [i] = parameters [i].Type;
  1211. types [types.Length - 1] = return_type;
  1212. return GetFuncType (types);
  1213. }
  1214. public static LambdaExpression Lambda (Type delegateType, Expression body, params ParameterExpression [] parameters)
  1215. {
  1216. return Lambda (delegateType, body, parameters as IEnumerable<ParameterExpression>);
  1217. }
  1218. static LambdaExpression CreateExpressionOf (Type type, Expression body, ReadOnlyCollection<ParameterExpression> parameters)
  1219. {
  1220. return (LambdaExpression) typeof (Expression<>).MakeGenericType (type).GetConstructor (
  1221. NonPublicInstance, null, new [] { typeof (Expression), typeof (ReadOnlyCollection<ParameterExpression>) }, null).Invoke (new object [] { body, parameters } );
  1222. }
  1223. public static LambdaExpression Lambda (Type delegateType, Expression body, IEnumerable<ParameterExpression> parameters)
  1224. {
  1225. if (delegateType == null)
  1226. throw new ArgumentNullException ("delegateType");
  1227. if (body == null)
  1228. throw new ArgumentNullException ("body");
  1229. var ps = parameters.ToReadOnlyCollection ();
  1230. body = CheckLambda (delegateType, body, ps);
  1231. return CreateExpressionOf (delegateType, body, ps);
  1232. }
  1233. public static MemberListBinding ListBind (MemberInfo member, params ElementInit [] initializers)
  1234. {
  1235. return ListBind (member, initializers as IEnumerable<ElementInit>);
  1236. }
  1237. static void CheckIsAssignableToIEnumerable (Type t)
  1238. {
  1239. if (!t.IsAssignableTo (typeof (IEnumerable)))
  1240. throw new ArgumentException (string.Format ("Type {0} doesn't implemen IEnumerable", t));
  1241. }
  1242. public static MemberListBinding ListBind (MemberInfo member, IEnumerable<ElementInit> initializers)
  1243. {
  1244. if (member == null)
  1245. throw new ArgumentNullException ("member");
  1246. if (initializers == null)
  1247. throw new ArgumentNullException ("initializers");
  1248. var inits = initializers.ToReadOnlyCollection ();
  1249. CheckForNull (inits, "initializers");
  1250. member.OnFieldOrProperty (
  1251. field => CheckIsAssignableToIEnumerable (field.FieldType),
  1252. prop => CheckIsAssignableToIEnumerable (prop.PropertyType));
  1253. return new MemberListBinding (member, inits);
  1254. }
  1255. public static MemberListBinding ListBind (MethodInfo propertyAccessor, params ElementInit [] initializers)
  1256. {
  1257. return ListBind (propertyAccessor, initializers as IEnumerable<ElementInit>);
  1258. }
  1259. static void CheckForNull<T> (ReadOnlyCollection<T> collection, string name) where T : class
  1260. {
  1261. foreach (var t in collection)
  1262. if (t == null)
  1263. throw new ArgumentNullException (name);
  1264. }
  1265. public static MemberListBinding ListBind (MethodInfo propertyAccessor, IEnumerable<ElementInit> initializers)
  1266. {
  1267. if (propertyAccessor == null)
  1268. throw new ArgumentNullException ("propertyAccessor");
  1269. if (initializers == null)
  1270. throw new ArgumentNullException ("initializers");
  1271. var inits = initializers.ToReadOnlyCollection ();
  1272. CheckForNull (inits, "initializers");
  1273. var prop = GetAssociatedProperty (propertyAccessor);
  1274. if (prop == null)
  1275. throw new ArgumentException ("propertyAccessor");
  1276. CheckIsAssignableToIEnumerable (prop.PropertyType);
  1277. return new MemberListBinding (prop, inits);
  1278. }
  1279. public static ListInitExpression ListInit (NewExpression newExpression, params ElementInit [] initializers)
  1280. {
  1281. return ListInit (newExpression, initializers as IEnumerable<ElementInit>);
  1282. }
  1283. public static ListInitExpression ListInit (NewExpression newExpression, IEnumerable<ElementInit> initializers)
  1284. {
  1285. var inits = CheckListInit (newExpression, initializers);
  1286. return new ListInitExpression (newExpression, inits);
  1287. }
  1288. public static ListInitExpression ListInit (NewExpression newExpression, params Expression [] initializers)
  1289. {
  1290. return ListInit (newExpression, initializers as IEnumerable<Expression>);
  1291. }
  1292. public static ListInitExpression ListInit (NewExpression newExpression, IEnumerable<Expression> initializers)
  1293. {
  1294. var inits = CheckListInit (newExpression, initializers);
  1295. var add_method = GetAddMethod (newExpression.Type, inits [0].Type);
  1296. if (add_method == null)
  1297. throw new InvalidOperationException ("No suitable add method found");
  1298. return new ListInitExpression (newExpression, CreateInitializers (add_method, inits));
  1299. }
  1300. static ReadOnlyCollection<ElementInit> CreateInitializers (MethodInfo add_method, ReadOnlyCollection<Expression> initializers)
  1301. {
  1302. return (from init in initializers select Expression.ElementInit (add_method, init)).ToReadOnlyCollection ();
  1303. }
  1304. static MethodInfo GetAddMethod (Type type, Type arg)
  1305. {
  1306. return type.GetMethod ("Add", PublicInstance | BindingFlags.IgnoreCase, null, new [] { arg }, null);
  1307. }
  1308. public static ListInitExpression ListInit (NewExpression newExpression, MethodInfo addMethod, params Expression [] initializers)
  1309. {
  1310. return ListInit (newExpression, addMethod, initializers as IEnumerable<Expression>);
  1311. }
  1312. static ReadOnlyCollection<T> CheckListInit<T> (NewExpression newExpression, IEnumerable<T> initializers) where T : class
  1313. {
  1314. if (newExpression == null)
  1315. throw new ArgumentNullException ("newExpression");
  1316. if (initializers == null)
  1317. throw new ArgumentNullException ("initializers");
  1318. if (!newExpression.Type.IsAssignableTo (typeof (IEnumerable)))
  1319. throw new InvalidOperationException ("The type of the new expression does not implement IEnumerable");
  1320. var inits = initializers.ToReadOnlyCollection ();
  1321. if (inits.Count == 0)
  1322. throw new ArgumentException ("Empty initializers");
  1323. CheckForNull (inits, "initializers");
  1324. return inits;
  1325. }
  1326. public static ListInitExpression ListInit (NewExpression newExpression, MethodInfo addMethod, IEnumerable<Expression> initializers)
  1327. {
  1328. var inits = CheckListInit (newExpression, initializers);
  1329. if (addMethod != null) {
  1330. if (addMethod.Name.ToLower (CultureInfo.InvariantCulture) != "add")
  1331. throw new ArgumentException ("addMethod");
  1332. var parameters = addMethod.GetParameters ();
  1333. if (parameters.Length != 1)
  1334. throw new ArgumentException ("addMethod");
  1335. foreach (var expression in inits)
  1336. if (!IsAssignableToParameterType (expression.Type, parameters [0]))
  1337. throw new InvalidOperationException ("Initializer not assignable to the add method parameter type");
  1338. }
  1339. if (addMethod == null)
  1340. addMethod = GetAddMethod (newExpression.Type, inits [0].Type);
  1341. if (addMethod == null)
  1342. throw new InvalidOperationException ("No suitable add method found");
  1343. return new ListInitExpression (newExpression, CreateInitializers (addMethod, inits));
  1344. }
  1345. public static MemberExpression MakeMemberAccess (Expression expression, MemberInfo member)
  1346. {
  1347. if (expression == null)
  1348. throw new ArgumentNullException ("expression");
  1349. if (member == null)
  1350. throw new ArgumentNullException ("member");
  1351. var field = member as FieldInfo;
  1352. if (field != null)
  1353. return Field (expression, field);
  1354. var property = member as PropertyInfo;
  1355. if (property != null)
  1356. return Property (expression, property);
  1357. throw new ArgumentException ("Member should either be a field or a property");
  1358. }
  1359. public static UnaryExpression MakeUnary (ExpressionType unaryType, Expression operand, Type type)
  1360. {
  1361. return MakeUnary (unaryType, operand, type, null);
  1362. }
  1363. public static UnaryExpression MakeUnary (ExpressionType unaryType, Expression operand, Type type, MethodInfo method)
  1364. {
  1365. switch (unaryType) {
  1366. case ExpressionType.ArrayLength:
  1367. return ArrayLength (operand);
  1368. case ExpressionType.Convert:
  1369. return Convert (operand, type, method);
  1370. case ExpressionType.ConvertChecked:
  1371. return ConvertChecked (operand, type, method);
  1372. case ExpressionType.Negate:
  1373. return Negate (operand, method);
  1374. case ExpressionType.NegateChecked:
  1375. return NegateChecked (operand, method);
  1376. case ExpressionType.Not:
  1377. return Not (operand, method);
  1378. case ExpressionType.Quote:
  1379. return Quote (operand);
  1380. case ExpressionType.TypeAs:
  1381. return TypeAs (operand, type);
  1382. case ExpressionType.UnaryPlus:
  1383. return UnaryPlus (operand, method);
  1384. }
  1385. throw new ArgumentException ("MakeUnary expect an unary operator");
  1386. }
  1387. public static MemberMemberBinding MemberBind (MemberInfo member, params MemberBinding [] bindings)
  1388. {
  1389. return MemberBind (member, bindings as IEnumerable<MemberBinding>);
  1390. }
  1391. public static MemberMemberBinding MemberBind (MemberInfo member, IEnumerable<MemberBinding> bindings)
  1392. {
  1393. if (member == null)
  1394. throw new ArgumentNullException ("member");
  1395. var type = member.OnFieldOrProperty (
  1396. field => field.FieldType,
  1397. prop => prop.PropertyType);
  1398. return new MemberMemberBinding (member, CheckMemberBindings (type, bindings));
  1399. }
  1400. public static MemberMemberBinding MemberBind (MethodInfo propertyAccessor, params MemberBinding [] bindings)
  1401. {
  1402. return MemberBind (propertyAccessor, bindings as IEnumerable<MemberBinding>);
  1403. }
  1404. public static MemberMemberBinding MemberBind (MethodInfo propertyAccessor, IEnumerable<MemberBinding> bindings)
  1405. {
  1406. if (propertyAccessor == null)
  1407. throw new ArgumentNullException ("propertyAccessor");
  1408. var bds = bindings.ToReadOnlyCollection ();
  1409. CheckForNull (bds, "bindings");
  1410. var prop = GetAssociatedProperty (propertyAccessor);
  1411. if (prop == null)
  1412. throw new ArgumentException ("propertyAccessor");
  1413. return new MemberMemberBinding (prop, CheckMemberBindings (prop.PropertyType, bindings));
  1414. }
  1415. static ReadOnlyCollection<MemberBinding> CheckMemberBindings (Type type, IEnumerable<MemberBinding> bindings)
  1416. {
  1417. if (bindings == null)
  1418. throw new ArgumentNullException ("bindings");
  1419. var bds = bindings.ToReadOnlyCollection ();
  1420. CheckForNull (bds, "bindings");
  1421. foreach (var binding in bds)
  1422. if (!type.IsAssignableTo (binding.Member.DeclaringType))
  1423. throw new ArgumentException ("Type not assignable to member type");
  1424. return bds;
  1425. }
  1426. public static MemberInitExpression MemberInit (NewExpression newExpression, params MemberBinding [] bindings)
  1427. {
  1428. return MemberInit (newExpression, bindings as IEnumerable<MemberBinding>);
  1429. }
  1430. public static MemberInitExpression MemberInit (NewExpression newExpression, IEnumerable<MemberBinding> bindings)
  1431. {
  1432. if (newExpression == null)
  1433. throw new ArgumentNullException ("newExpression");
  1434. return new MemberInitExpression (newExpression, CheckMemberBindings (newExpression.Type, bindings));
  1435. }
  1436. public static UnaryExpression Negate (Expression expression)
  1437. {
  1438. return Negate (expression, null);
  1439. }
  1440. public static UnaryExpression Negate (Expression expression, MethodInfo method)
  1441. {
  1442. method = UnaryCoreCheck ("op_UnaryNegation", expression, method, type => IsSignedNumber (type));
  1443. return MakeSimpleUnary (ExpressionType.Negate, expression, method);
  1444. }
  1445. public static UnaryExpression NegateChecked (Expression expression)
  1446. {
  1447. return NegateChecked (expression, null);
  1448. }
  1449. public static UnaryExpression NegateChecked (Expression expression, MethodInfo method)
  1450. {
  1451. method = UnaryCoreCheck ("op_UnaryNegation", expression, method, type => IsSignedNumber (type));
  1452. return MakeSimpleUnary (ExpressionType.NegateChecked, expression, method);
  1453. }
  1454. public static NewExpression New (ConstructorInfo constructor)
  1455. {
  1456. if (constructor == null)
  1457. throw new ArgumentNullException ("constructor");
  1458. if (constructor.GetParameters ().Length > 0)
  1459. throw new ArgumentException ("Constructor must be parameter less");
  1460. return new NewExpression (constructor, (null as IEnumerable<Expression>).ToReadOnlyCollection (), null);
  1461. }
  1462. public static NewExpression New (Type type)
  1463. {
  1464. if (type == null)
  1465. throw new ArgumentNullException ("type");
  1466. CheckNotVoid (type);
  1467. var args = (null as IEnumerable<Expression>).ToReadOnlyCollection ();
  1468. if (type.IsValueType)
  1469. return new NewExpression (type, args);
  1470. var ctor = type.GetConstructor (Type.EmptyTypes);
  1471. if (ctor == null)
  1472. throw new ArgumentException ("Type doesn't have a parameter less constructor");
  1473. return new NewExpression (ctor, args, null);
  1474. }
  1475. public static NewExpression New (ConstructorInfo constructor, params Expression [] arguments)
  1476. {
  1477. return New (constructor, arguments as IEnumerable<Expression>);
  1478. }
  1479. public static NewExpression New (ConstructorInfo constructor, IEnumerable<Expression> arguments)
  1480. {
  1481. if (constructor == null)
  1482. throw new ArgumentNullException ("constructor");
  1483. var args = CheckMethodArguments (constructor, arguments);
  1484. return new NewExpression (constructor, args, null);
  1485. }
  1486. static IList<Expression> CreateArgumentList (IEnumerable<Expression> arguments)
  1487. {
  1488. if (arguments == null)
  1489. return arguments.ToReadOnlyCollection ();
  1490. return arguments.ToList ();
  1491. }
  1492. static void CheckNonGenericMethod (MethodBase method)
  1493. {
  1494. if (method.IsGenericMethodDefinition || method.ContainsGenericParameters)
  1495. throw new ArgumentException ("Can not used open generic methods");
  1496. }
  1497. static ReadOnlyCollection<Expression> CheckMethodArguments (MethodBase method, IEnumerable<Expression> args)
  1498. {
  1499. CheckNonGenericMethod (method);
  1500. var arguments = CreateArgumentList (args);
  1501. var parameters = method.GetParameters ();
  1502. if (arguments.Count != parameters.Length)
  1503. throw new ArgumentException ("The number of arguments doesn't match the number of parameters");
  1504. for (int i = 0; i < parameters.Length; i++) {
  1505. if (arguments [i] == null)
  1506. throw new ArgumentNullException ("arguments");
  1507. if (!IsAssignableToParameterType (arguments [i].Type, parameters [i])) {
  1508. if (!parameters [i].ParameterType.IsExpression ())
  1509. throw new ArgumentException ("arguments");
  1510. arguments [i] = Expression.Quote (arguments [i]);
  1511. }
  1512. }
  1513. return arguments.ToReadOnlyCollection ();
  1514. }
  1515. public static NewExpression New (ConstructorInfo constructor, IEnumerable<Expression> arguments, params MemberInfo [] members)
  1516. {
  1517. return New (constructor, arguments, members as IEnumerable<MemberInfo>);
  1518. }
  1519. public static NewExpression New (ConstructorInfo constructor, IEnumerable<Expression> arguments, IEnumerable<MemberInfo> members)
  1520. {
  1521. if (constructor == null)
  1522. throw new ArgumentNullException ("constructor");
  1523. var args = arguments.ToReadOnlyCollection ();
  1524. var mmbs = members.ToReadOnlyCollection ();
  1525. CheckForNull (args, "arguments");
  1526. CheckForNull (mmbs, "members");
  1527. args = CheckMethodArguments (constructor, arguments);
  1528. if (args.Count != mmbs.Count)
  1529. throw new ArgumentException ("Arguments count does not match members count");
  1530. for (int i = 0; i < mmbs.Count; i++) {
  1531. var member = mmbs [i];
  1532. Type type = null;
  1533. switch (member.MemberType) {
  1534. case MemberTypes.Field:
  1535. type = (member as FieldInfo).FieldType;
  1536. break;
  1537. case MemberTypes.Method:
  1538. type = (member as MethodInfo).ReturnType;
  1539. break;
  1540. case MemberTypes.Property:
  1541. var prop = member as PropertyInfo;
  1542. if (prop.GetGetMethod (true) == null)
  1543. throw new ArgumentException ("Property must have a getter");
  1544. type = (member as PropertyInfo).PropertyType;
  1545. break;
  1546. default:
  1547. throw new ArgumentException ("Member type not allowed");
  1548. }
  1549. if (!args [i].Type.IsAssignableTo (type))
  1550. throw new ArgumentException ("Argument type not assignable to member type");
  1551. }
  1552. return new NewExpression (constructor, args, mmbs);
  1553. }
  1554. public static NewArrayExpression NewArrayBounds (Type type, params Expression [] bounds)
  1555. {
  1556. return NewArrayBounds (type, bounds as IEnumerable<Expression>);
  1557. }
  1558. public static NewArrayExpression NewArrayBounds (Type type, IEnumerable<Expression> bounds)
  1559. {
  1560. if (type == null)
  1561. throw new ArgumentNullException ("type");
  1562. if (bounds == null)
  1563. throw new ArgumentNullException ("bounds");
  1564. CheckNotVoid (type);
  1565. var array_bounds = bounds.ToReadOnlyCollection ();
  1566. foreach (var expression in array_bounds)
  1567. if (!IsInt (expression.Type))
  1568. throw new ArgumentException ("The bounds collection can only contain expression of integers types");
  1569. return new NewArrayExpression (ExpressionType.NewArrayBounds, type.MakeArrayType (array_bounds.Count), array_bounds);
  1570. }
  1571. public static NewArrayExpression NewArrayInit (Type type, params Expression [] initializers)
  1572. {
  1573. return NewArrayInit (type, initializers as IEnumerable<Expression>);
  1574. }
  1575. public static NewArrayExpression NewArrayInit (Type type, IEnumerable<Expression> initializers)
  1576. {
  1577. if (type == null)
  1578. throw new ArgumentNullException ("type");
  1579. if (initializers == null)
  1580. throw new ArgumentNullException ("initializers");
  1581. CheckNotVoid (type);
  1582. var inits = initializers.ToReadOnlyCollection ();
  1583. foreach (var expression in inits) {
  1584. if (expression == null)
  1585. throw new ArgumentNullException ("initializers");
  1586. if (!expression.Type.IsAssignableTo (type))
  1587. throw new InvalidOperationException (
  1588. string.Format ("{0} IsAssignableTo {1}, expression [ {2} ] : {3}", expression.Type, type, expression.NodeType, expression));
  1589. // TODO: Quote elements if type == typeof (Expression)
  1590. }
  1591. return new NewArrayExpression (ExpressionType.NewArrayInit, type.MakeArrayType (), inits);
  1592. }
  1593. public static UnaryExpression Not (Expression expression)
  1594. {
  1595. return Not (expression, null);
  1596. }
  1597. public static UnaryExpression Not (Expression expression, MethodInfo method)
  1598. {
  1599. Func<Type, bool> validator = type => IsIntOrBool (type);
  1600. method = UnaryCoreCheck ("op_LogicalNot", expression, method, validator);
  1601. if (method == null)
  1602. method = UnaryCoreCheck ("op_OnesComplement", expression, method, validator);
  1603. return MakeSimpleUnary (ExpressionType.Not, expression, method);
  1604. }
  1605. static void CheckNotVoid (Type type)
  1606. {
  1607. if (type == typeof (void))
  1608. throw new ArgumentException ("Type can't be void");
  1609. }
  1610. public static ParameterExpression Parameter (Type type, string name)
  1611. {
  1612. if (type == null)
  1613. throw new ArgumentNullException ("type");
  1614. CheckNotVoid (type);
  1615. return new ParameterExpression (type, name);
  1616. }
  1617. public static MemberExpression Property (Expression expression, MethodInfo propertyAccessor)
  1618. {
  1619. if (propertyAccessor == null)
  1620. throw new ArgumentNullException ("propertyAccessor");
  1621. CheckNonGenericMethod (propertyAccessor);
  1622. if (!propertyAccessor.IsStatic) {
  1623. if (expression == null)
  1624. throw new ArgumentNullException ("expression");
  1625. if (!expression.Type.IsAssignableTo (propertyAccessor.DeclaringType))
  1626. throw new ArgumentException ("expression");
  1627. } else if (expression != null)
  1628. throw new ArgumentException ("expression");
  1629. var prop = GetAssociatedProperty (propertyAccessor);
  1630. if (prop == null)
  1631. throw new ArgumentException (string.Format ("Method {0} has no associated property", propertyAccessor));
  1632. return new MemberExpression (expression, prop, prop.PropertyType);
  1633. }
  1634. static PropertyInfo GetAssociatedProperty (MethodInfo method)
  1635. {
  1636. if (method == null)
  1637. return null;
  1638. foreach (var prop in method.DeclaringType.GetProperties (All)) {
  1639. if (method.Equals (prop.GetGetMethod (true)))
  1640. return prop;
  1641. if (method.Equals (prop.GetSetMethod (true)))
  1642. return prop;
  1643. }
  1644. return null;
  1645. }
  1646. public static MemberExpression Property (Expression expression, PropertyInfo property)
  1647. {
  1648. if (property == null)
  1649. throw new ArgumentNullException ("property");
  1650. var getter = property.GetGetMethod (true);
  1651. if (getter == null)
  1652. throw new ArgumentException ("getter");
  1653. if (!getter.IsStatic) {
  1654. if (expression == null)
  1655. throw new ArgumentNullException ("expression");
  1656. if (!expression.Type.IsAssignableTo (property.DeclaringType))
  1657. throw new ArgumentException ("expression");
  1658. } else if (expression != null)
  1659. throw new ArgumentException ("expression");
  1660. return new MemberExpression (expression, property, property.PropertyType);
  1661. }
  1662. public static MemberExpression Property (Expression expression, string propertyName)
  1663. {
  1664. if (expression == null)
  1665. throw new ArgumentNullException ("expression");
  1666. var prop = expression.Type.GetProperty (propertyName, AllInstance);
  1667. if (prop == null)
  1668. throw new ArgumentException (string.Format ("No property named {0} on {1}", propertyName, expression.Type));
  1669. return new MemberExpression (expression, prop, prop.PropertyType);
  1670. }
  1671. public static MemberExpression PropertyOrField (Expression expression, string propertyOrFieldName)
  1672. {
  1673. if (expression == null)
  1674. throw new ArgumentNullException ("expression");
  1675. if (propertyOrFieldName == null)
  1676. throw new ArgumentNullException ("propertyOrFieldName");
  1677. var prop = expression.Type.GetProperty (propertyOrFieldName, AllInstance);
  1678. if (prop != null)
  1679. return new MemberExpression (expression, prop, prop.PropertyType);
  1680. var field = expression.Type.GetField (propertyOrFieldName, AllInstance);
  1681. if (field != null)
  1682. return new MemberExpression (expression, field, field.FieldType);
  1683. throw new ArgumentException (string.Format ("No field or property named {0} on {1}", propertyOrFieldName, expression.Type));
  1684. }
  1685. public static UnaryExpression Quote (Expression expression)
  1686. {
  1687. if (expression == null)
  1688. throw new ArgumentNullException ("expression");
  1689. return new UnaryExpression (ExpressionType.Quote, expression, expression.GetType ());
  1690. }
  1691. public static UnaryExpression TypeAs (Expression expression, Type type)
  1692. {
  1693. if (expression == null)
  1694. throw new ArgumentNullException ("expression");
  1695. if (type == null)
  1696. throw new ArgumentNullException ("type");
  1697. if (type.IsValueType && !type.IsNullable ())
  1698. throw new ArgumentException ("TypeAs expect a reference or a nullable type");
  1699. return new UnaryExpression (ExpressionType.TypeAs, expression, type);
  1700. }
  1701. public static TypeBinaryExpression TypeIs (Expression expression, Type type)
  1702. {
  1703. if (expression == null)
  1704. throw new ArgumentNullException ("expression");
  1705. if (type == null)
  1706. throw new ArgumentNullException ("type");
  1707. CheckNotVoid (type);
  1708. return new TypeBinaryExpression (ExpressionType.TypeIs, expression, type, typeof (bool));
  1709. }
  1710. public static UnaryExpression UnaryPlus (Expression expression)
  1711. {
  1712. return UnaryPlus (expression, null);
  1713. }
  1714. public static UnaryExpression UnaryPlus (Expression expression, MethodInfo method)
  1715. {
  1716. method = UnaryCoreCheck ("op_UnaryPlus", expression, method, type => IsNumber (type));
  1717. return MakeSimpleUnary (ExpressionType.UnaryPlus, expression, method);
  1718. }
  1719. static bool IsInt (Type t)
  1720. {
  1721. return t == typeof (byte) || t == typeof (sbyte) ||
  1722. t == typeof (short) || t == typeof (ushort) ||
  1723. t == typeof (int) || t == typeof (uint) ||
  1724. t == typeof (long) || t == typeof (ulong);
  1725. }
  1726. static bool IsIntOrBool (Type t)
  1727. {
  1728. return IsInt (t) || t == typeof (bool);
  1729. }
  1730. static bool IsNumber (Type t)
  1731. {
  1732. if (IsInt (t))
  1733. return true;
  1734. return t == typeof (float) || t == typeof (double);
  1735. }
  1736. static bool IsSignedNumber (Type t)
  1737. {
  1738. return IsNumber (t) && !IsUnsigned (t);
  1739. }
  1740. internal static bool IsUnsigned (Type t)
  1741. {
  1742. #if !TARGET_JVM
  1743. if (t.IsPointer)
  1744. return IsUnsigned (t.GetElementType ());
  1745. #endif
  1746. return t == typeof (ushort) ||
  1747. t == typeof (uint) ||
  1748. t == typeof (ulong) ||
  1749. t == typeof (byte);
  1750. }
  1751. //
  1752. // This method must be overwritten by derived classes to
  1753. // compile the expression
  1754. //
  1755. internal virtual void Emit (EmitContext ec)
  1756. {
  1757. throw new NotImplementedException (String.Format ("Emit method is not implemented in expression type {0}", GetType ()));
  1758. }
  1759. }
  1760. }