Expression.cs 60 KB

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