Expression.cs 71 KB

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