Expression.cs 67 KB

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