Expression.cs 66 KB

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