Expression.cs 71 KB

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