| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126 |
- //
- // Expression.cs
- //
- // Author:
- // Jb Evain ([email protected])
- // Miguel de Icaza ([email protected])
- //
- // (C) 2008 Novell, Inc. (http://www.novell.com)
- //
- // Permission is hereby granted, free of charge, to any person obtaining
- // a copy of this software and associated documentation files (the
- // "Software"), to deal in the Software without restriction, including
- // without limitation the rights to use, copy, modify, merge, publish,
- // distribute, sublicense, and/or sell copies of the Software, and to
- // permit persons to whom the Software is furnished to do so, subject to
- // the following conditions:
- //
- // The above copyright notice and this permission notice shall be
- // included in all copies or substantial portions of the Software.
- //
- // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
- // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
- // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
- // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
- //
- using System;
- using System.Collections;
- using System.Collections.Generic;
- using System.Collections.ObjectModel;
- using System.Linq;
- using System.Reflection;
- using System.Reflection.Emit;
- namespace System.Linq.Expressions {
- public abstract class Expression {
- ExpressionType node_type;
- Type type;
- const BindingFlags PublicInstance = BindingFlags.Public | BindingFlags.Instance;
- const BindingFlags NonPublicInstance = BindingFlags.NonPublic | BindingFlags.Instance;
- const BindingFlags PublicStatic = BindingFlags.Public | BindingFlags.Static;
- const BindingFlags AllInstance = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance;
- const BindingFlags AllStatic = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static;
- const BindingFlags All = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance;
- public ExpressionType NodeType {
- get { return node_type; }
- }
- public Type Type {
- get { return type; }
- }
- protected Expression (ExpressionType node_type, Type type)
- {
- this.node_type = node_type;
- this.type = type;
- }
- public override string ToString ()
- {
- return ExpressionPrinter.ToString (this);
- }
- #region Binary Expressions
- static MethodInfo GetUnaryOperator (string oper_name, Type declaring, Type param)
- {
- return GetUnaryOperator (oper_name, declaring, param, null);
- }
- static MethodInfo GetUnaryOperator (string oper_name, Type declaring, Type param, Type ret)
- {
- var methods = declaring.GetMethods (PublicStatic);
- foreach (var method in methods) {
- if (method.Name != oper_name)
- continue;
- var parameters = method.GetParameters ();
- if (parameters.Length != 1)
- continue;
- if (!IsAssignableToParameterType (param, parameters [0]))
- continue;
- if (ret != null && method.ReturnType != GetNotNullableOf (ret))
- continue;
- return method;
- }
- return null;
- }
- static bool IsAssignableToParameterType (Type type, ParameterInfo param)
- {
- var ptype = param.ParameterType;
- if (ptype.IsByRef)
- ptype = ptype.GetElementType ();
- return GetNotNullableOf (type).IsAssignableTo (ptype);
- }
- static MethodInfo CheckUnaryMethod (MethodInfo method, Type param)
- {
- if (method.ReturnType == typeof (void))
- throw new ArgumentException ("Specified method must return a value", "method");
- if (!method.IsStatic)
- throw new ArgumentException ("Method must be static", "method");
- var parameters = method.GetParameters ();
- if (parameters.Length != 1)
- throw new ArgumentException ("Must have only one parameters", "method");
- if (!IsAssignableToParameterType (param, parameters [0]))
- throw new InvalidOperationException ("left-side argument type does not match expression type");
- return method;
- }
- static MethodInfo UnaryCoreCheck (string oper_name, Expression expression, MethodInfo method, Func<Type, bool> validator)
- {
- if (expression == null)
- throw new ArgumentNullException ("expression");
- if (method != null)
- return CheckUnaryMethod (method, expression.Type);
- var type = GetNotNullableOf (expression.Type);
- if (validator (type))
- return null;
- if (oper_name != null) {
- method = GetUnaryOperator (oper_name, type, expression.Type);
- if (method != null)
- return method;
- }
- throw new InvalidOperationException (
- string.Format ("Operation {0} not defined for {1}", oper_name != null ? oper_name.Substring (3) : "is", expression.Type));
- }
- static MethodInfo GetBinaryOperator (string oper_name, Type on_type, Expression left, Expression right)
- {
- MethodInfo [] methods = on_type.GetMethods (PublicStatic);
- foreach (var method in methods) {
- if (method.Name != oper_name)
- continue;
- var parameters = method.GetParameters ();
- if (parameters.Length != 2)
- continue;
- if (!IsAssignableToParameterType (left.Type, parameters [0]))
- continue;
- if (!IsAssignableToParameterType (right.Type, parameters [1]))
- continue;
- // Method has papers in order.
- return method;
- }
- return null;
- }
- //
- // Performs basic checks on the incoming expressions for binary expressions
- // and any provided MethodInfo.
- //
- static MethodInfo BinaryCoreCheck (string oper_name, Expression left, Expression right, MethodInfo method)
- {
- if (left == null)
- throw new ArgumentNullException ("left");
- if (right == null)
- throw new ArgumentNullException ("right");
- if (method != null){
- if (method.ReturnType == typeof (void))
- throw new ArgumentException ("Specified method must return a value", "method");
- if (!method.IsStatic)
- throw new ArgumentException ("Method must be static", "method");
- var parameters = method.GetParameters ();
- if (parameters.Length != 2)
- throw new ArgumentException ("Must have only two parameters", "method");
- if (!IsAssignableToParameterType (left.Type, parameters [0]))
- throw new InvalidOperationException ("left-side argument type does not match left expression type");
- if (!IsAssignableToParameterType (right.Type, parameters [1]))
- throw new InvalidOperationException ("right-side argument type does not match right expression type");
- return method;
- } else {
- Type ltype = left.Type;
- Type rtype = right.Type;
- Type ultype = GetNotNullableOf (ltype);
- Type urtype = GetNotNullableOf (rtype);
- if (oper_name == "op_BitwiseOr" || oper_name == "op_BitwiseAnd") {
- if (ultype == typeof (bool)) {
- if (ultype == urtype && ltype == rtype)
- return null;
- }
- }
- // Use IsNumber to avoid expensive reflection.
- if (IsNumber (ultype)){
- if (ultype == urtype && ltype == rtype)
- return null;
- if (oper_name != null){
- method = GetBinaryOperator (oper_name, urtype, left, right);
- if (method != null)
- return method;
- }
- }
- if (oper_name != null){
- method = GetBinaryOperator (oper_name, ultype, left, right);
- if (method != null)
- return method;
- }
- //
- // == and != allow reference types without operators defined.
- //
- if (!ltype.IsValueType && !rtype.IsValueType &&
- (oper_name == "op_Equality" || oper_name == "op_Inequality"))
- return null;
- throw new InvalidOperationException (
- String.Format ("Operation {0} not defined for {1} and {2}", oper_name != null ? oper_name.Substring (3) : "is", ltype, rtype));
- }
- }
- //
- // This is like BinaryCoreCheck, but if no method is used adds the restriction that
- // only ints and bools are allowed
- //
- static MethodInfo BinaryBitwiseCoreCheck (string oper_name, Expression left, Expression right, MethodInfo method)
- {
- if (left == null)
- throw new ArgumentNullException ("left");
- if (right == null)
- throw new ArgumentNullException ("right");
- if (method == null) {
- // avoid reflection shortcut and catches Ints/bools before we check Numbers in general
- if (left.Type == right.Type && IsIntOrBool (left.Type))
- return null;
- }
- method = BinaryCoreCheck (oper_name, left, right, method);
- if (method == null) {
- // The check in BinaryCoreCheck allows a bit more than we do
- // (floats and doubles). Catch this here
- if (left.Type == typeof (double) || left.Type == typeof (float))
- throw new InvalidOperationException ("Types not supported");
- }
- return method;
- }
- static Type GetResultType (Expression expression, MethodInfo method)
- {
- return method == null ? expression.Type : method.ReturnType;
- }
- static BinaryExpression MakeSimpleBinary (ExpressionType et, Expression left, Expression right, MethodInfo method)
- {
- bool is_lifted;
- if (method == null) {
- if (IsNullable (left.Type)) {
- if (!IsNullable (right.Type))
- throw new InvalidOperationException ("Assertion, internal error: left is nullable, requires right to be as well");
- is_lifted = true;
- } else
- is_lifted = false;
- } else {
- //
- // FIXME: implement
- //
- is_lifted = false;
- }
- return new BinaryExpression (et, GetResultType (left, method), left, right, is_lifted, is_lifted, method, null);
- }
- static UnaryExpression MakeSimpleUnary (ExpressionType et, Expression expression, MethodInfo method)
- {
- bool is_lifted;
- if (method == null) {
- is_lifted = IsNullable (expression.Type);
- } else {
- // FIXME: implement
- is_lifted = false;
- }
- return new UnaryExpression (et, expression, GetResultType (expression, method), method, is_lifted);
- }
- static BinaryExpression MakeBoolBinary (ExpressionType et, Expression left, Expression right, bool liftToNull, MethodInfo method)
- {
- Type result;
- Type ltype = left.Type;
- Type rtype = right.Type;
- bool lnullable = IsNullable (ltype);
- bool rnullable = IsNullable (rtype);
- bool is_lifted;
- // Implement the rules as described in "Expression.Equal" method.
- if (method == null) {
- if (!lnullable && !rnullable) {
- is_lifted = false;
- liftToNull = false;
- result = typeof (bool);
- } else if (lnullable && rnullable) {
- is_lifted = true;
- result = liftToNull ? typeof(bool?) : typeof (bool);
- } else
- throw new InvalidOperationException ("Internal error: this should have been caught in BinaryCoreCheck");
- } else {
- ParameterInfo [] pi = method.GetParameters ();
- Type mltype = pi [0].ParameterType;
- Type mrtype = pi [1].ParameterType;
- if (ltype == mltype && rtype == mrtype) {
- is_lifted = false;
- liftToNull = false;
- result = method.ReturnType;
- } else if (ltype.IsValueType && rtype.IsValueType &&
- ((lnullable && GetNullableOf (ltype) == mltype) ||
- (rnullable && GetNullableOf (rtype) == mrtype))){
- is_lifted = true;
- if (method.ReturnType == typeof(bool)){
- result = liftToNull ? typeof(bool?) : typeof(bool);
- } else {
- //
- // This behavior is not documented: what
- // happens if the result is not typeof(bool), but
- // the parameters are nullable: the result
- // becomes nullable<returntype>
- //
- // See:
- // https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=323139
- result = typeof (Nullable<>).MakeGenericType (method.ReturnType);
- }
- } else {
- is_lifted = false;
- liftToNull = false;
- result = method.ReturnType;
- }
- }
- return new BinaryExpression (et, result, left, right, liftToNull, is_lifted, method, null);
- }
- //
- // Arithmetic
- //
- public static BinaryExpression Add (Expression left, Expression right)
- {
- return Add (left, right, null);
- }
- public static BinaryExpression Add (Expression left, Expression right, MethodInfo method)
- {
- method = BinaryCoreCheck ("op_Addition", left, right, method);
- return MakeSimpleBinary (ExpressionType.Add, left, right, method);
- }
- public static BinaryExpression AddChecked (Expression left, Expression right)
- {
- return AddChecked (left, right, null);
- }
- public static BinaryExpression AddChecked (Expression left, Expression right, MethodInfo method)
- {
- method = BinaryCoreCheck ("op_Addition", left, right, method);
- // The check in BinaryCoreCheck allows a bit more than we do
- // (byte, sbyte). Catch that here
- if (method == null) {
- if (left.Type == typeof (byte) || left.Type == typeof (sbyte))
- throw new InvalidOperationException (String.Format ("AddChecked not defined for {0} and {1}", left.Type, right.Type));
- }
- return MakeSimpleBinary (ExpressionType.AddChecked, left, right, method);
- }
- public static BinaryExpression Subtract (Expression left, Expression right)
- {
- return Subtract (left, right, null);
- }
- public static BinaryExpression Subtract (Expression left, Expression right, MethodInfo method)
- {
- method = BinaryCoreCheck ("op_Subtraction", left, right, method);
- return MakeSimpleBinary (ExpressionType.Subtract, left, right, method);
- }
- public static BinaryExpression SubtractChecked (Expression left, Expression right)
- {
- return SubtractChecked (left, right, null);
- }
- public static BinaryExpression SubtractChecked (Expression left, Expression right, MethodInfo method)
- {
- method = BinaryCoreCheck ("op_Subtraction", left, right, method);
- // The check in BinaryCoreCheck allows a bit more than we do
- // (byte, sbyte). Catch that here
- if (method == null) {
- if (left.Type == typeof (byte) || left.Type == typeof (sbyte))
- throw new InvalidOperationException (String.Format ("SubtractChecked not defined for {0} and {1}", left.Type, right.Type));
- }
- return MakeSimpleBinary (ExpressionType.SubtractChecked, left, right, method);
- }
- public static BinaryExpression Modulo (Expression left, Expression right)
- {
- return Modulo (left, right, null);
- }
- public static BinaryExpression Modulo (Expression left, Expression right, MethodInfo method)
- {
- method = BinaryCoreCheck ("op_Modulus", left, right, method);
- return MakeSimpleBinary (ExpressionType.Modulo, left, right, method);
- }
- public static BinaryExpression Multiply (Expression left, Expression right)
- {
- return Multiply (left, right, null);
- }
- public static BinaryExpression Multiply (Expression left, Expression right, MethodInfo method)
- {
- method = BinaryCoreCheck ("op_Multiply", left, right, method);
- return MakeSimpleBinary (ExpressionType.Multiply, left, right, method);
- }
- public static BinaryExpression MultiplyChecked (Expression left, Expression right)
- {
- return MultiplyChecked (left, right, null);
- }
- public static BinaryExpression MultiplyChecked (Expression left, Expression right, MethodInfo method)
- {
- method = BinaryCoreCheck ("op_Multiply", left, right, method);
- return MakeSimpleBinary (ExpressionType.MultiplyChecked, left, right, method);
- }
- public static BinaryExpression Divide (Expression left, Expression right)
- {
- return Divide (left, right, null);
- }
- public static BinaryExpression Divide (Expression left, Expression right, MethodInfo method)
- {
- method = BinaryCoreCheck ("op_Division", left, right, method);
- return MakeSimpleBinary (ExpressionType.Divide, left, right, method);
- }
- public static BinaryExpression Power (Expression left, Expression right)
- {
- return Power (left, right, null);
- }
- public static BinaryExpression Power (Expression left, Expression right, MethodInfo method)
- {
- method = BinaryCoreCheck (null, left, right, method);
- if (left.Type != typeof (double))
- throw new InvalidOperationException ("Power only supports double arguments");
- return MakeSimpleBinary (ExpressionType.Power, left, right, method);
- }
- //
- // Bitwise
- //
- public static BinaryExpression And (Expression left, Expression right)
- {
- return And (left, right, null);
- }
- public static BinaryExpression And (Expression left, Expression right, MethodInfo method)
- {
- method = BinaryBitwiseCoreCheck ("op_BitwiseAnd", left, right, method);
- return MakeSimpleBinary (ExpressionType.And, left, right, method);
- }
- public static BinaryExpression Or (Expression left, Expression right)
- {
- return Or (left, right, null);
- }
- public static BinaryExpression Or (Expression left, Expression right, MethodInfo method)
- {
- method = BinaryBitwiseCoreCheck ("op_BitwiseOr", left, right, method);
- return MakeSimpleBinary (ExpressionType.Or, left, right, method);
- }
- public static BinaryExpression ExclusiveOr (Expression left, Expression right)
- {
- return ExclusiveOr (left, right, null);
- }
- public static BinaryExpression ExclusiveOr (Expression left, Expression right, MethodInfo method)
- {
- method = BinaryBitwiseCoreCheck ("op_ExclusiveOr", left, right, method);
- return MakeSimpleBinary (ExpressionType.ExclusiveOr, left, right, method);
- }
- public static BinaryExpression LeftShift (Expression left, Expression right)
- {
- return LeftShift (left, right, null);
- }
- public static BinaryExpression LeftShift (Expression left, Expression right, MethodInfo method)
- {
- method = BinaryBitwiseCoreCheck ("op_LeftShift", left, right, method);
- return MakeSimpleBinary (ExpressionType.LeftShift, left, right, method);
- }
- public static BinaryExpression RightShift (Expression left, Expression right)
- {
- return RightShift (left, right, null);
- }
- public static BinaryExpression RightShift (Expression left, Expression right, MethodInfo method)
- {
- method = BinaryCoreCheck ("op_RightShift", left, right, method);
- return MakeSimpleBinary (ExpressionType.RightShift, left, right, method);
- }
- //
- // Short-circuit
- //
- public static BinaryExpression AndAlso (Expression left, Expression right)
- {
- return AndAlso (left, right, null);
- }
- public static BinaryExpression AndAlso (Expression left, Expression right, MethodInfo method)
- {
- method = ConditionalBinaryCheck ("op_BitwiseAnd", left, right, method);
- return MakeBoolBinary (ExpressionType.AndAlso, left, right, true, method);
- }
- static MethodInfo ConditionalBinaryCheck (string oper, Expression left, Expression right, MethodInfo method)
- {
- method = BinaryCoreCheck (oper, left, right, method);
- if (method == null) {
- if (GetNotNullableOf (left.Type) != typeof (bool))
- throw new InvalidOperationException ("Only booleans are allowed");
- } else {
- // The method should have identical parameter and return types.
- if (left.Type != right.Type || method.ReturnType != left.Type)
- throw new ArgumentException ("left, right and return type must match");
- }
- return method;
- }
- public static BinaryExpression OrElse (Expression left, Expression right)
- {
- return OrElse (left, right, null);
- }
- public static BinaryExpression OrElse (Expression left, Expression right, MethodInfo method)
- {
- method = ConditionalBinaryCheck ("op_BitwiseOr", left, right, method);
- return MakeBoolBinary (ExpressionType.OrElse, left, right, true, method);
- }
- //
- // Comparison
- //
- public static BinaryExpression Equal (Expression left, Expression right)
- {
- return Equal (left, right, false, null);
- }
- public static BinaryExpression Equal (Expression left, Expression right, bool liftToNull, MethodInfo method)
- {
- method = BinaryCoreCheck ("op_Equality", left, right, method);
- return MakeBoolBinary (ExpressionType.Equal, left, right, liftToNull, method);
- }
- public static BinaryExpression NotEqual (Expression left, Expression right)
- {
- return NotEqual (left, right, false, null);
- }
- public static BinaryExpression NotEqual (Expression left, Expression right, bool liftToNull, MethodInfo method)
- {
- method = BinaryCoreCheck ("op_Inequality", left, right, method);
- return MakeBoolBinary (ExpressionType.NotEqual, left, right, liftToNull, method);
- }
- public static BinaryExpression GreaterThan (Expression left, Expression right)
- {
- return GreaterThan (left, right, false, null);
- }
- public static BinaryExpression GreaterThan (Expression left, Expression right, bool liftToNull, MethodInfo method)
- {
- method = BinaryCoreCheck ("op_GreaterThan", left, right, method);
- return MakeBoolBinary (ExpressionType.GreaterThan, left, right, liftToNull, method);
- }
- public static BinaryExpression GreaterThanOrEqual (Expression left, Expression right)
- {
- return GreaterThanOrEqual (left, right, false, null);
- }
- public static BinaryExpression GreaterThanOrEqual (Expression left, Expression right, bool liftToNull, MethodInfo method)
- {
- method = BinaryCoreCheck ("op_GreaterThanOrEqual", left, right, method);
- return MakeBoolBinary (ExpressionType.GreaterThanOrEqual, left, right, liftToNull, method);
- }
- public static BinaryExpression LessThan (Expression left, Expression right)
- {
- return LessThan (left, right, false, null);
- }
- public static BinaryExpression LessThan (Expression left, Expression right, bool liftToNull, MethodInfo method)
- {
- method = BinaryCoreCheck ("op_LessThan", left, right, method);
- return MakeBoolBinary (ExpressionType.LessThan, left, right, liftToNull, method);
- }
- public static BinaryExpression LessThanOrEqual (Expression left, Expression right)
- {
- return LessThanOrEqual (left, right, false, null);
- }
- public static BinaryExpression LessThanOrEqual (Expression left, Expression right, bool liftToNull, MethodInfo method)
- {
- method = BinaryCoreCheck ("op_LessThanOrEqual", left, right, method);
- return MakeBoolBinary (ExpressionType.LessThanOrEqual, left, right, liftToNull, method);
- }
- //
- // Miscelaneous
- //
- static void CheckArray (Expression array)
- {
- if (array == null)
- throw new ArgumentNullException ("array");
- if (!array.Type.IsArray)
- throw new ArgumentException ("The array argument must be of type array");
- }
- public static BinaryExpression ArrayIndex (Expression array, Expression index)
- {
- CheckArray (array);
- if (index == null)
- throw new ArgumentNullException ("index");
- if (array.Type.GetArrayRank () != 1)
- throw new ArgumentException ("The array argument must be a single dimensional array");
- if (index.Type != typeof (int))
- throw new ArgumentException ("The index must be of type int");
- return new BinaryExpression (ExpressionType.ArrayIndex, array.Type.GetElementType (), array, index);
- }
- public static BinaryExpression Coalesce (Expression left, Expression right)
- {
- return Coalesce (left, right, null);
- }
- public static BinaryExpression Coalesce (Expression left, Expression right, LambdaExpression conversion)
- {
- if (left == null)
- throw new ArgumentNullException ("left");
- if (right == null)
- throw new ArgumentNullException ("right");
- //
- // First arg must ne nullable (either Nullable<T> or a reference type
- //
- if (left.Type.IsValueType && !IsNullable (left.Type))
- throw new InvalidOperationException ("Left expression can never be null");
- Type result = null;
- if (IsNullable (left.Type)) {
- Type lbase = GetNullableOf (left.Type);
- if (!IsNullable (right.Type) && right.Type.IsAssignableTo (lbase))
- result = lbase;
- }
- if (result == null && right.Type.IsAssignableTo (left.Type))
- result = left.Type;
- if (result == null) {
- if (IsNullable (left.Type) && GetNullableOf (left.Type).IsAssignableTo (right.Type))
- result = right.Type;
- }
- if (result == null)
- throw new ArgumentException ("Incompatible argument types");
- //
- // FIXME: What do we do with "conversion"?
- //
- return new BinaryExpression (ExpressionType.Coalesce, result, left, right, false, false, null, conversion);
- }
- //
- // MakeBinary constructors
- //
- public static BinaryExpression MakeBinary (ExpressionType binaryType, Expression left, Expression right)
- {
- return MakeBinary (binaryType, left, right, false, null);
- }
- public static BinaryExpression MakeBinary (ExpressionType binaryType, Expression left, Expression right, bool liftToNull, MethodInfo method)
- {
- return MakeBinary (binaryType, left, right, liftToNull, method, null);
- }
- public static BinaryExpression MakeBinary (ExpressionType binaryType, Expression left, Expression right, bool liftToNull, MethodInfo method, LambdaExpression conversion)
- {
- switch (binaryType) {
- case ExpressionType.Add:
- return Add (left, right, method);
- case ExpressionType.AddChecked:
- return AddChecked (left, right, method);
- case ExpressionType.AndAlso:
- return AndAlso (left, right);
- case ExpressionType.Coalesce:
- return Coalesce (left, right, conversion);
- case ExpressionType.Divide:
- return Divide (left, right, method);
- case ExpressionType.Equal:
- return Equal (left, right, liftToNull, method);
- case ExpressionType.ExclusiveOr:
- return ExclusiveOr (left, right, method);
- case ExpressionType.GreaterThan:
- return GreaterThan (left, right, liftToNull, method);
- case ExpressionType.GreaterThanOrEqual:
- return GreaterThanOrEqual (left, right, liftToNull, method);
- case ExpressionType.LeftShift:
- return LeftShift (left, right, method);
- case ExpressionType.LessThan:
- return LessThan (left, right, liftToNull, method);
- case ExpressionType.LessThanOrEqual:
- return LessThanOrEqual (left, right, liftToNull, method);
- case ExpressionType.Modulo:
- return Modulo (left, right, method);
- case ExpressionType.Multiply:
- return Multiply (left, right, method);
- case ExpressionType.MultiplyChecked:
- return MultiplyChecked (left, right, method);
- case ExpressionType.NotEqual:
- return NotEqual (left, right, liftToNull, method);
- case ExpressionType.OrElse:
- return OrElse (left, right);
- case ExpressionType.Power:
- return Power (left, right, method);
- case ExpressionType.RightShift:
- return RightShift (left, right, method);
- case ExpressionType.Subtract:
- return Subtract (left, right, method);
- case ExpressionType.SubtractChecked:
- return SubtractChecked (left, right, method);
- case ExpressionType.And:
- return And (left, right, method);
- case ExpressionType.Or:
- return Or (left, right, method);
- }
- throw new ArgumentException ("MakeBinary expect a binary node type");
- }
- #endregion
- public static MethodCallExpression ArrayIndex (Expression array, params Expression [] indexes)
- {
- return ArrayIndex (array, indexes as IEnumerable<Expression>);
- }
- public static MethodCallExpression ArrayIndex (Expression array, IEnumerable<Expression> indexes)
- {
- CheckArray (array);
- if (indexes == null)
- throw new ArgumentNullException ("indexes");
- var args = indexes.ToReadOnlyCollection ();
- if (array.Type.GetArrayRank () != args.Count)
- throw new ArgumentException ("The number of arguments doesn't match the rank of the array");
- foreach (var arg in args)
- if (arg.Type != typeof (int))
- throw new ArgumentException ("The index must be of type int");
- return Call (array, array.Type.GetMethod ("Get", PublicInstance), args);
- }
- public static UnaryExpression ArrayLength (Expression array)
- {
- if (array == null)
- throw new ArgumentNullException ("array");
- if (!array.Type.IsArray)
- throw new ArgumentException ("The type of the expression must me Array");
- if (array.Type.GetArrayRank () != 1)
- throw new ArgumentException ("The array must be a single dimensional array");
- return new UnaryExpression (ExpressionType.ArrayLength, array, typeof (int));
- }
- public static MemberAssignment Bind (MemberInfo member, Expression expression)
- {
- if (member == null)
- throw new ArgumentNullException ("member");
- if (expression == null)
- throw new ArgumentNullException ("expression");
- Type type = null;
- var prop = member as PropertyInfo;
- if (prop != null && prop.GetSetMethod (true) != null)
- type = prop.PropertyType;
- var field = member as FieldInfo;
- if (field != null)
- type = field.FieldType;
- if (type == null)
- throw new ArgumentException ("member");
- if (!expression.Type.IsAssignableTo (type))
- throw new ArgumentException ("member");
- return new MemberAssignment (member, expression);
- }
- public static MemberAssignment Bind (MethodInfo propertyAccessor, Expression expression)
- {
- if (propertyAccessor == null)
- throw new ArgumentNullException ("propertyAccessor");
- if (expression == null)
- throw new ArgumentNullException ("expression");
- var prop = GetAssociatedProperty (propertyAccessor);
- if (prop == null)
- throw new ArgumentException ("propertyAccessor");
- var setter = prop.GetSetMethod (true);
- if (setter == null)
- throw new ArgumentException ("setter");
- if (!expression.Type.IsAssignableTo (prop.PropertyType))
- throw new ArgumentException ("member");
- return new MemberAssignment (prop, expression);
- }
- public static MethodCallExpression Call (Expression instance, MethodInfo method)
- {
- return Call (instance, method, null as IEnumerable<Expression>);
- }
- public static MethodCallExpression Call (MethodInfo method, params Expression [] arguments)
- {
- return Call (null, method, arguments as IEnumerable<Expression>);
- }
- public static MethodCallExpression Call (Expression instance, MethodInfo method, params Expression [] arguments)
- {
- return Call (instance, method, arguments as IEnumerable<Expression>);
- }
- public static MethodCallExpression Call (Expression instance, MethodInfo method, IEnumerable<Expression> arguments)
- {
- if (method == null)
- throw new ArgumentNullException ("method");
- if (instance == null && !method.IsStatic)
- throw new ArgumentNullException ("instance");
- if (!method.IsStatic && !instance.Type.IsAssignableTo (method.DeclaringType))
- throw new ArgumentException ("Type is not assignable to the declaring type of the method");
- var args = arguments.ToReadOnlyCollection ();
- CheckMethodArguments (method, args);
- return new MethodCallExpression (instance, method, args);
- }
- static Type [] CollectTypes (IEnumerable<Expression> expressions)
- {
- return (from arg in expressions select arg.Type).ToArray ();
- }
- static MethodInfo TryMakeGeneric (MethodInfo method, Type [] args)
- {
- if (method == null)
- return null;
- if (!method.IsGenericMethod && args == null)
- return method;
- if (args.Length == method.GetGenericArguments ().Length)
- return method.MakeGenericMethod (args);
- return null;
- }
- public static MethodCallExpression Call (Expression instance, string methodName, Type [] typeArguments, params Expression [] arguments)
- {
- if (instance == null)
- throw new ArgumentNullException ("instance");
- if (methodName == null)
- throw new ArgumentNullException ("methodName");
- var method = TryGetMethod (instance.Type, methodName, AllInstance,
- CollectTypes (arguments), typeArguments);
- var args = arguments.ToReadOnlyCollection ();
- CheckMethodArguments (method, args);
- return new MethodCallExpression (instance, method, args);
- }
- static bool MethodMatch (MethodInfo method, string name, Type [] parameterTypes)
- {
- if (method.Name != name)
- return false;
- var parameters = method.GetParameters ();
- if (parameters.Length != parameterTypes.Length)
- return false;
- if (method.IsGenericMethod) // if it's a generic method, when can't compare its parameters
- return true;
- for (int i = 0; i < parameters.Length; i++)
- if (!IsAssignableToParameterType (parameterTypes [i], parameters [i]))
- return false;
- return true;
- }
- static MethodInfo TryGetMethod (Type type, string methodName, BindingFlags flags, Type [] parameterTypes, Type [] argumentTypes)
- {
- var methods = from meth in type.GetMethods (flags)
- where MethodMatch (meth, methodName, parameterTypes)
- select meth;
- if (methods.Count () > 1)
- throw new InvalidOperationException ("Too much method candidates");
- var method = TryMakeGeneric (methods.FirstOrDefault (), argumentTypes);
- if (method != null)
- return method;
- throw new InvalidOperationException ("No such method");
- }
- public static MethodCallExpression Call (Type type, string methodName, Type [] typeArguments, params Expression [] arguments)
- {
- if (type == null)
- throw new ArgumentNullException ("type");
- if (methodName == null)
- throw new ArgumentNullException ("methodName");
- var method = TryGetMethod (type, methodName, AllStatic,
- CollectTypes (arguments), typeArguments);
- var args = arguments.ToReadOnlyCollection ();
- CheckMethodArguments (method, args);
- return new MethodCallExpression (method, args);
- }
- public static ConditionalExpression Condition (Expression test, Expression ifTrue, Expression ifFalse)
- {
- if (test == null)
- throw new ArgumentNullException ("test");
- if (ifTrue == null)
- throw new ArgumentNullException ("ifTrue");
- if (ifFalse == null)
- throw new ArgumentNullException ("ifFalse");
- if (test.Type != typeof (bool))
- throw new ArgumentException ("Test expression should be of type bool");
- if (ifTrue.Type != ifFalse.Type)
- throw new ArgumentException ("The ifTrue and ifFalse type do not match");
- return new ConditionalExpression (test, ifTrue, ifFalse);
- }
- public static ConstantExpression Constant (object value)
- {
- if (value == null)
- return new ConstantExpression (null, typeof (object));
- return Constant (value, value.GetType ());
- }
- public static ConstantExpression Constant (object value, Type type)
- {
- if (type == null)
- throw new ArgumentNullException ("type");
- //
- // value must be compatible with type, no conversions
- // are allowed
- //
- if (value == null){
- if (type.IsValueType && !IsNullable (type))
- throw new ArgumentException ();
- } else {
- if (!(type.IsValueType && IsNullable (type)) && !value.GetType ().IsAssignableTo (type))
- throw new ArgumentException ();
- }
- return new ConstantExpression (value, type);
- }
- static bool IsConvertiblePrimitive (Type type)
- {
- var t = GetNotNullableOf (type);
- if (t == typeof (bool))
- return false;
- if (t.IsEnum)
- return true;
- return t.IsPrimitive;
- }
- internal static bool IsPrimitiveConversion (Type type, Type target)
- {
- if (type == target)
- return true;
- if (IsConvertiblePrimitive (type) && IsConvertiblePrimitive (target))
- return true;
- return false;
- }
- internal static bool IsReferenceConversion (Type type, Type target)
- {
- if (type == target)
- return true;
- if (type.IsAssignableTo (target) || target.IsAssignableTo (type))
- return true;
- if (type == typeof (object) || target == typeof (object))
- return true;
- if (type.IsInterface || target.IsInterface)
- return true;
- return false;
- }
- public static UnaryExpression Convert (Expression expression, Type type)
- {
- return Convert (expression, type, null);
- }
- static MethodInfo GetUserConversionMethod (Type type, Type target)
- {
- var method = GetUnaryOperator ("op_Explicit", type, type, target);
- if (method == null)
- method = GetUnaryOperator ("op_Implicit", type, type, target);
- if (method == null)
- throw new InvalidOperationException ();
- return method;
- }
- public static UnaryExpression Convert (Expression expression, Type type, MethodInfo method)
- {
- if (expression == null)
- throw new ArgumentNullException ("expression");
- if (type == null)
- throw new ArgumentNullException ("type");
- var et = expression.Type;
- if (method != null)
- CheckUnaryMethod (method, et);
- else if (!IsPrimitiveConversion (et, type) && !IsReferenceConversion (et, type))
- method = GetUserConversionMethod (et, type);
- return new UnaryExpression (ExpressionType.Convert,
- expression, type, method,
- IsConvertNodeLifted (method, expression, type));
- }
- static bool IsConvertNodeLifted (MethodInfo method, Expression operand, Type target)
- {
- if (method == null)
- return IsNullable (operand.Type) || IsNullable (target);
- if (IsNullable (operand.Type) && !ParameterMatch (method, operand.Type))
- return true;
- if (IsNullable (target) && !ReturnTypeMatch (method, target))
- return true;
- return false;
- }
- static bool ParameterMatch (MethodInfo method, Type type)
- {
- return method.GetParameters () [0].ParameterType == type;
- }
- static bool ReturnTypeMatch (MethodInfo method, Type type)
- {
- return method.ReturnType == type;
- }
- public static UnaryExpression ConvertChecked (Expression expression, Type type)
- {
- return ConvertChecked (expression, type, null);
- }
- public static UnaryExpression ConvertChecked (Expression expression, Type type, MethodInfo method)
- {
- if (expression == null)
- throw new ArgumentNullException ("expression");
- if (type == null)
- throw new ArgumentNullException ("type");
- var et = expression.Type;
- if (method != null)
- CheckUnaryMethod (method, et);
- else if (IsReferenceConversion (et, type))
- return Convert (expression, type, method);
- else if (!IsPrimitiveConversion (et, type))
- method = GetUserConversionMethod (et, type);
- return new UnaryExpression (ExpressionType.ConvertChecked,
- expression, type, method,
- IsConvertNodeLifted (method, expression, type));
- }
- public static ElementInit ElementInit (MethodInfo addMethod, params Expression [] arguments)
- {
- return ElementInit (addMethod, arguments as IEnumerable<Expression>);
- }
- public static ElementInit ElementInit (MethodInfo addMethod, IEnumerable<Expression> arguments)
- {
- if (addMethod == null)
- throw new ArgumentNullException ("addMethod");
- if (arguments == null)
- throw new ArgumentNullException ("arguments");
- if (addMethod.Name.ToLowerInvariant () != "add")
- throw new ArgumentException ("addMethod");
- if (addMethod.IsStatic)
- throw new ArgumentException ("addMethod must be an instance method", "addMethod");
- var args = arguments.ToReadOnlyCollection ();
- CheckMethodArguments (addMethod, args);
- return new ElementInit (addMethod, args);
- }
- public static MemberExpression Field (Expression expression, FieldInfo field)
- {
- if (field == null)
- throw new ArgumentNullException ("field");
- if (!field.IsStatic) {
- if (expression == null)
- throw new ArgumentNullException ("expression");
- if (!expression.Type.IsAssignableTo (field.DeclaringType))
- throw new ArgumentException ("field");
- }
- return new MemberExpression (expression, field, field.FieldType);
- }
- public static MemberExpression Field (Expression expression, string fieldName)
- {
- if (expression == null)
- throw new ArgumentNullException ("expression");
- var field = expression.Type.GetField (fieldName, AllInstance);
- if (field == null)
- throw new ArgumentException (string.Format ("No field named {0} on {1}", fieldName, expression.Type));
- return new MemberExpression (expression, field, field.FieldType);
- }
- public static Type GetActionType (params Type [] typeArgs)
- {
- if (typeArgs == null)
- throw new ArgumentNullException ("typeArgs");
- if (typeArgs.Length > 4)
- throw new ArgumentException ("No Action type of this arity");
- if (typeArgs.Length == 0)
- return typeof (Action);
- Type action = null;
- switch (typeArgs.Length) {
- case 1:
- action = typeof (Action<>);
- break;
- case 2:
- action = typeof (Action<,>);
- break;
- case 3:
- action = typeof (Action<,,>);
- break;
- case 4:
- action = typeof (Action<,,,>);
- break;
- }
- return action.MakeGenericType (typeArgs);
- }
- public static Type GetFuncType (params Type [] typeArgs)
- {
- if (typeArgs == null)
- throw new ArgumentNullException ("typeArgs");
- if (typeArgs.Length < 1 || typeArgs.Length > 5)
- throw new ArgumentException ("No Func type of this arity");
- Type func = null;
- switch (typeArgs.Length) {
- case 1:
- func = typeof (Func<>);
- break;
- case 2:
- func = typeof (Func<,>);
- break;
- case 3:
- func = typeof (Func<,,>);
- break;
- case 4:
- func = typeof (Func<,,,>);
- break;
- case 5:
- func = typeof (Func<,,,,>);
- break;
- }
- return func.MakeGenericType (typeArgs);
- }
- public static InvocationExpression Invoke (Expression expression, params Expression [] arguments)
- {
- return Invoke (expression, arguments as IEnumerable<Expression>);
- }
- static Type GetInvokableType (Type t)
- {
- if (t.IsAssignableTo (typeof (Delegate)))
- return t;
- return GetGenericType (t, typeof (Expression<>));
- }
- static Type GetGenericType (Type t, Type def)
- {
- if (t == null)
- return null;
- if (t.IsGenericType && t.GetGenericTypeDefinition () == def)
- return t;
- return GetGenericType (t.BaseType, def);
- }
- public static InvocationExpression Invoke (Expression expression, IEnumerable<Expression> arguments)
- {
- if (expression == null)
- throw new ArgumentNullException ("expression");
- var type = GetInvokableType (expression.Type);
- if (type == null)
- throw new ArgumentException ("The type of the expression is not invokable");
- var args = arguments.ToReadOnlyCollection ();
- CheckForNull (args, "arguments");
- var invoke = type.GetMethod ("Invoke");
- if (invoke == null)
- throw new ArgumentException ("expression");
- if (invoke.GetParameters ().Length != args.Count)
- throw new InvalidOperationException ("Arguments count doesn't match parameters length");
- CheckMethodArguments (invoke, args);
- return new InvocationExpression (expression, invoke.ReturnType, args);
- }
- static bool CanAssign (Type target, Type source)
- {
- // This catches object and value type mixage, type compatibility is handled later
- if (target.IsValueType ^ source.IsValueType)
- return false;
- return source.IsAssignableTo (target);
- }
- static void CheckLambda (Type delegateType, Expression body, ReadOnlyCollection<ParameterExpression> parameters)
- {
- if (!delegateType.IsSubclassOf (typeof (System.Delegate)))
- throw new ArgumentException ("delegateType");
- var invoke = delegateType.GetMethod ("Invoke", BindingFlags.Instance | BindingFlags.Public);
- if (invoke == null)
- throw new ArgumentException ("delegate must contain an Invoke method", "delegateType");
- var invoke_parameters = invoke.GetParameters ();
- if (invoke_parameters.Length != parameters.Count)
- throw new ArgumentException (string.Format ("Different number of arguments in delegate {0}", delegateType), "delegateType");
- for (int i = 0; i < invoke_parameters.Length; i++) {
- if (!CanAssign (parameters [i].Type, invoke_parameters [i].ParameterType))
- throw new ArgumentException (String.Format ("Can not assign a {0} to a {1}", invoke_parameters [i].ParameterType, parameters [i].Type));
- }
- if (invoke.ReturnType != typeof (void) && !CanAssign (invoke.ReturnType, body.Type))
- throw new ArgumentException (String.Format ("body type {0} can not be assigned to {1}", body.Type, invoke.ReturnType));
- }
- public static Expression<TDelegate> Lambda<TDelegate> (Expression body, params ParameterExpression [] parameters)
- {
- return Lambda<TDelegate> (body, parameters as IEnumerable<ParameterExpression>);
- }
- public static Expression<TDelegate> Lambda<TDelegate> (Expression body, IEnumerable<ParameterExpression> parameters)
- {
- if (body == null)
- throw new ArgumentNullException ("body");
- var ps = parameters.ToReadOnlyCollection ();
- CheckLambda (typeof (TDelegate), body, ps);
- return new Expression<TDelegate> (body, ps);
- }
- public static LambdaExpression Lambda (Expression body, params ParameterExpression [] parameters)
- {
- if (body == null)
- throw new ArgumentNullException ("body");
- if (parameters.Length > 4)
- throw new ArgumentException ("Too many parameters");
- return Lambda (GetDelegateType (body.Type, parameters), body, parameters);
- }
- static Type GetDelegateType (Type return_type, ParameterExpression [] parameters)
- {
- if (parameters == null)
- parameters = new ParameterExpression [0];
- if (return_type == typeof (void))
- return GetActionType (parameters.Select (p => p.Type).ToArray ());
- var types = new Type [parameters.Length + 1];
- for (int i = 0; i < types.Length - 1; i++)
- types [i] = parameters [i].Type;
- types [types.Length - 1] = return_type;
- return GetFuncType (types);
- }
- public static LambdaExpression Lambda (Type delegateType, Expression body, params ParameterExpression [] parameters)
- {
- return Lambda (delegateType, body, parameters as IEnumerable<ParameterExpression>);
- }
- static LambdaExpression CreateExpressionOf (Type type, Expression body, ReadOnlyCollection<ParameterExpression> parameters)
- {
- return (LambdaExpression) Activator.CreateInstance (
- typeof (Expression<>).MakeGenericType (type),
- NonPublicInstance, null, new object [] { body, parameters }, null);
- }
- public static LambdaExpression Lambda (Type delegateType, Expression body, IEnumerable<ParameterExpression> parameters)
- {
- if (delegateType == null)
- throw new ArgumentNullException ("delegateType");
- if (body == null)
- throw new ArgumentNullException ("body");
- var ps = parameters.ToReadOnlyCollection ();
- CheckLambda (delegateType, body, ps);
- return CreateExpressionOf (delegateType, body, ps);
- }
- public static MemberListBinding ListBind (MemberInfo member, params ElementInit [] initializers)
- {
- return ListBind (member, initializers as IEnumerable<ElementInit>);
- }
- static void CheckIsAssignableToIEnumerable (Type t)
- {
- if (!t.IsAssignableTo (typeof (IEnumerable)))
- throw new ArgumentException (string.Format ("Type {0} doesn't implemen IEnumerable", t));
- }
- public static MemberListBinding ListBind (MemberInfo member, IEnumerable<ElementInit> initializers)
- {
- if (member == null)
- throw new ArgumentNullException ("member");
- if (initializers == null)
- throw new ArgumentNullException ("initializers");
- var inits = initializers.ToReadOnlyCollection ();
- CheckForNull (inits, "initializers");
- member.OnFieldOrProperty (
- field => CheckIsAssignableToIEnumerable (field.FieldType),
- prop => CheckIsAssignableToIEnumerable (prop.PropertyType));
- return new MemberListBinding (member, inits);
- }
- public static MemberListBinding ListBind (MethodInfo propertyAccessor, params ElementInit [] initializers)
- {
- return ListBind (propertyAccessor, initializers as IEnumerable<ElementInit>);
- }
- static void CheckForNull<T> (ReadOnlyCollection<T> collection, string name) where T : class
- {
- foreach (var t in collection)
- if (t == null)
- throw new ArgumentNullException (name);
- }
- public static MemberListBinding ListBind (MethodInfo propertyAccessor, IEnumerable<ElementInit> initializers)
- {
- if (propertyAccessor == null)
- throw new ArgumentNullException ("propertyAccessor");
- if (initializers == null)
- throw new ArgumentNullException ("initializers");
- var inits = initializers.ToReadOnlyCollection ();
- CheckForNull (inits, "initializers");
- var prop = GetAssociatedProperty (propertyAccessor);
- if (prop == null)
- throw new ArgumentException ("propertyAccessor");
- CheckIsAssignableToIEnumerable (prop.PropertyType);
- return new MemberListBinding (prop, inits);
- }
- public static ListInitExpression ListInit (NewExpression newExpression, params ElementInit [] initializers)
- {
- return ListInit (newExpression, initializers as IEnumerable<ElementInit>);
- }
- public static ListInitExpression ListInit (NewExpression newExpression, IEnumerable<ElementInit> initializers)
- {
- var inits = CheckListInit (newExpression, initializers);
- return new ListInitExpression (newExpression, inits);
- }
- public static ListInitExpression ListInit (NewExpression newExpression, params Expression [] initializers)
- {
- return ListInit (newExpression, initializers as IEnumerable<Expression>);
- }
- public static ListInitExpression ListInit (NewExpression newExpression, IEnumerable<Expression> initializers)
- {
- var inits = CheckListInit (newExpression, initializers);
- var add_method = GetAddMethod (newExpression.Type, inits [0].Type);
- if (add_method == null)
- throw new InvalidOperationException ("No suitable add method found");
- return new ListInitExpression (newExpression, CreateInitializers (add_method, inits));
- }
- static ReadOnlyCollection<ElementInit> CreateInitializers (MethodInfo add_method, ReadOnlyCollection<Expression> initializers)
- {
- return (from init in initializers select Expression.ElementInit (add_method, init)).ToReadOnlyCollection ();
- }
- static MethodInfo GetAddMethod (Type type, Type arg)
- {
- return type.GetMethod ("Add", PublicInstance | BindingFlags.IgnoreCase, null, new [] { arg }, null);
- }
- public static ListInitExpression ListInit (NewExpression newExpression, MethodInfo addMethod, params Expression [] initializers)
- {
- return ListInit (newExpression, addMethod, initializers as IEnumerable<Expression>);
- }
- static ReadOnlyCollection<T> CheckListInit<T> (NewExpression newExpression, IEnumerable<T> initializers) where T : class
- {
- if (newExpression == null)
- throw new ArgumentNullException ("newExpression");
- if (initializers == null)
- throw new ArgumentNullException ("initializers");
- if (!newExpression.Type.IsAssignableTo (typeof (IEnumerable)))
- throw new InvalidOperationException ("The type of the new expression does not implement IEnumerable");
- var inits = initializers.ToReadOnlyCollection ();
- if (inits.Count == 0)
- throw new ArgumentException ("Empty initializers");
- CheckForNull (inits, "initializers");
- return inits;
- }
- public static ListInitExpression ListInit (NewExpression newExpression, MethodInfo addMethod, IEnumerable<Expression> initializers)
- {
- var inits = CheckListInit (newExpression, initializers);
- if (addMethod != null) {
- if (addMethod.Name.ToLowerInvariant () != "add")
- throw new ArgumentException ("addMethod");
- var parameters = addMethod.GetParameters ();
- if (parameters.Length != 1)
- throw new ArgumentException ("addMethod");
- foreach (var expression in inits)
- if (!IsAssignableToParameterType (expression.Type, parameters [0]))
- throw new InvalidOperationException ("Initializer not assignable to the add method parameter type");
- }
- if (addMethod == null)
- addMethod = GetAddMethod (newExpression.Type, inits [0].Type);
- if (addMethod == null)
- throw new InvalidOperationException ("No suitable add method found");
- return new ListInitExpression (newExpression, CreateInitializers (addMethod, inits));
- }
- public static MemberExpression MakeMemberAccess (Expression expression, MemberInfo member)
- {
- if (expression == null)
- throw new ArgumentNullException ("expression");
- if (member == null)
- throw new ArgumentNullException ("member");
- var field = member as FieldInfo;
- if (field != null)
- return Field (expression, field);
- var property = member as PropertyInfo;
- if (property != null)
- return Property (expression, property);
- throw new ArgumentException ("Member should either be a field or a property");
- }
- public static UnaryExpression MakeUnary (ExpressionType unaryType, Expression operand, Type type)
- {
- return MakeUnary (unaryType, operand, type, null);
- }
- public static UnaryExpression MakeUnary (ExpressionType unaryType, Expression operand, Type type, MethodInfo method)
- {
- switch (unaryType) {
- case ExpressionType.ArrayLength:
- return ArrayLength (operand);
- case ExpressionType.Convert:
- return Convert (operand, type, method);
- case ExpressionType.ConvertChecked:
- return ConvertChecked (operand, type, method);
- case ExpressionType.Negate:
- return Negate (operand, method);
- case ExpressionType.NegateChecked:
- return NegateChecked (operand, method);
- case ExpressionType.Not:
- return Not (operand, method);
- case ExpressionType.Quote:
- return Quote (operand);
- case ExpressionType.TypeAs:
- return TypeAs (operand, type);
- case ExpressionType.UnaryPlus:
- return UnaryPlus (operand, method);
- }
- throw new ArgumentException ("MakeUnary expect an unary operator");
- }
- public static MemberMemberBinding MemberBind (MemberInfo member, params MemberBinding [] bindings)
- {
- return MemberBind (member, bindings as IEnumerable<MemberBinding>);
- }
- public static MemberMemberBinding MemberBind (MemberInfo member, IEnumerable<MemberBinding> bindings)
- {
- if (member == null)
- throw new ArgumentNullException ("member");
- var type = member.OnFieldOrProperty (
- field => field.FieldType,
- prop => prop.PropertyType);
- return new MemberMemberBinding (member, CheckMemberBindings (type, bindings));
- }
- public static MemberMemberBinding MemberBind (MethodInfo propertyAccessor, params MemberBinding [] bindings)
- {
- return MemberBind (propertyAccessor, bindings as IEnumerable<MemberBinding>);
- }
- public static MemberMemberBinding MemberBind (MethodInfo propertyAccessor, IEnumerable<MemberBinding> bindings)
- {
- if (propertyAccessor == null)
- throw new ArgumentNullException ("propertyAccessor");
- var bds = bindings.ToReadOnlyCollection ();
- CheckForNull (bds, "bindings");
- var prop = GetAssociatedProperty (propertyAccessor);
- if (prop == null)
- throw new ArgumentException ("propertyAccessor");
- return new MemberMemberBinding (prop, CheckMemberBindings (prop.PropertyType, bindings));
- }
- static ReadOnlyCollection<MemberBinding> CheckMemberBindings (Type type, IEnumerable<MemberBinding> bindings)
- {
- if (bindings == null)
- throw new ArgumentNullException ("bindings");
- var bds = bindings.ToReadOnlyCollection ();
- CheckForNull (bds, "bindings");
- foreach (var binding in bds)
- if (!type.IsAssignableTo (binding.Member.DeclaringType))
- throw new ArgumentException ("Type not assignable to member type");
- return bds;
- }
- public static MemberInitExpression MemberInit (NewExpression newExpression, params MemberBinding [] bindings)
- {
- return MemberInit (newExpression, bindings as IEnumerable<MemberBinding>);
- }
- public static MemberInitExpression MemberInit (NewExpression newExpression, IEnumerable<MemberBinding> bindings)
- {
- if (newExpression == null)
- throw new ArgumentNullException ("newExpression");
- return new MemberInitExpression (newExpression, CheckMemberBindings (newExpression.Type, bindings));
- }
- public static UnaryExpression Negate (Expression expression)
- {
- return Negate (expression, null);
- }
- public static UnaryExpression Negate (Expression expression, MethodInfo method)
- {
- method = UnaryCoreCheck ("op_UnaryNegation", expression, method, type => IsSignedNumber (type));
- return MakeSimpleUnary (ExpressionType.Negate, expression, method);
- }
- public static UnaryExpression NegateChecked (Expression expression)
- {
- return NegateChecked (expression, null);
- }
- public static UnaryExpression NegateChecked (Expression expression, MethodInfo method)
- {
- method = UnaryCoreCheck ("op_UnaryNegation", expression, method, type => IsSignedNumber (type));
- return MakeSimpleUnary (ExpressionType.Negate, expression, method);
- }
- public static NewExpression New (ConstructorInfo constructor)
- {
- if (constructor == null)
- throw new ArgumentNullException ("constructor");
- if (constructor.GetParameters ().Length > 0)
- throw new ArgumentException ("Constructor must be parameter less");
- return new NewExpression (constructor, (null as IEnumerable<Expression>).ToReadOnlyCollection (), null);
- }
- public static NewExpression New (Type type)
- {
- if (type == null)
- throw new ArgumentNullException ("type");
- CheckNotVoid (type);
- var args = (null as IEnumerable<Expression>).ToReadOnlyCollection ();
- if (type.IsValueType)
- return new NewExpression (type, args);
- var ctor = type.GetConstructor (Type.EmptyTypes);
- if (ctor == null)
- throw new ArgumentException ("Type doesn't have a parameter less constructor");
- return new NewExpression (ctor, args, null);
- }
- public static NewExpression New (ConstructorInfo constructor, params Expression [] arguments)
- {
- return New (constructor, arguments as IEnumerable<Expression>);
- }
- public static NewExpression New (ConstructorInfo constructor, IEnumerable<Expression> arguments)
- {
- if (constructor == null)
- throw new ArgumentNullException ("constructor");
- var args = arguments.ToReadOnlyCollection ();
- CheckMethodArguments (constructor, args);
- return new NewExpression (constructor, args, null);
- }
- static void CheckMethodArguments (MethodBase method, ReadOnlyCollection<Expression> arguments)
- {
- var parameters = method.GetParameters ();
- if (arguments.Count != parameters.Length)
- throw new ArgumentException ("The number of arguments doesn't match the number of parameters");
- for (int i = 0; i < parameters.Length; i++) {
- if (arguments [i] == null)
- throw new ArgumentNullException ("arguments");
- if (!IsAssignableToParameterType (arguments [i].Type, parameters [i]))
- throw new ArgumentException ("arguments");
- }
- }
- public static NewExpression New (ConstructorInfo constructor, IEnumerable<Expression> arguments, params MemberInfo [] members)
- {
- return New (constructor, arguments, members as IEnumerable<MemberInfo>);
- }
- public static NewExpression New (ConstructorInfo constructor, IEnumerable<Expression> arguments, IEnumerable<MemberInfo> members)
- {
- if (constructor == null)
- throw new ArgumentNullException ("constructor");
- var args = arguments.ToReadOnlyCollection ();
- var mmbs = members.ToReadOnlyCollection ();
- CheckForNull (args, "arguments");
- CheckForNull (mmbs, "members");
- CheckMethodArguments (constructor, args);
- if (args.Count != mmbs.Count)
- throw new ArgumentException ("Arguments count does not match members count");
- for (int i = 0; i < mmbs.Count; i++) {
- var member = mmbs [i];
- Type type = null;
- switch (member.MemberType) {
- case MemberTypes.Field:
- type = (member as FieldInfo).FieldType;
- break;
- case MemberTypes.Method:
- type = (member as MethodInfo).ReturnType;
- break;
- case MemberTypes.Property:
- var prop = member as PropertyInfo;
- if (prop.GetGetMethod (true) == null)
- throw new ArgumentException ("Property must have a getter");
- type = (member as PropertyInfo).PropertyType;
- break;
- default:
- throw new ArgumentException ("Member type not allowed");
- }
- if (!args [i].Type.IsAssignableTo (type))
- throw new ArgumentException ("Argument type not assignable to member type");
- }
- return new NewExpression (constructor, args, mmbs);
- }
- public static NewArrayExpression NewArrayBounds (Type type, params Expression [] bounds)
- {
- return NewArrayBounds (type, bounds as IEnumerable<Expression>);
- }
- public static NewArrayExpression NewArrayBounds (Type type, IEnumerable<Expression> bounds)
- {
- if (type == null)
- throw new ArgumentNullException ("type");
- if (bounds == null)
- throw new ArgumentNullException ("bounds");
- CheckNotVoid (type);
- var array_bounds = bounds.ToReadOnlyCollection ();
- foreach (var expression in array_bounds)
- if (!IsInt (expression.Type))
- throw new ArgumentException ("The bounds collection can only contain expression of integers types");
- return new NewArrayExpression (ExpressionType.NewArrayBounds, type.MakeArrayType (array_bounds.Count), array_bounds);
- }
- public static NewArrayExpression NewArrayInit (Type type, params Expression [] initializers)
- {
- return NewArrayInit (type, initializers as IEnumerable<Expression>);
- }
- public static NewArrayExpression NewArrayInit (Type type, IEnumerable<Expression> initializers)
- {
- if (type == null)
- throw new ArgumentNullException ("type");
- if (initializers == null)
- throw new ArgumentNullException ("initializers");
- CheckNotVoid (type);
- var inits = initializers.ToReadOnlyCollection ();
- foreach (var expression in inits) {
- if (expression == null)
- throw new ArgumentNullException ("initializers");
- if (!expression.Type.IsAssignableTo (type))
- throw new InvalidOperationException ();
- // TODO: Quote elements if type == typeof (Expression)
- }
- return new NewArrayExpression (ExpressionType.NewArrayInit, type.MakeArrayType (), inits);
- }
- public static UnaryExpression Not (Expression expression)
- {
- return Not (expression, null);
- }
- public static UnaryExpression Not (Expression expression, MethodInfo method)
- {
- Func<Type, bool> validator = type => IsIntOrBool (type);
- method = UnaryCoreCheck ("op_LogicalNot", expression, method, validator);
- if (method == null)
- method = UnaryCoreCheck ("op_OnesComplement", expression, method, validator);
- return MakeSimpleUnary (ExpressionType.Not, expression, method);
- }
- static void CheckNotVoid (Type type)
- {
- if (type == typeof (void))
- throw new ArgumentException ("Type can't be void");
- }
- public static ParameterExpression Parameter (Type type, string name)
- {
- if (type == null)
- throw new ArgumentNullException ("type");
- CheckNotVoid (type);
- return new ParameterExpression (type, name);
- }
- public static MemberExpression Property (Expression expression, MethodInfo propertyAccessor)
- {
- if (propertyAccessor == null)
- throw new ArgumentNullException ("propertyAccessor");
- if (!propertyAccessor.IsStatic) {
- if (expression == null)
- throw new ArgumentNullException ("expression");
- if (!expression.Type.IsAssignableTo (propertyAccessor.DeclaringType))
- throw new ArgumentException ("expression");
- }
- var prop = GetAssociatedProperty (propertyAccessor);
- if (prop == null)
- throw new ArgumentException (string.Format ("Method {0} has no associated property", propertyAccessor));
- return new MemberExpression (expression, prop, prop.PropertyType);
- }
- static PropertyInfo GetAssociatedProperty (MethodInfo method)
- {
- foreach (var prop in method.DeclaringType.GetProperties (All)) {
- if (prop.GetGetMethod (true) == method)
- return prop;
- if (prop.GetSetMethod (true) == method)
- return prop;
- }
- return null;
- }
- public static MemberExpression Property (Expression expression, PropertyInfo property)
- {
- if (property == null)
- throw new ArgumentNullException ("property");
- var getter = property.GetGetMethod (true);
- if (getter == null)
- throw new ArgumentException ("getter");
- if (!getter.IsStatic) {
- if (expression == null)
- throw new ArgumentNullException ("expression");
- if (!expression.Type.IsAssignableTo (property.DeclaringType))
- throw new ArgumentException ("expression");
- }
- return new MemberExpression (expression, property, property.PropertyType);
- }
- public static MemberExpression Property (Expression expression, string propertyName)
- {
- if (expression == null)
- throw new ArgumentNullException ("expression");
- var prop = expression.Type.GetProperty (propertyName, AllInstance);
- if (prop == null)
- throw new ArgumentException (string.Format ("No property named {0} on {1}", propertyName, expression.Type));
- return new MemberExpression (expression, prop, prop.PropertyType);
- }
- public static MemberExpression PropertyOrField (Expression expression, string propertyOrFieldName)
- {
- if (expression == null)
- throw new ArgumentNullException ("expression");
- if (propertyOrFieldName == null)
- throw new ArgumentNullException ("propertyOrFieldName");
- var prop = expression.Type.GetProperty (propertyOrFieldName, AllInstance);
- if (prop != null)
- return new MemberExpression (expression, prop, prop.PropertyType);
- var field = expression.Type.GetField (propertyOrFieldName, AllInstance);
- if (field != null)
- return new MemberExpression (expression, field, field.FieldType);
- throw new ArgumentException (string.Format ("No field or property named {0} on {1}", propertyOrFieldName, expression.Type));
- }
- public static UnaryExpression Quote (Expression expression)
- {
- if (expression == null)
- throw new ArgumentNullException ("expression");
- return new UnaryExpression (ExpressionType.Quote, expression, expression.GetType ());
- }
- public static UnaryExpression TypeAs (Expression expression, Type type)
- {
- if (expression == null)
- throw new ArgumentNullException ("expression");
- if (type == null)
- throw new ArgumentNullException ("type");
- if (type.IsValueType && !IsNullable (type))
- throw new ArgumentException ("TypeAs expect a reference or a nullable type");
- return new UnaryExpression (ExpressionType.TypeAs, expression, type);
- }
- public static TypeBinaryExpression TypeIs (Expression expression, Type type)
- {
- if (expression == null)
- throw new ArgumentNullException ("expression");
- if (type == null)
- throw new ArgumentNullException ("type");
- CheckNotVoid (type);
- return new TypeBinaryExpression (ExpressionType.TypeIs, expression, type, typeof (bool));
- }
- public static UnaryExpression UnaryPlus (Expression expression)
- {
- return UnaryPlus (expression, null);
- }
- public static UnaryExpression UnaryPlus (Expression expression, MethodInfo method)
- {
- method = UnaryCoreCheck ("op_UnaryPlus", expression, method, type => IsNumber (type));
- return MakeSimpleUnary (ExpressionType.UnaryPlus, expression, method);
- }
- static bool IsInt (Type t)
- {
- return t == typeof (byte) || t == typeof (sbyte) ||
- t == typeof (short) || t == typeof (ushort) ||
- t == typeof (int) || t == typeof (uint) ||
- t == typeof (long) || t == typeof (ulong);
- }
- static bool IsIntOrBool (Type t)
- {
- return IsInt (t) || t == typeof (bool);
- }
- static bool IsNumber (Type t)
- {
- if (IsInt (t))
- return true;
- return t == typeof (float) || t == typeof (double) || t == typeof (decimal);
- }
- internal static bool IsNullable (Type type)
- {
- return type.IsGenericInstanceOf (typeof (Nullable<>));
- }
- static bool IsSignedNumber (Type t)
- {
- return IsNumber (t) && !IsUnsigned (t);
- }
- internal static bool IsUnsigned (Type t)
- {
- #if !TARGET_JVM
- if (t.IsPointer)
- return IsUnsigned (t.GetElementType ());
- #endif
- return t == typeof (ushort) ||
- t == typeof (uint) ||
- t == typeof (ulong) ||
- t == typeof (byte);
- }
- //
- // returns the T in a a Nullable<T> type.
- //
- internal static Type GetNullableOf (Type type)
- {
- return type.GetFirstGenericArgument ();
- }
- internal static Type GetNotNullableOf (Type type)
- {
- return IsNullable (type) ? GetNullableOf (type) : type;
- }
- //
- // This method must be overwritten by derived classes to
- // compile the expression
- //
- internal virtual void Emit (EmitContext ec)
- {
- throw new NotImplementedException ();
- }
- }
- }
|