Expression.cs 66 KB

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