Expression.cs 65 KB

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