Expression.cs 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290
  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 !TARGET_JVM
  1770. if (t.IsPointer)
  1771. return IsUnsigned (t.GetElementType ());
  1772. #endif
  1773. return t == typeof (ushort) ||
  1774. t == typeof (uint) ||
  1775. t == typeof (ulong) ||
  1776. t == typeof (byte);
  1777. }
  1778. //
  1779. // This method must be overwritten by derived classes to
  1780. // compile the expression
  1781. //
  1782. #if !FULL_AOT_RUNTIME
  1783. internal virtual void Emit (EmitContext ec)
  1784. {
  1785. throw new NotImplementedException (String.Format ("Emit method is not implemented in expression type {0}", GetType ()));
  1786. }
  1787. #endif
  1788. }
  1789. }