Expression.cs 56 KB

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