Пример #1
0
 private void FreeTemp(ParameterExpression temp) {
     Debug.Assert(_freeTemps == null || !_freeTemps.Contains(temp));
     if (_freeTemps == null) {
         _freeTemps = new List<ParameterExpression>();
     }
     _freeTemps.Add(temp);
 }
Пример #2
0
 internal LocalStorage(LambdaCompiler compiler, ParameterExpression variable)
     : base(compiler, variable) {
     // ByRef variables are supported. This is used internally by
     // the compiler when emitting an inlined lambda invoke, to 
     // handle ByRef parameters. BlockExpression prevents this
     // from being exposed to user created trees.
     _local = compiler.GetNamedLocal(variable.IsByRef ? variable.Type.MakeByRefType() : variable.Type, variable);
 }
Пример #3
0
        public void CreateSimpleDefCommand()
        {
            IList<ParameterExpression> parameters = new ParameterExpression[] { new ParameterExpression("a", null, false), new ParameterExpression("b", null, false) };
            ICommand body = new SetCommand("c", new ConstantExpression(1));
            DefCommand command = new DefCommand("foo", parameters, body);

            Assert.AreEqual("foo", command.Name);
            Assert.AreEqual(parameters, command.ParameterExpressions);
            Assert.AreEqual(body, command.Body);
        }
 public StaticModuleGenerator(TypeBuilder class_builder, bool native_regex)
 {
     ClassBuilder = class_builder;
     NativeRegex = native_regex;
     Initializers = new List<Expression>();
     Subroutines = new Dictionary<Subroutine, SubInfo>();
     CreatedPackages = new HashSet<string>();
     InitRuntime = Expression.Parameter(typeof(Runtime), "runtime");
     Globals = new Dictionary<string, FieldInfo>();
 }
Пример #5
0
            private ParameterExpression UseTemp(ParameterExpression temp) {
                Debug.Assert(_freeTemps == null || !_freeTemps.Contains(temp));
                Debug.Assert(_usedTemps == null || !_usedTemps.Contains(temp));

                if (_usedTemps == null) {
                    _usedTemps = new Stack<ParameterExpression>();
                }
                _usedTemps.Push(temp);
                return temp;
            }
Пример #6
0
 public SubGenerator()
 {
     Runtime = Expression.Parameter(typeof(Runtime), "runtime");
     Arguments = Expression.Parameter(typeof(P5Array), "args");
     Context = Expression.Parameter(typeof(Opcode.ContextValues), "context");
     Pad = Expression.Parameter(typeof(P5ScratchPad), "pad");
     Variables = new List<ParameterExpression>();
     Lexicals = new List<ParameterExpression>();
     Temporaries = new List<ParameterExpression>();
     BlockLabels = new Dictionary<BasicBlock, LabelTarget>();
     ValueBlocks = new Dictionary<BasicBlock, Expression>();
     LexStates = new List<ParameterExpression>();
     RxStates = new List<ParameterExpression>();
 }
Пример #7
0
        public void RaiseWhenNonDefaultArgumentFollowsDefaultArgument()
        {
            IList<ParameterExpression> parameters = new ParameterExpression[] { new ParameterExpression("a", new ConstantExpression(1), false), new ParameterExpression("b", null, false) };
            ICommand body = new SetCommand("c", new ConstantExpression(1));

            try
            {
                DefCommand command = new DefCommand("foo", parameters, body);
                Assert.Fail("Exception expected");
            }
            catch (Exception ex)
            {
                Assert.IsInstanceOfType(ex, typeof(SyntaxError));
                Assert.AreEqual("non-default argument follows default argument", ex.Message);
            }
        }
        public void CreateAndEvaluateParameterExpressionWithNameAndList()
        {
            var expression = new ParameterExpression("a", null, true);

            var result = expression.Evaluate(null);

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(Parameter));

            var param = (Parameter)result;

            Assert.AreEqual("a", expression.Name);
            Assert.IsNull(expression.DefaultExpression);
            Assert.IsTrue(expression.IsList);

            Assert.AreEqual("a", param.Name);
            Assert.IsNull(param.DefaultValue);
            Assert.IsTrue(param.IsList);
        }
        /// <summary>
        /// Extendses the specified parameter map.
        /// </summary>
        /// <param name="extend">The extend id.</param>
        /// <returns></returns>
        public ParameterExpression Extends(string extend)
        {
            Contract.Require.That(extend, Is.Not.Null & Is.Not.Empty).When("retrieving extend argument in Extends method");

            if (parentConfiguration == null)
            {
                parameterExpression = new ParameterExpression(builder);
                parentConfiguration = builder.RegisterConfiguration();
                parameterExpression.parentConfiguration = parentConfiguration;
            }
            if (parameterExpression == null)
            {
                parameterExpression = new ParameterExpression(builder);
                parameterExpression.parentConfiguration = parentConfiguration;
            }
            parentConfiguration.CreateAttribute(ConfigConstants.ATTRIBUTE_EXTENDS, builder.ApplyNamespace(extend));

            return parameterExpression;
        }
Пример #10
0
        internal HoistedLocals(HoistedLocals parent, ReadOnlyCollection<ParameterExpression> vars)
        {
            if (parent != null)
            {
                // Add the parent locals array as the 0th element in the array
                vars = vars.AddFirst(parent.SelfVariable);
            }

            Dictionary<Expression, int> indexes = new Dictionary<Expression, int>(vars.Count);
            for (int i = 0; i < vars.Count; i++)
            {
                indexes.Add(vars[i], i);
            }

            SelfVariable = Expression.Variable(typeof(object[]), name: null);
            Parent = parent;
            Variables = vars;
            Indexes = new ReadOnlyDictionary<Expression, int>(indexes);
        }
Пример #11
0
        public void ExecuteSimpleDefCommand()
        {
            IList<ParameterExpression> parameters = new ParameterExpression[] { new ParameterExpression("a", null, false), new ParameterExpression("b", null, false) };
            ICommand body = new SetCommand("c", new ConstantExpression(1));
            DefCommand command = new DefCommand("foo", parameters, body);

            Machine machine = new Machine();

            command.Execute(machine.Environment);

            var func = machine.Environment.GetValue("foo");

            Assert.IsNotNull(func);
            Assert.IsInstanceOfType(func, typeof(IFunction));
            Assert.IsInstanceOfType(func, typeof(DefinedFunction));

            var dfunc = (DefinedFunction)func;

            Assert.AreEqual(parameters.Count, dfunc.Parameters.Count);
            Assert.AreEqual(body, dfunc.Body);
        }
        public void CreateAndEvaluateParameterExpressionWithNameAndDefaultExpression()
        {
            var environment = new BindingEnvironment();
            environment.SetValue("b", 1);
            var defaultExpression = new NameExpression("b");
            var expression = new ParameterExpression("a", defaultExpression, false);

            var result = expression.Evaluate(environment);

            Assert.IsNotNull(result);
            Assert.IsInstanceOfType(result, typeof(Parameter));

            var param = (Parameter)result;

            Assert.AreEqual("a", expression.Name);
            Assert.AreEqual(defaultExpression, expression.DefaultExpression);
            Assert.IsFalse(expression.IsList);

            Assert.AreEqual("a", param.Name);
            Assert.AreEqual(1, param.DefaultValue);
            Assert.IsFalse(param.IsList);
        }
 public ParameterExpressionProxy(ParameterExpression node) {
     _node = node;
 }
