Expression.cs 69 KB

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