Expression.cs 63 KB

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