Пример #14
0
 public LightExceptionCheckExpression(Expression expr, Type retType, LabelTarget currentHandler, ParameterExpression lastValue) {
     _expr = expr;
     _retType = retType;
     _target = currentHandler;
     _lastValue = lastValue;
 }
Пример #15
0
 /// <summary>
 /// 替换参数
 /// </summary>
 /// <typeparam name="T">动态实体</typeparam>
 /// <param name="expr1"></param>
 /// <param name="expr2"></param>
 /// <param name="newParameter"></param>
 /// <returns></returns>
 public static (Expression left, Expression right) ReplaceParameter <T>(this Expression <Func <T, bool> > expr1,
                                                                        Expression <Func <T, bool> > expr2, out ParameterExpression newParameter)
 {
Пример #16
0
 /// <summary>
 /// False coalescing expression.
 /// {result} ::= IsTrue(tmp = {left}) ? tmp : {right}
 /// Generalized OR semantics.
 /// </summary>
 public static Expression CoalesceFalse(Expression left, Expression right, MethodInfo isTrue, out ParameterExpression temp)
 {
     ContractUtils.RequiresNotNull(isTrue, "isTrue");
     return(CoalesceInternal(left, right, isTrue, true, out temp));
 }
Пример #17
0
 public static Expression<Func<ValueObject, string>> GetSelectDimension(string nomDimension)
 {
     ParameterExpression param = Expression.Parameter(typeof(ValueObject), "x");
     MemberExpression member = Expression.Property(param, nomDimension);
     return Expression.Lambda<Func<ValueObject, string>>(member, param);
 }
 private void AddressOf(ParameterExpression node, Type type)
 {
     if (TypeUtils.AreEquivalent(type, node.Type))
     {
         if (node.IsByRef)
         {
             _scope.EmitGet(node);
         }
         else
         {
             _scope.EmitAddressOf(node);
         }
     }
     else
     {
         EmitExpressionAddress(node, type);
     }
 }
Пример #19
0
 internal Storage(LambdaCompiler compiler, ParameterExpression variable) {
     Compiler = compiler;
     Variable = variable;
 }
Пример #20
0
 /// <summary>
 /// Creates a <see cref="CatchBlock"/> representing a catch statement with
 /// an <see cref="Exception"/> filter and a reference to the caught <see cref="Exception"/> object.
 /// </summary>
 /// <param name="variable">A <see cref="ParameterExpression"/> representing a reference to the <see cref="Exception"/> object caught by this handler.</param>
 /// <param name="body">The body of the catch statement.</param>
 /// <param name="filter">The body of the <see cref="Exception"/> filter.</param>
 /// <returns>The created <see cref="CatchBlock"/>.</returns>
 public static CatchBlock Catch(ParameterExpression variable, Expression body, Expression filter)
 {
     ContractUtils.RequiresNotNull(variable, "variable");
     return(MakeCatchBlock(variable.Type, variable, body, filter));
 }
Пример #21
0
 public StatisVisitor(ParameterExpression newParamter)
 {
     _newParamter = newParamter;
 }
        private IList <MemberAssignment> ProcessEntry(SelectEntry entry, ParameterExpression parameter, string suffix = "")
        {
            List <MemberAssignment> bindings = new List <MemberAssignment>();
            Type type = parameter.Type;

            //process the sub properties
            if (entry.Childs.Count > 0)
            {
                PropertyInfo     propertyInfo   = Utils.GetPropertyInfo(parameter.Type, entry.Property);
                MemberExpression originalMember = Expression.Property(parameter, propertyInfo);

                Type childType = propertyInfo.PropertyType;
                ParameterExpression     childParameter = Expression.Parameter(childType, entry.Property);
                List <MemberAssignment> subBindings    = new List <MemberAssignment>();



                var isCollection = Utils.IsEnumerable(childParameter);
                //The property is a Enumerable
                if (isCollection)
                {
                    // Get the type of the child elements
                    Type elementType = childType.GetGenericArguments()[0];
                    // Create an expression for the parameter
                    ParameterExpression elementParameter = Expression.Parameter(elementType, entry.Property + ".Element");

                    foreach (SelectEntry e in entry.Childs)
                    {
                        subBindings.AddRange(ProcessEntry(e, elementParameter));
                    }

                    // Convert the list to Queryable
                    Expression asQueryable = Utils.AsQueryable(childParameter);
                    //Expression to generate a new element of the list
                    NewExpression        newElementExpression  = Expression.New(elementType);
                    MemberInitExpression initElementExpression = Expression.MemberInit(newElementExpression, subBindings);
                    //Iterate over the original elements (Queryable.Select)
                    MethodCallExpression selectExpr = Expression.Call(typeof(Queryable), "Select", new[] { elementType, elementType }, asQueryable, MakeLambda(initElementExpression, elementParameter));
                    //Convert the result to list
                    Expression toListCall = Expression.Call(typeof(Enumerable), "ToList", selectExpr.Type.GetGenericArguments(), selectExpr);
                    // Check for null original collection (avoid null pointer)
                    Expression notNullConditionExpression = Expression.NotEqual(childParameter, Expression.Constant(null, childParameter.Type));
                    Expression trueExpression             = MakeLambda(Expression.Convert(toListCall, childParameter.Type), childParameter);
                    Expression falseExpression            = MakeLambda(Expression.Constant(null, childParameter.Type), childParameter);

                    Expression notNullExpression = Expression.Condition(notNullConditionExpression, trueExpression, falseExpression);
                    Expression notNullLambda     = MakeLambda(Expression.Invoke(notNullExpression, originalMember), childParameter);

                    //Invocate the null-check expression
                    Expression invocation = Expression.Invoke(notNullLambda, originalMember);
                    // Add the invocation to the bindings on the original element
                    bindings.Add(Expression.Bind(propertyInfo, invocation));
                }
                else
                {
                    // Add the child entities to the initialization bindings of the object
                    foreach (SelectEntry e in entry.Childs)
                    {
                        subBindings.AddRange(ProcessEntry(e, childParameter));
                    }
                    // Add the lambda to the bindings of the property in the parent object
                    bindings.Add(Expression.Bind(propertyInfo, CreateNewObject(childParameter, childType, subBindings, originalMember)));
                }
            }
            else
            {
                // Add the property to the init bindings
                bindings.Add(AssignProperty(parameter.Type, entry.Property, parameter));
            }
            return(bindings);
        }
Пример #23
0
        public override Expression GetSerializerExpression(Type memberType, Expression getterExp, ParameterExpression writerExp)
        {
            Debug.Assert(_innerBuilder != null, "Underlying builder can't be null for CheckNullBuilder");
            if (memberType.GetTypeInfo().IsValueType)
            {
                return(_innerBuilder.GetSerializerExpression(memberType, getterExp, writerExp));
            }

            var boolType    = typeof(bool);
            var valueExp    = getterExp;
            var writeMethod = GetWriterMethod("Write", boolType);
            var bodyExp     = _innerBuilder.GetSerializerExpression(memberType, getterExp, writerExp);

            return(Expression.IfThenElse(
                       Expression.Equal(valueExp, Expression.Constant(null, memberType)),
                       Expression.Call(writerExp, writeMethod, Expression.Constant(false, boolType)),
                       Expression.Block(Expression.Call(writerExp, writeMethod, Expression.Constant(true, boolType)), bodyExp)));
        }
Пример #24
0
        protected override Expression VisitParameter(ParameterExpression parameter)
        {
            Add(parameter.Name.GetHashCode());

            return(parameter);
        }
Пример #25
0
        static Expression <Func <TEntity, bool> > BuildPredicate <TEntity>(object key)
        {
            /*
             * key:
             * 如果实体是单一主键,则传入的 key 与主键属性类型相同的值
             * 如果实体是多主键,则传入的 key 须是包含了与实体主键类型相同的属性的对象,如:new { Key1 = "1", Key2 = "2" }
             */

            Utils.CheckNull(key);

            Type           entityType     = typeof(TEntity);
            TypeDescriptor typeDescriptor = TypeDescriptor.GetDescriptor(entityType);

            EnsureEntityHasPrimaryKey(typeDescriptor);

            KeyValuePairList <MemberInfo, object> keyValueMap = new KeyValuePairList <MemberInfo, object>();

            if (typeDescriptor.PrimaryKeys.Count == 1)
            {
                keyValueMap.Add(typeDescriptor.PrimaryKeys[0].MemberInfo, key);
            }
            else
            {
                /*
                 * key: new { Key1 = "1", Key2 = "2" }
                 */

                object multipleKeyObject     = key;
                Type   multipleKeyObjectType = multipleKeyObject.GetType();

                for (int i = 0; i < typeDescriptor.PrimaryKeys.Count; i++)
                {
                    MappingMemberDescriptor keyMemberDescriptor = typeDescriptor.PrimaryKeys[i];
                    MemberInfo keyMember = multipleKeyObjectType.GetProperty(keyMemberDescriptor.MemberInfo.Name);
                    if (keyMember == null)
                    {
                        throw new ArgumentException(string.Format("The input object does not define property for key '{0}'.", keyMemberDescriptor.MemberInfo.Name));
                    }

                    object value = keyMember.GetMemberValue(multipleKeyObject);
                    if (value == null)
                    {
                        throw new ArgumentException(string.Format("The primary key '{0}' could not be null.", keyMemberDescriptor.MemberInfo.Name));
                    }

                    keyValueMap.Add(keyMemberDescriptor.MemberInfo, value);
                }
            }

            ParameterExpression parameter  = Expression.Parameter(entityType, "a");
            Expression          lambdaBody = null;

            foreach (var keyValue in keyValueMap)
            {
                Expression propOrField  = Expression.PropertyOrField(parameter, keyValue.Key.Name);
                Expression wrappedValue = Chloe.Extensions.ExpressionExtension.MakeWrapperAccess(keyValue.Value, keyValue.Key.GetMemberType());
                Expression e            = Expression.Equal(propOrField, wrappedValue);
                lambdaBody = lambdaBody == null ? e : Expression.AndAlso(lambdaBody, e);
            }

            Expression <Func <TEntity, bool> > predicate = Expression.Lambda <Func <TEntity, bool> >(lambdaBody, parameter);

            return(predicate);
        }
Пример #26
0
 public NewExpressionVisitor(ParameterExpression param)
 {
     this._NewParameter = param;
 }
Пример #27
0
 /// <summary>
 /// Creates a <see cref="CatchBlock"/> representing a catch statement with 
 /// an <see cref="Exception"/> filter and a reference to the caught <see cref="Exception"/> object.
 /// </summary>
 /// <param name="variable">A <see cref="ParameterExpression"/> representing a reference to the <see cref="Exception"/> object caught by this handler.</param>
 /// <param name="body">The body of the catch statement.</param>
 /// <param name="filter">The body of the <see cref="Exception"/> filter.</param>
 /// <returns>The created <see cref="CatchBlock"/>.</returns>
 public static CatchBlock Catch(ParameterExpression variable, Expression body, Expression filter) {
     ContractUtils.RequiresNotNull(variable, "variable");
     return MakeCatchBlock(variable.Type, variable, body, filter);
 }
Пример #28
0
 protected override Expression VisitParameter(ParameterExpression node)
 {
     return(_newParamter);
 }
Пример #29
0
 internal CatchBlock(Type test, ParameterExpression variable, Expression body, Expression filter) {
     _test = test;
     _var = variable;
     _body = body;
     _filter = filter;
 }
Пример #30
0
 /// <summary>
 /// Null coalescing expression
 /// {result} ::= ((tmp = {_left}) == null) ? {right} : tmp
 /// '??' operator in C#.
 /// </summary>
 public static Expression Coalesce(Expression left, Expression right, out ParameterExpression temp)
 {
     return(CoalesceInternal(left, right, null, false, out temp));
 }
Пример #31
0
 internal ElementBoxStorage(Storage array, int index, ParameterExpression variable)
     : base(array.Compiler, variable) {
     _array = array;
     _index = index;
     _boxType = typeof(StrongBox<>).MakeGenericType(variable.Type);
     _boxValueField = _boxType.GetField("Value");
 }
Пример #32
0
 private void CacheBoxToLocal(LambdaCompiler lc, ParameterExpression v)
 {
     Debug.Assert(ShouldCache(v) && !_locals.ContainsKey(v));
     var local = new LocalBoxStorage(lc, v);
     local.EmitStoreBox();
     _locals.Add(v, local);
 }
Пример #33
0
        /// <summary>
        /// Parser语法分析器
        /// </summary>
        /// <param name="parameter">参数表达式</param>
        /// <param name="expression"></param>
        /// <returns></returns>
        private static Expression Parser(ParameterExpression parameter, Expression expression)
        {
            if (expression == null)
            {
                return(null);
            }
            switch (expression.NodeType)
            {
            //一元运算符
            case ExpressionType.Negate:
            case ExpressionType.NegateChecked:
            case ExpressionType.Not:
            case ExpressionType.Convert:
            case ExpressionType.ConvertChecked:
            case ExpressionType.ArrayLength:
            case ExpressionType.Quote:
            case ExpressionType.TypeAs:
            {
                var unary = expression as UnaryExpression;
                var exp   = Parser(parameter, unary.Operand);
                return(Expression.MakeUnary(expression.NodeType, exp, unary.Type, unary.Method));
            }

            //二元运算符
            case ExpressionType.Add:
            case ExpressionType.AddChecked:
            case ExpressionType.Subtract:
            case ExpressionType.SubtractChecked:
            case ExpressionType.Multiply:
            case ExpressionType.MultiplyChecked:
            case ExpressionType.Divide:
            case ExpressionType.Modulo:
            case ExpressionType.And:
            case ExpressionType.AndAlso:
            case ExpressionType.Or:
            case ExpressionType.OrElse:
            case ExpressionType.LessThan:
            case ExpressionType.LessThanOrEqual:
            case ExpressionType.GreaterThan:
            case ExpressionType.GreaterThanOrEqual:
            case ExpressionType.Equal:
            case ExpressionType.NotEqual:
            case ExpressionType.Coalesce:
            case ExpressionType.ArrayIndex:
            case ExpressionType.RightShift:
            case ExpressionType.LeftShift:
            case ExpressionType.ExclusiveOr:
            {
                var binary     = expression as BinaryExpression;
                var left       = Parser(parameter, binary.Left);
                var right      = Parser(parameter, binary.Right);
                var conversion = Parser(parameter, binary.Conversion);
                if (binary.NodeType == ExpressionType.Coalesce && binary.Conversion != null)
                {
                    return(Expression.Coalesce(left, right, conversion as LambdaExpression));
                }
                else
                {
                    return(Expression.MakeBinary(expression.NodeType, left, right, binary.IsLiftedToNull,
                                                 binary.Method));
                }
            }

            //其他
            case ExpressionType.Call:
            {
                var call = expression as MethodCallExpression;
                List <Expression> arguments = new List <Expression>();
                foreach (var argument in call.Arguments)
                {
                    arguments.Add(Parser(parameter, argument));
                }
                var instance = Parser(parameter, call.Object);
                call = Expression.Call(instance, call.Method, arguments);
                return(call);
            }

            case ExpressionType.Lambda:
            {
                var lambda = expression as LambdaExpression;
                return(Parser(parameter, lambda.Body));
            }

            case ExpressionType.MemberAccess:
            {
                var memberAccess = expression as MemberExpression;
                if (memberAccess.Expression == null)
                {
                    memberAccess = Expression.MakeMemberAccess(null, memberAccess.Member);
                }
                else
                {
                    var exp    = Parser(parameter, memberAccess.Expression);
                    var member = exp.Type.GetMember(memberAccess.Member.Name).FirstOrDefault();
                    memberAccess = Expression.MakeMemberAccess(exp, member);
                }
                return(memberAccess);
            }

            case ExpressionType.Parameter:
                return(parameter);

            case ExpressionType.Constant:
                return(expression);

            case ExpressionType.TypeIs:
            {
                var typeis = expression as TypeBinaryExpression;
                var exp    = Parser(parameter, typeis.Expression);
                return(Expression.TypeIs(exp, typeis.TypeOperand));
            }

            default:
                throw new Exception($"Unhandled expression type:{expression.NodeType}");
            }
        }
Пример #34
0
 private void AddressOf(ParameterExpression node, Type type) {
     if (type == node.Type) {
         if (node.IsByRef) {
             _scope.EmitGet(node);
         } else {
             _scope.EmitAddressOf(node);
         }
     } else {
         EmitExpressionAddress(node, type);
     }
 }
Пример #35
0
 protected override Expression VisitParameter(ParameterExpression node)
 {
     return(ChangeSource_VisitParameter(node, _paramters));
 }
Пример #36
0
 protected override Expression VisitParameter(ParameterExpression p)
 {
     return(this.ParameterExpression);
 }
Пример #37
0
 private void CombineExp(Expression <Func <T, bool> > expression, bool condition, ParameterExpression parameter, Func <Expression, Expression, BinaryExpression> exp)
 {
     if (condition)
     {
         if (filter != null)
         {
             Expression left  = Rebuild(filter.Body, parameter);
             Expression right = Rebuild(expression.Body, parameter);
             filter = (Expression <Func <T, bool> >)Expression.Lambda(exp(left, right), parameter);
         }
         else if (filter == null)
         {
             filter = expression;
         }
     }
 }
Пример #38
0
        /// <summary>
        /// Gets a filter expression to be used as part of a AttributeValue Query or EntityAttributeQueryExpression
        /// </summary>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="filterValues">The filter values: FieldName, <see cref="ComparisonType">Comparison Type</see>, (optional) Comparison Value(s)</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <returns></returns>
        public virtual Expression AttributeFilterExpression( Dictionary<string, ConfigurationValue> configurationValues, List<string> filterValues, ParameterExpression parameterExpression )
        {
            // If filterValues.Count >= 2, then filterValues[0] is ComparisonType, and filterValues[1] is a CompareToValue. Otherwise, filterValues[0] is a CompareToValue (for example, a SingleSelect attribute)
            if ( filterValues.Count >= 2 )
            {
                ComparisonType? comparisonType = filterValues[0].ConvertToEnumOrNull<ComparisonType>();
                if ( comparisonType.HasValue )
                {
                    string compareToValue = filterValues[1];
                    MemberExpression propertyExpression = Expression.Property( parameterExpression, this.AttributeValueFieldName );

                    if ( !string.IsNullOrWhiteSpace( compareToValue ) )
                    {
                        // both a comparison type and value are specified, so we can process normally
                        return ComparisonHelper.ComparisonExpression( comparisonType.Value, propertyExpression, AttributeConstantExpression( compareToValue ) );
                    }
                    else
                    {
                        // No comparison value was specified, so we can filter if the Comparison Type using no value still makes sense
                        if ( ( ComparisonType.IsBlank | ComparisonType.IsNotBlank ).HasFlag( comparisonType ) )
                        {
                            // Just checking if IsBlank or IsNotBlank, so let ComparisonExpression do its thing
                            return ComparisonHelper.ComparisonExpression( comparisonType.Value, propertyExpression, AttributeConstantExpression( string.Empty ) );
                        }
                        else if ( this.FilterComparisonType.HasFlag( ComparisonType.IsBlank ) )
                        {
                            // if this Filter supports IsBlank/IsNotBlank, we can convert this to IsBlank/IsNotBlank if no value was specified
                            if ( comparisonType == ComparisonType.EqualTo )
                            {
                                // an EqualTo  was specified, but no value was specified, so convert it to a IsBlank
                                return ComparisonHelper.ComparisonExpression( ComparisonType.IsBlank, propertyExpression, AttributeConstantExpression( string.Empty ) );
                            }
                            else if ( comparisonType == ComparisonType.NotEqualTo )
                            {
                                // a NotEqualTo was specified, but no value was specified, so convert it to a IsNotBlank
                                return ComparisonHelper.ComparisonExpression( ComparisonType.IsNotBlank, propertyExpression, AttributeConstantExpression( string.Empty ) );
                            }
                        }
                    }
                }
                else
                {
                    // No comparison type specified, so return NoAttributeFilterExpression ( which means don't filter )
                    return new NoAttributeFilterExpression();
                }
            }

            // return NoAttributeFilterExpression ( which means don't filter ) if there isn't enough information to make a Comparison Expression
            return new NoAttributeFilterExpression();
        }
Пример #39
0
        private Expression ReduceIndex() {
            // left[a0, a1, ... aN] (op)
            //
            // ... is reduced into ...
            //
            // tempObj = left
            // tempArg0 = a0
            // ...
            // tempArgN = aN
            // tempValue = tempObj[tempArg0, ... tempArgN]
            // tempObj[tempArg0, ... tempArgN] = op(tempValue)
            // tempValue

            bool prefix = IsPrefix;
            var index = (IndexExpression)_operand;
            int count = index.Arguments.Count;
            var block = new Expression[count + (prefix ? 2 : 4)];
            var temps = new ParameterExpression[count + (prefix ? 1 : 2)];
            var args = new ParameterExpression[count];

            int i = 0;
            temps[i] = Parameter(index.Object.Type, null);
            block[i] = Assign(temps[i], index.Object);
            i++;
            while (i <= count) {
                var arg = index.Arguments[i - 1];
                args[i - 1] = temps[i] = Parameter(arg.Type, null);
                block[i] = Assign(temps[i], arg);
                i++;
            }
            index = MakeIndex(temps[0], index.Indexer, new TrueReadOnlyCollection<Expression>(args));
            if (!prefix) {
                var lastTemp = temps[i] = Parameter(index.Type, null);
                block[i] = Assign(temps[i], index);
                i++;
                Debug.Assert(i == temps.Length);
                block[i++] = Assign(index, FunctionalOp(lastTemp));
                block[i++] = lastTemp;
            } else {
                Debug.Assert(i == temps.Length);
                block[i++] = Assign(index, FunctionalOp(index));
            }
            Debug.Assert(i == block.Length);
            return Block(new TrueReadOnlyCollection<ParameterExpression>(temps), new TrueReadOnlyCollection<Expression>(block));
        }
Пример #40
0
        /// <summary>
        /// Gets a filter expression for an attribute value.
        /// </summary>
        /// <param name="configurationValues">The configuration values.</param>
        /// <param name="filterValues">The filter values.</param>
        /// <param name="parameterExpression">The parameter expression.</param>
        /// <returns></returns>
        public override Expression AttributeFilterExpression(Dictionary <string, ConfigurationValue> configurationValues, List <string> filterValues, ParameterExpression parameterExpression)
        {
            if (filterValues.Count == 1)
            {
                MemberExpression propertyExpression = Expression.Property(parameterExpression, "ValueAsNumeric");
                ComparisonType   comparisonType     = ComparisonType.EqualTo;
                return(ComparisonHelper.ComparisonExpression(comparisonType, propertyExpression, AttributeConstantExpression(filterValues[0])));
            }

            return(base.AttributeFilterExpression(configurationValues, filterValues, parameterExpression));
        }
Пример #41
0
 private static ParameterExpression NewParameter(ParameterExpression parameterExpression)
 {
     return(Expression.Variable(parameterExpression.Type, parameterExpression.Name));
 }
Пример #42
0
 public RebindParameterVisitor(ParameterExpression oldParameter, ParameterExpression newParameter)
 {
     _oldParameter = oldParameter;
     _newParameter = newParameter;
 }
Пример #43
0
 private void EmitBinaryMethod(BinaryExpression b, CompilationFlags flags) {
     if (b.IsLifted) {
         ParameterExpression p1 = Expression.Variable(TypeUtils.GetNonNullableType(b.Left.Type), null);
         ParameterExpression p2 = Expression.Variable(TypeUtils.GetNonNullableType(b.Right.Type), null);
         MethodCallExpression mc = Expression.Call(null, b.Method, p1, p2);
         Type resultType = null;
         if (b.IsLiftedToNull) {
             resultType = TypeUtils.GetNullableType(mc.Type);
         } else {
             switch (b.NodeType) {
                 case ExpressionType.Equal:
                 case ExpressionType.NotEqual:
                 case ExpressionType.LessThan:
                 case ExpressionType.LessThanOrEqual:
                 case ExpressionType.GreaterThan:
                 case ExpressionType.GreaterThanOrEqual:
                     if (mc.Type != typeof(bool)) {
                         throw Error.ArgumentMustBeBoolean();
                     }
                     resultType = typeof(bool);
                     break;
                 default:
                     resultType = TypeUtils.GetNullableType(mc.Type);
                     break;
             }
         }
         var variables = new ParameterExpression[] { p1, p2 };
         var arguments = new Expression[] { b.Left, b.Right };
         ValidateLift(variables, arguments);
         EmitLift(b.NodeType, resultType, mc, variables, arguments);
     } else {
         EmitMethodCallExpression(Expression.Call(null, b.Method, b.Left, b.Right), flags);
     }
 }
 protected virtual Expression VisitParameter(ParameterExpression p)
 {
     return(p);
 }
Пример #45
0
 protected override Expression VisitParameter(ParameterExpression node)
 {
     return Expression.Parameter(node.IsByRef ? node.Type.MakeByRefType() : node.Type, node.Name);
 }
Пример #46
0
        public virtual void PushdownIntoSubquery()
        {
            var clientProjection = _valueBufferSlots.Count != 0;

            if (!clientProjection)
            {
                var result = new Dictionary <ProjectionMember, Expression>();
                foreach (var keyValuePair in _projectionMapping)
                {
                    if (keyValuePair.Value is EntityProjectionExpression entityProjection)
                    {
                        var map = new Dictionary <IProperty, Expression>();
                        foreach (var property in GetAllPropertiesInHierarchy(entityProjection.EntityType))
                        {
                            var expressionToAdd = entityProjection.BindProperty(property);
                            var index           = AddToProjection(expressionToAdd);
                            map[property] = CreateReadValueExpression(expressionToAdd.Type, index, property);
                        }
                        result[keyValuePair.Key] = new EntityProjectionExpression(entityProjection.EntityType, map);
                    }
                    else
                    {
                        var index = AddToProjection(keyValuePair.Value);
                        result[keyValuePair.Key] = CreateReadValueExpression(
                            keyValuePair.Value.Type, index, InferPropertyFromInner(keyValuePair.Value));
                    }
                }

                _projectionMapping = result;
            }

            var selectorLambda = Lambda(
                New(
                    _valueBufferConstructor,
                    NewArrayInit(
                        typeof(object),
                        _valueBufferSlots
                        .Select(e => e.Type.IsValueType ? Convert(e, typeof(object)) : e))),
                CurrentParameter);

            _groupingParameter = null;

            ServerQueryExpression = Call(
                FileContextLinqOperatorProvider.Select.MakeGenericMethod(ServerQueryExpression.Type.TryGetSequenceType(), typeof(ValueBuffer)),
                ServerQueryExpression,
                selectorLambda);

            if (clientProjection)
            {
                var newValueBufferSlots = _valueBufferSlots
                                          .Select((e, i) => CreateReadValueExpression(e.Type, i, InferPropertyFromInner(e)))
                                          .ToList();

                _valueBufferSlots.Clear();
                _valueBufferSlots.AddRange(newValueBufferSlots);
            }
            else
            {
                _valueBufferSlots.Clear();
            }
        }
Пример #47
0
 protected override Expression VisitParameter(ParameterExpression node)
 {
     return Expression.Parameter(node.Type, node.Name); // clones
 }
 /// <inheritdoc />
 protected abstract override T VisitParameter(ParameterExpression node);
Пример #49
0
        /// <summary>
        /// Creates a <see cref="CatchBlock"/> representing a catch statement with the specified elements.
        /// </summary>
        /// <param name="type">The <see cref="Type"/> of <see cref="Exception"/> this <see cref="CatchBlock"/> will handle.</param>
        /// <param name="variable">A <see cref="ParameterExpression"/> representing a reference to the <see cref="Exception"/> object caught by this handler.</param>
        /// <param name="body">The body of the catch statement.</param>
        /// <param name="filter">The body of the <see cref="Exception"/> filter.</param>
        /// <returns>The created <see cref="CatchBlock"/>.</returns>
        /// <remarks><paramref name="type"/> must be non-null and match the type of <paramref name="variable"/> (if it is supplied).</remarks>
        public static CatchBlock MakeCatchBlock(Type type, ParameterExpression variable, Expression body, Expression filter) {
            ContractUtils.RequiresNotNull(type, "type");
            ContractUtils.Requires(variable == null || TypeUtils.AreEquivalent(variable.Type, type), "variable");
            if (variable != null && variable.IsByRef) {
                throw Error.VariableMustNotBeByRef(variable, variable.Type);
            }
            RequiresCanRead(body, "body");
            if (filter != null) {
                RequiresCanRead(filter, "filter");
                if (filter.Type != typeof(bool)) throw Error.ArgumentMustBeBoolean();
            }

            return new CatchBlock(type, variable, body, filter);
        }
Пример #50
0
 internal ArgumentStorage(LambdaCompiler compiler, ParameterExpression p)
     : base(compiler, p) {
     _argument = compiler.GetLambdaArgument(compiler.Parameters.IndexOf(p));
 }
Пример #51
0
 /// <summary>
 /// Creates a new expression that is like this one, but using the
 /// supplied children. If all of the children are the same, it will
 /// return this expression.
 /// </summary>
 /// <param name="variable">The <see cref="Variable" /> property of the result.</param>
 /// <param name="filter">The <see cref="Filter" /> property of the result.</param>
 /// <param name="body">The <see cref="Body" /> property of the result.</param>
 /// <returns>This expression if no children changed, or an expression with the updated children.</returns>
 public CatchBlock Update(ParameterExpression variable, Expression filter, Expression body) {
     if (variable == Variable && filter == Filter && body == Body) {
         return this;
     }
     return Expression.MakeCatchBlock(Test, variable, body, filter);
 }
Пример #52
0
        protected override SequenceConvertInfo Convert(
            ExpressionBuilder builder, MethodCallExpression methodCall, BuildInfo buildInfo, ParameterExpression param)
        {
            if (methodCall.Arguments.Count == 2)
            {
                var predicate = (LambdaExpression)methodCall.Arguments[1].Unwrap();
                var info      = builder.ConvertSequence(new BuildInfo(buildInfo, methodCall.Arguments[0]), predicate.Parameters[0]);

                if (info != null)
                {
                    info.Expression = methodCall.Transform(ex => ConvertMethod(methodCall, 0, info, predicate.Parameters[0], ex));
                    info.Parameter  = param;

                    return(info);
                }
            }
            else
            {
                var info = builder.ConvertSequence(new BuildInfo(buildInfo, methodCall.Arguments[0]), null);

                if (info != null)
                {
                    info.Expression = methodCall.Transform(ex => ConvertMethod(methodCall, 0, info, null, ex));
                    info.Parameter  = param;

                    return(info);
                }
            }

            return(null);
        }
Пример #53
0
        private void EmitLift(ExpressionType nodeType, Type resultType, MethodCallExpression mc, ParameterExpression[] paramList, Expression[] argList)
        {
            Debug.Assert(TypeUtils.AreEquivalent(TypeUtils.GetNonNullableType(resultType), TypeUtils.GetNonNullableType(mc.Type)));

            switch (nodeType)
            {
                default:
                case ExpressionType.LessThan:
                case ExpressionType.LessThanOrEqual:
                case ExpressionType.GreaterThan:
                case ExpressionType.GreaterThanOrEqual:
                    {
                        Label exit = _ilg.DefineLabel();
                        Label exitNull = _ilg.DefineLabel();
                        LocalBuilder anyNull = _ilg.DeclareLocal(typeof(bool));
                        for (int i = 0, n = paramList.Length; i < n; i++)
                        {
                            ParameterExpression v = paramList[i];
                            Expression arg = argList[i];
                            if (TypeUtils.IsNullableType(arg.Type))
                            {
                                _scope.AddLocal(this, v);
                                EmitAddress(arg, arg.Type);
                                _ilg.Emit(OpCodes.Dup);
                                _ilg.EmitHasValue(arg.Type);
                                _ilg.Emit(OpCodes.Ldc_I4_0);
                                _ilg.Emit(OpCodes.Ceq);
                                _ilg.Emit(OpCodes.Stloc, anyNull);
                                _ilg.EmitGetValueOrDefault(arg.Type);
                                _scope.EmitSet(v);
                            }
                            else
                            {
                                _scope.AddLocal(this, v);
                                EmitExpression(arg);
                                if (!arg.Type.GetTypeInfo().IsValueType)
                                {
                                    _ilg.Emit(OpCodes.Dup);
                                    _ilg.Emit(OpCodes.Ldnull);
                                    _ilg.Emit(OpCodes.Ceq);
                                    _ilg.Emit(OpCodes.Stloc, anyNull);
                                }
                                _scope.EmitSet(v);
                            }
                            _ilg.Emit(OpCodes.Ldloc, anyNull);
                            _ilg.Emit(OpCodes.Brtrue, exitNull);
                        }
                        EmitMethodCallExpression(mc);
                        if (TypeUtils.IsNullableType(resultType) && !TypeUtils.AreEquivalent(resultType, mc.Type))
                        {
                            ConstructorInfo ci = resultType.GetConstructor(new Type[] { mc.Type });
                            _ilg.Emit(OpCodes.Newobj, ci);
                        }
                        _ilg.Emit(OpCodes.Br_S, exit);
                        _ilg.MarkLabel(exitNull);
                        if (TypeUtils.AreEquivalent(resultType, TypeUtils.GetNullableType(mc.Type)))
                        {
                            if (resultType.GetTypeInfo().IsValueType)
                            {
                                LocalBuilder result = GetLocal(resultType);
                                _ilg.Emit(OpCodes.Ldloca, result);
                                _ilg.Emit(OpCodes.Initobj, resultType);
                                _ilg.Emit(OpCodes.Ldloc, result);
                                FreeLocal(result);
                            }
                            else
                            {
                                _ilg.Emit(OpCodes.Ldnull);
                            }
                        }
                        else
                        {
                            switch (nodeType)
                            {
                                case ExpressionType.LessThan:
                                case ExpressionType.LessThanOrEqual:
                                case ExpressionType.GreaterThan:
                                case ExpressionType.GreaterThanOrEqual:
                                    _ilg.Emit(OpCodes.Ldc_I4_0);
                                    break;
                                default:
                                    throw Error.UnknownLiftType(nodeType);
                            }
                        }
                        _ilg.MarkLabel(exit);
                        return;
                    }
                case ExpressionType.Equal:
                case ExpressionType.NotEqual:
                    {
                        if (TypeUtils.AreEquivalent(resultType, TypeUtils.GetNullableType(mc.Type)))
                        {
                            goto default;
                        }
                        Label exit = _ilg.DefineLabel();
                        Label exitAllNull = _ilg.DefineLabel();
                        Label exitAnyNull = _ilg.DefineLabel();

                        LocalBuilder anyNull = _ilg.DeclareLocal(typeof(bool));
                        LocalBuilder allNull = _ilg.DeclareLocal(typeof(bool));
                        _ilg.Emit(OpCodes.Ldc_I4_0);
                        _ilg.Emit(OpCodes.Stloc, anyNull);
                        _ilg.Emit(OpCodes.Ldc_I4_1);
                        _ilg.Emit(OpCodes.Stloc, allNull);

                        for (int i = 0, n = paramList.Length; i < n; i++)
                        {
                            ParameterExpression v = paramList[i];
                            Expression arg = argList[i];
                            _scope.AddLocal(this, v);
                            if (TypeUtils.IsNullableType(arg.Type))
                            {
                                EmitAddress(arg, arg.Type);
                                _ilg.Emit(OpCodes.Dup);
                                _ilg.EmitHasValue(arg.Type);
                                _ilg.Emit(OpCodes.Ldc_I4_0);
                                _ilg.Emit(OpCodes.Ceq);
                                _ilg.Emit(OpCodes.Dup);
                                _ilg.Emit(OpCodes.Ldloc, anyNull);
                                _ilg.Emit(OpCodes.Or);
                                _ilg.Emit(OpCodes.Stloc, anyNull);
                                _ilg.Emit(OpCodes.Ldloc, allNull);
                                _ilg.Emit(OpCodes.And);
                                _ilg.Emit(OpCodes.Stloc, allNull);
                                _ilg.EmitGetValueOrDefault(arg.Type);
                            }
                            else
                            {
                                EmitExpression(arg);
                                if (!arg.Type.GetTypeInfo().IsValueType)
                                {
                                    _ilg.Emit(OpCodes.Dup);
                                    _ilg.Emit(OpCodes.Ldnull);
                                    _ilg.Emit(OpCodes.Ceq);
                                    _ilg.Emit(OpCodes.Dup);
                                    _ilg.Emit(OpCodes.Ldloc, anyNull);
                                    _ilg.Emit(OpCodes.Or);
                                    _ilg.Emit(OpCodes.Stloc, anyNull);
                                    _ilg.Emit(OpCodes.Ldloc, allNull);
                                    _ilg.Emit(OpCodes.And);
                                    _ilg.Emit(OpCodes.Stloc, allNull);
                                }
                                else
                                {
                                    _ilg.Emit(OpCodes.Ldc_I4_0);
                                    _ilg.Emit(OpCodes.Stloc, allNull);
                                }
                            }
                            _scope.EmitSet(v);
                        }
                        _ilg.Emit(OpCodes.Ldloc, allNull);
                        _ilg.Emit(OpCodes.Brtrue, exitAllNull);
                        _ilg.Emit(OpCodes.Ldloc, anyNull);
                        _ilg.Emit(OpCodes.Brtrue, exitAnyNull);

                        EmitMethodCallExpression(mc);
                        if (TypeUtils.IsNullableType(resultType) && !TypeUtils.AreEquivalent(resultType, mc.Type))
                        {
                            ConstructorInfo ci = resultType.GetConstructor(new Type[] { mc.Type });
                            _ilg.Emit(OpCodes.Newobj, ci);
                        }
                        _ilg.Emit(OpCodes.Br_S, exit);

                        _ilg.MarkLabel(exitAllNull);
                        _ilg.EmitBoolean(nodeType == ExpressionType.Equal);
                        _ilg.Emit(OpCodes.Br_S, exit);

                        _ilg.MarkLabel(exitAnyNull);
                        _ilg.EmitBoolean(nodeType == ExpressionType.NotEqual);

                        _ilg.MarkLabel(exit);
                        return;
                    }
            }
        }
Пример #54
0
        public RemoteGroupExpressionCompiler(GroupingInfo[] grouping, SummaryInfo[] totalSummary, SummaryInfo[] groupSummary)
            : base(false)
        {
            _groupByParam = CreateItemParam(typeof(T));

            if (grouping != null)
            {
                foreach (var i in grouping)
                {
                    var selectorExpr = CompileAccessorExpression(_groupByParam, i.Selector);
                    if (!String.IsNullOrEmpty(i.GroupInterval))
                    {
                        var groupIntervalExpr = CompileGroupInterval(selectorExpr, i.GroupInterval);

                        if (Utils.CanAssignNull(selectorExpr.Type))
                        {
                            var nullableType = typeof(Nullable <>).MakeGenericType(groupIntervalExpr.Type);
                            var nullConst    = Expression.Constant(null, nullableType);
                            var test         = Expression.Equal(selectorExpr, nullConst);

                            groupIntervalExpr = Expression.Convert(groupIntervalExpr, nullableType);
                            selectorExpr      = Expression.Condition(test, nullConst, groupIntervalExpr);
                        }
                        else
                        {
                            selectorExpr = groupIntervalExpr;
                        }
                    }

                    _groupKeyExprList.Add(selectorExpr);
                    _descendingList.Add(i.Desc);
                }
            }

            if (totalSummary != null)
            {
                InitSummary(totalSummary, _totalSummaryExprList, _totalSummaryTypes, _totalSummaryParams);
            }

            if (_groupKeyExprList.Any() && groupSummary != null)
            {
                InitSummary(groupSummary, _groupSummaryExprList, _groupSummaryTypes, _groupSummaryParams);
            }

            if (_groupKeyExprList.Count > MAX_GROUPS)
            {
                throw new NotSupportedException($"Maximum number of groups ({MAX_GROUPS}) exceeded");
            }

            if (_totalSummaryExprList.Count > MAX_AGGREGATES)
            {
                throw new NotSupportedException($"Maximum number of total-summary aggregates ({MAX_AGGREGATES}) exceeded");
            }

            if (_groupSummaryExprList.Count > MAX_AGGREGATES)
            {
                throw new NotSupportedException($"Maximum number of group-summary aggregates ({MAX_AGGREGATES}) exceeded");
            }

            var typeArguments = new List <Type>(MAX_GROUPS + 2 * MAX_AGGREGATES);

            for (var i = 0; i < MAX_GROUPS; i++)
            {
                typeArguments.Add(i < _groupKeyExprList.Count ? _groupKeyExprList[i].Type : typeof(Object));
            }

            for (var i = 0; i < MAX_AGGREGATES; i++)
            {
                typeArguments.Add(i < _totalSummaryExprList.Count ? _totalSummaryExprList[i].Type : typeof(Object));
            }

            for (var i = 0; i < MAX_AGGREGATES; i++)
            {
                typeArguments.Add(i < _groupSummaryExprList.Count ? _groupSummaryExprList[i].Type : typeof(Object));
            }

            _remoteGroupClassType = typeof(RemoteGroup <, , , , , , , , , , , , , , , , , , , , , , ,>).MakeGenericType(typeArguments.ToArray());
        }
Пример #55
0
 internal LocalBoxStorage(LambdaCompiler compiler, ParameterExpression variable)
     : base(compiler, variable) {
     _boxType = typeof(StrongBox<>).MakeGenericType(variable.Type);
     _boxValueField = _boxType.GetField("Value");
     _boxLocal = compiler.GetNamedLocal(_boxType, variable);
 }
Пример #56
0
        private static Expression CoalesceInternal(Expression left, Expression right, MethodInfo isTrue, bool isReverse, out ParameterExpression temp)
        {
            ContractUtils.RequiresNotNull(left, "left");
            ContractUtils.RequiresNotNull(right, "right");

            // A bit too strict, but on a safe side.
            ContractUtils.Requires(left.Type == right.Type, "Expression types must match");

            temp = Expression.Variable(left.Type, "tmp_left");

            Expression condition;

            if (isTrue != null)
            {
                ContractUtils.Requires(isTrue.ReturnType == typeof(bool), "isTrue", "Predicate must return bool.");
                ParameterInfo[] parameters = isTrue.GetParameters();
                ContractUtils.Requires(parameters.Length == 1, "isTrue", "Predicate must take one parameter.");
                ContractUtils.Requires(isTrue.IsStatic && isTrue.IsPublic, "isTrue", "Predicate must be public and static.");

                Type pt = parameters[0].ParameterType;
                ContractUtils.Requires(TypeUtils.CanAssign(pt, left.Type), "left", "Incorrect left expression type");
                condition = Expression.Call(isTrue, Expression.Assign(temp, left));
            }
            else
            {
                ContractUtils.Requires(TypeUtils.CanCompareToNull(left.Type), "left", "Incorrect left expression type");
                condition = Expression.Equal(Expression.Assign(temp, left), AstUtils.Constant(null, left.Type));
            }

            Expression t, f;

            if (isReverse)
            {
                t = temp;
                f = right;
            }
            else
            {
                t = right;
                f = temp;
            }

            return(Expression.Condition(condition, t, f));
        }
Пример #57
0
 protected override Expression VisitParameter(ParameterExpression node)
 {
     return(Expression.Constant(this.fake, node.Type));
 }
Пример #58
0
 private bool EqualsParameter(ParameterExpression x, ParameterExpression y)
 {
     return(x.Type == y.Type);
 }
Пример #59
0
        // Helper that is used when re-eval of LHS is safe.
        private Expression ByValParameterTypeEqual(ParameterExpression value) {
            Expression getType = Expression.Call(value, typeof(object).GetMethod("GetType"));
            
            // In remoting scenarios, obj.GetType() can return an interface.
            // But there's a 



            if (_typeOperand.IsInterface) {
                var temp = Expression.Parameter(typeof(Type));
                getType = Expression.Block(new[] { temp }, Expression.Assign(temp, getType), temp);
            }

            // We use reference equality when comparing to null for correctness
            // (don't invoke a user defined operator), and reference equality
            // on types for performance (so the JIT can optimize the IL).
            return Expression.AndAlso(
                Expression.ReferenceNotEqual(value, Expression.Constant(null)),
                Expression.ReferenceEqual(
                    getType, 
                    Expression.Constant(_typeOperand.GetNonNullableType(), typeof(Type))
                )
            );
        }
Пример #60
0
 public ParameterReplacer(ParameterExpression paramExpr)
 {
     this.ParameterExpression = paramExpr;
 }