Expression.cs 54 KB

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