Expression.cs 60 KB

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