Expression.cs 66 KB

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