Expression.cs 59 KB

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