Ejemplo n.º 1
0
        public SlicerResult VisitAssignment(RtlAssignment ass)
        {
            if (!(ass.Dst is Identifier id))
            {
                // Ignore writes to memory.
                return(null);
            }
            this.assignLhs = ass.Dst;
            var killedRegs = Live.Where(de => de.Key is Identifier i && i.Storage.Domain == id.Storage.Domain).ToList();

            if (killedRegs.Count == 0)
            {
                // This assignment doesn't affect the end result.
                return(null);
            }
            foreach (var killedReg in killedRegs)
            {
                this.Live.Remove(killedReg.Key);
            }
            this.assignLhs = killedRegs[0].Key;
            var se = ass.Src.Accept(this, killedRegs[0].Value);

            if (se == null)
            {
                return(se);
            }
            if (se.SrcExpr != null)
            {
                var newJt = ExpressionReplacer.Replace(assignLhs, se.SrcExpr, JumpTableFormat);
                this.JumpTableFormat = slicer.Simplify(newJt);
            }
            DebugEx.Verbose(BackwardSlicer.trace, "  expr:  {0}", this.JumpTableFormat);
            this.assignLhs = null;
            return(se);
        }
        public async Task <IEnumerable <VegaMoveDeviceData> > GetCurrentAsync(CancellationToken cancellationToken = default)
        {
            var dataIds = (from data in _context.MoveDeviceDatas
                           group data by data.DeviceId into gData
                           select new { gData.Key, date = gData.Max(x => x.Uptime) })
                          .AsNoTracking();

            Expression <Func <VegaMoveDeviceData, bool> > predict = x => false;

            foreach (var item in dataIds)
            {
                Expression <Func <VegaMoveDeviceData, bool> > lambdaNew =
                    x => x.Uptime == item.date && x.DeviceId == item.Key;

                var lambdaBody = ExpressionReplacer
                                 .ReplaceParameter(lambdaNew.Body, lambdaNew.Parameters[0], predict.Parameters[0]);

                var body = Expression.OrElse(predict.Body, lambdaBody);

                predict = Expression.Lambda <Func <VegaMoveDeviceData, bool> >(body, predict.Parameters);
            }

            return(await _context.MoveDeviceDatas
                   .Where(predict)
                   .AsNoTracking()
                   .ToListAsync(cancellationToken)
                   .ConfigureAwait(false));
        }
Ejemplo n.º 3
0
 internal void Compile(params object[] args)
 {
     if (this.fnQuery == null)
     {
         // first identify the query provider being used
         Expression         body = this.query.Body;
         ConstantExpression root = RootQueryableFinder.Find(body) as ConstantExpression;
         if (root == null && args != null && args.Length > 0)
         {
             Expression replaced = ExpressionReplacer.ReplaceAll(
                 body,
                 this.query.Parameters.ToArray(),
                 args.Select((a, i) => Expression.Constant(a, this.query.Parameters[i].Type)).ToArray()
                 );
             body = PartialEvaluator.Eval(replaced);
             root = RootQueryableFinder.Find(body) as ConstantExpression;
         }
         if (root == null)
         {
             throw new InvalidOperationException("Could not find query provider");
         }
         // ask the query provider to compile the query by 'executing' the lambda expression
         IQueryProvider provider = ((IQueryable)root.Value).Provider;
         Delegate       result   = (Delegate)provider.Execute(this.query);
         System.Threading.Interlocked.CompareExchange(ref this.fnQuery, result, null);
     }
 }
        public static Expression ExtractLoopInvariantFatExpressions(this Expression expression, IEnumerable <ParameterExpression> invariantParameters, Func <Expression, Expression> resultSelector)
        {
            var extractedExpressions = new InvariantCodeExtractor(invariantParameters).Extract(expression);

            if (extractedExpressions.Length == 0)
            {
                return(resultSelector(expression));
            }

            var aliases   = new Dictionary <Expression, Expression>();
            var variables = new List <ParameterExpression>();

            foreach (var exp in extractedExpressions)
            {
                if (!aliases.ContainsKey(exp))
                {
                    var variable = Expression.Variable(exp.Type);
                    variables.Add(variable);
                    aliases.Add(exp, variable);
                }
            }

            var optimizedExpression = new ExpressionReplacer(aliases).Visit(expression);

            return(Expression.Block(variables, aliases.Select(pair => Expression.Assign(pair.Value, pair.Key)).Concat(new[] { resultSelector(optimizedExpression) })));
        }
Ejemplo n.º 5
0
        private static Expression Complex(this LambdaExpression current, LambdaExpression other, Func <Expression, Expression, Expression> func)
        {
            if (current == null && other == null)
            {
                return(null);
            }

            if (other == null)
            {
                return(current);
            }

            if (current == null)
            {
                return(other);
            }

            if (current.Parameters.Count != other.Parameters.Count)
            {
                return(null);
            }

            var pars = current.Parameters;

            var left  = current.Body;
            var right = other.Body;

            right = ExpressionReplacer.Replace(right, pars);

            return(func(left, right));
        }
        /// <summary>
        /// Bind parameter expressions to <see cref="LambdaExpression"/>.
        /// </summary>
        /// <param name="lambdaExpression"><see cref="LambdaExpression"/> to bind parameters.</param>
        /// <param name="parameters"><see cref="Expression"/>s to bind to <paramref name="lambdaExpression"/></param>
        /// <returns>Body of <paramref name="lambdaExpression"/> with lambda's parameters replaced
        /// with corresponding expression from <paramref name="parameters"/></returns>
        /// <exception cref="InvalidOperationException">Something went wrong :(.</exception>
        public static Expression BindParameters(this LambdaExpression lambdaExpression, params Expression[] parameters)
        {
            if (lambdaExpression.Parameters.Count != parameters.Length)
            {
                throw new InvalidOperationException(String.Format(
                                                        Strings.ExUnableToBindParametersToLambdaXParametersCountIsIncorrect,
                                                        lambdaExpression.ToString(true)));
            }
            if (parameters.Length == 0)
            {
                return(lambdaExpression);
            }
            var convertedParameters = new Expression[parameters.Length];

            for (int i = 0; i < lambdaExpression.Parameters.Count; i++)
            {
                var expressionParameter = lambdaExpression.Parameters[i];
                if (expressionParameter.Type.IsAssignableFrom(parameters[i].Type))
                {
                    convertedParameters[i] = expressionParameter.Type == parameters[i].Type
            ? parameters[i]
            : Expression.Convert(parameters[i], expressionParameter.Type);
                }
                else
                {
                    throw new InvalidOperationException(String.Format(
                                                            Strings.ExUnableToUseExpressionXAsXParameterOfLambdaXBecauseOfTypeMistmatch,
                                                            parameters[i].ToString(true), i, lambdaExpression.Parameters[i].ToString(true)));
                }
            }
            return(ExpressionReplacer.ReplaceAll(
                       lambdaExpression.Body, lambdaExpression.Parameters, convertedParameters));
        }
Ejemplo n.º 7
0
        private static TExpr ReplaceExpressions <TExpr>(TExpr expression, Expression orig, Expression replacement)
            where TExpr : Expression
        {
            var replacer = new ExpressionReplacer(orig, replacement);

            return(replacer.VisitAndConvert(expression, nameof(ReplaceExpressions)));
        }
Ejemplo n.º 8
0
        public void Test007()
        {
            var builder = ExpressionReplacer.Search(GenericExpressionToSearchIn());

            builder.When(GenericExpressionToSearchFor(), GenericExpressionToReplaceWith());
            builder.ReplaceIn(GenericExpressionToSearchIn());
        }
Ejemplo n.º 9
0
        protected override Expression VisitMethodCall(MethodCallExpression node)
        {
            var obj = base.Visit(node.Object);

            var args = base.Visit(node.Arguments);

            LambdaExpression?lambda = ExpressionCleaner.GetFieldExpansion(obj?.Type, node.Method);

            if (lambda != null)
            {
                var replace = ExpressionReplacer.Replace(Expression.Invoke(lambda, obj == null ? args : args.PreAnd(obj)));

                return(this.Visit(replace));
            }

            if (node.Method.Name == "ToString" && node.Arguments.IsEmpty() && obj is CachedEntityExpression ce)
            {
                var table = (Table)ce.Constructor.table;

                if (table.ToStrColumn == null)
                {
                    throw new InvalidOperationException("Impossible to get ToStrColumn from " + ce.ToString());
                }

                return(BindMember(ce, (FieldValue)table.ToStrColumn, null));
            }

            return(node.Update(obj, args));
        }
Ejemplo n.º 10
0
    public static Expression Replace(InvocationExpression invocation)
    {
        LambdaExpression lambda = (LambdaExpression)invocation.Expression;
        var replacer            = new ExpressionReplacer(0.To(lambda.Parameters.Count).ToDictionaryEx(i => lambda.Parameters[i], i => invocation.Arguments[i]));

        return(replacer.Visit(lambda.Body));
    }
Ejemplo n.º 11
0
            public static Expression Replace(Expression expression, ParameterExpression searchExp, ParameterExpression replaceExp)
            {
                var replacer = new ExpressionReplacer {
                    searchExp = searchExp, replaceExp = replaceExp
                };

                return(replacer.Visit(expression));
            }
Ejemplo n.º 12
0
 public void Test001()
 {
     ExpressionReplacer.Replace(
         GenericExpressionToSearchIn(),
         GenericExpressionToSearchFor(),
         GenericExpressionToReplaceWith()
         );
 }
        private static LambdaExpression Compose(LambdaExpression first, LambdaExpression second)
        {
            var body = ExpressionReplacer.Replace(second.Body,
                                                  second.Parameters [0],
                                                  first.Body);

            return(Expression.Lambda(body, first.Parameters [0]));
        }
Ejemplo n.º 14
0
        protected static Expression ModifyExpressionAndReturnResult(Expression expression, IQueryable queryableEntities, MethodCallExpression expressionToReplace, MethodInfo replacingMethod)
        {
            var replacingExpression = GetReplacingExpression(expressionToReplace, queryableEntities, replacingMethod);

            var treeModifier = new ExpressionReplacer(expressionToReplace, replacingExpression);

            return(treeModifier.Visit(expression));
        }
Ejemplo n.º 15
0
        //internal static Expression JustVisit(LambdaExpression expression, PropertyRoute route)
        //{
        //    if (route.Type.IsLite())
        //        route = route.Add("Entity");

        //    return JustVisit(expression, ));
        //}

        internal static Expression JustVisit(LambdaExpression expression, MetaExpression metaExpression)
        {
            var cleaned = MetaEvaluator.Clean(expression);

            var replaced = ExpressionReplacer.Replace(Expression.Invoke(cleaned, metaExpression));

            return(new MetadataVisitor().Visit(replaced));
        }
Ejemplo n.º 16
0
        public void Test001()
        {
            var xgr = new ExpressionGenerator();

            var e1 = xgr.MultiProject(
                () => new {
                FieldOne = 1,
                FieldTwo = "ABC"
            },
                x => new InitializerOne {
                IntField    = x.FieldOne,
                StringField = x.FieldTwo
            },
                _initializerOneTemplate,
                x => new InitializerTwo {
                StringFieldOne = x.FieldTwo + "DEF",
                StringFieldTwo = "GHI" + x.FieldTwo
            },
                _initializerTwoTemplate,
                (x, y) => new {
                InitializerOneResult = x,
                InitializerTwoResult = y
            }
                );

            var inputPlaceholder = xgr.FromFunc(() => new {
                FieldOne = 1,
                FieldTwo = "ABC"
            });
            var expectations = xgr.FromFunc(inputPlaceholder, x => new {
                InitializerOneResult = (new InitializerOne {
                    IntField = x.FieldOne,
                    StringField = x.FieldTwo
                }).StringField + (new InitializerOne
                {
                    IntField = x.FieldOne,
                    StringField = x.FieldTwo
                }).IntField,
                InitializerTwoResult = (new InitializerTwo {
                    StringFieldOne = x.FieldTwo + "DEF",
                    StringFieldTwo = "GHI" + x.FieldTwo
                }).StringFieldTwo + (new InitializerTwo
                {
                    StringFieldOne = x.FieldTwo + "DEF",
                    StringFieldTwo = "GHI" + x.FieldTwo
                }).StringFieldOne
            });

            var inputParam = Expression.Parameter(inputPlaceholder.ReturnType);
            var expected   = Expression.Lambda(
                ExpressionReplacer.Replace(expectations.Body, inputPlaceholder.Body, inputParam),
                inputParam
                );

            var comparer = new ExpressionComparer();

            Assert.IsTrue(comparer.AreEqual(expected, e1));
        }
Ejemplo n.º 17
0
        private static TContainer DoArrange <TContainer>(object obj, Type objType, LambdaExpression expression, Func <TContainer> containerFactory) where TContainer : IMethodMock
        {
            var repo                     = MockingContext.CurrentRepository;
            var instanceParam            = expression.Parameters[0];
            var instanceConstant         = Expression.Constant(obj);
            var parameterlessBody        = ExpressionReplacer.Replace(expression.Body, instanceParam, instanceConstant);
            var parameterlessArrangeStmt = Expression.Lambda(parameterlessBody);

            return(repo.Arrange(parameterlessArrangeStmt, containerFactory));
        }
Ejemplo n.º 18
0
        public void Test014()
        {
            var builder = ExpressionReplacer.PrepareSearch();

            try { builder.GetResult(); Assert.Fail("Test should not reach here"); }
            catch (NullReferenceException eError)
            {
                Assert.AreEqual("no target, perhaps you want ReplaceIn() instead", eError.Message);
            }
        }
        protected override Expression VisitMethodCall(MethodCallExpression node)
        {
            if (node.Method.DeclaringType == typeof(string) && node.Method.Name == nameof(string.Format) ||
                node.Method.DeclaringType == typeof(StringExtensions) && node.Method.Name == nameof(StringExtensions.FormatWith))
            {
                var formatStr  = Visit(node.Arguments[0]);
                var remainging = node.Arguments.Skip(1).Select(a => Visit(ToString(a))).ToList();


                return(node.Update(null, new Sequence <Expression> {
                    formatStr, remainging
                }));
            }

            var obj  = base.Visit(node.Object);
            var args = base.Visit(node.Arguments);

            if (node.Method.Name == "ToString" && node.Arguments.IsEmpty() && obj is CachedEntityExpression ce && ce.Type.IsEntity())
            {
                var table = (Table)ce.Constructor.table;

                if (table.ToStrColumn != null)
                {
                    return(BindMember(ce, (FieldValue)table.ToStrColumn, null));
                }
                else if (this.root != ce)
                {
                    var cachedTableType = typeof(CachedTable <>).MakeGenericType(table.Type);

                    ConstantExpression tab = Expression.Constant(ce.Constructor.cachedTable, cachedTableType);

                    var mi = cachedTableType.GetMethod(nameof(CachedTable <Entity> .GetToString));

                    return(Expression.Call(tab, mi, ce.PrimaryKey.UnNullify()));
                }
            }

            LambdaExpression?lambda = ExpressionCleaner.GetFieldExpansion(obj?.Type, node.Method);

            if (lambda != null)
            {
                var replace = ExpressionReplacer.Replace(Expression.Invoke(lambda, obj == null ? args : args.PreAnd(obj)));

                return(this.Visit(replace));
            }

            if (node.Method.Name == nameof(Entity.Mixin) && obj is CachedEntityExpression cee)
            {
                var mixin = ((Table)cee.Constructor.table).GetField(node.Method);

                return(GetField(mixin, cee.Constructor, cee.PrimaryKey));
            }

            return(node.Update(obj, args));
        }
Ejemplo n.º 20
0
 protected override Expression VisitInvocation(InvocationExpression iv)
 {
     if (iv.Expression is LambdaExpression)
     {
         return(Visit(ExpressionReplacer.Replace(iv)));
     }
     else
     {
         return(base.VisitInvocation(iv)); //Just calling a delegate in the projector
     }
 }
        private MappingEntry CreateMappingEntry(Expression expression)
        {
            var tupleAccess = expression.StripCasts().AsTupleAccess();

            if (tupleAccess != null)
            {
                return(new MappingEntry(tupleAccess.GetTupleAccessArgument()));
            }
            expression = ExpressionReplacer.Replace(expression, filterDataTuple, calculatedColumnParameter);
            return(new MappingEntry(FastExpression.Lambda(expression, calculatedColumnParameter)));
        }
Ejemplo n.º 22
0
        public static Expression <Func <T, bool> > AddWithAnd <T>(this Expression <Func <T, bool> > expr1, Expression <Func <T, bool> > expr2)
        {
            if (expr1 == null)
            {
                return(expr2);
            }
            var replacer        = new ExpressionReplacer(CreateFromToReplaceSet(expr2.Parameters, expr1.Parameters), null, null, null, null);
            var rightExpression = (LambdaExpression)replacer.HandleExpression(expr2);

            return(Expression.Lambda <Func <T, bool> >
                       (Expression.AndAlso(expr1.Body, rightExpression.Body), expr1.Parameters));
        }
Ejemplo n.º 23
0
        private static void GetGeneralMemberBindings(object obj, Type sourceType, Type conversionType, ParameterExpression parExp, List <MemberBinding> bindings, ConvertMapper mapper)
        {
            var lazyMgr = obj as ILazyManager;

            foreach (var property in conversionType.GetProperties(BindingFlags.Public | BindingFlags.Instance))
            {
                try
                {
                    if (lazyMgr != null && !lazyMgr.IsValueCreated(property.Name))
                    {
                        continue;
                    }

                    Expression descExp = null;

                    //在映射器里查找转换表达式
                    if (mapper != null)
                    {
                        descExp = mapper.GetMapExpression(property);
                        if (descExp != null)
                        {
                            descExp = (ExpressionReplacer.Replace(descExp, parExp) as LambdaExpression).Body;
                        }
                    }

                    if (descExp == null)
                    {
                        var sourceProperty = sourceType.GetProperty(property.Name, BindingFlags.Public | BindingFlags.Instance);
                        if (sourceProperty == null || !sourceProperty.CanRead || !property.CanWrite)
                        {
                            continue;
                        }

                        descExp = Expression.MakeMemberAccess(parExp, sourceProperty);
                        if (property.PropertyType != sourceProperty.PropertyType)
                        {
                            descExp = Expression.Call(null, MthToType,
                                                      Expression.Convert(descExp, typeof(object)),
                                                      Expression.Constant(property.PropertyType),
                                                      Expression.Constant(null),
                                                      Expression.Constant(null, typeof(ConvertMapper)));
                            descExp = Expression.Convert(descExp, property.PropertyType);
                        }
                    }

                    bindings.Add(Expression.Bind(property, descExp));
                }
                catch
                {
                    continue;
                }
            }
        }
Ejemplo n.º 24
0
 public static void ApplyFunctionalSpec <T>(T mock, Expression <Func <T, bool> > specExpr, IReturnArranger arranger)
 {
     try
     {
         var body = ExpressionReplacer.Replace(specExpr.Body, specExpr.Parameters[0], Expression.Constant(mock, typeof(T)));
         ApplySpecExpression(body, arranger);
     }
     catch (InvalidCastException ex)
     {
         throw new MockException("Incorrect functional spec expression format.", ex);
     }
 }
        public static Expression <Func <T, bool> > MakePropertiesPredicate <T, TValue>(Expression <Func <TValue, TValue, bool> > pattern, TValue searchValue, bool isOr)
        {
            var parameter  = Expression.Parameter(typeof(T), "e");
            var searchExpr = Expression.Constant(searchValue);

            var predicateBody = typeof(T).GetProperties()
                                .Where(p => p.PropertyType == typeof(TValue))
                                .Select(p =>
                                        ExpressionReplacer.GetBody(pattern, Expression.MakeMemberAccess(
                                                                       parameter, p), searchExpr))
                                .Aggregate(isOr ? Expression.OrElse : Expression.AndAlso);

            return(Expression.Lambda <Func <T, bool> >(predicateBody, parameter));
        }
Ejemplo n.º 26
0
        private static void DoAssert(object obj, Type objType, LambdaExpression expression, Args args, Occurs occurs)
        {
            var        repo = MockingContext.CurrentRepository;
            Expression parameterlessArrangeStmt = null;

            if (expression != null)
            {
                var instanceParam     = expression.Parameters[0];
                var instanceConstant  = Expression.Constant(obj);
                var parameterlessBody = ExpressionReplacer.Replace(expression.Body, instanceParam, instanceConstant);
                parameterlessArrangeStmt = Expression.Lambda(parameterlessBody);
            }
            repo.Assert(obj, parameterlessArrangeStmt, args, occurs);
        }
Ejemplo n.º 27
0
        public static TExpression Replace <TExpression>(
            this TExpression expression,
            Dictionary <Expression, Expression> replacementsByTarget)
            where TExpression : Expression
        {
            if (replacementsByTarget.None())
            {
                return(expression);
            }

            var replacer = new ExpressionReplacer(replacementsByTarget);
            var replaced = replacer.ReplaceIn(expression);

            return((TExpression)replaced);
        }
Ejemplo n.º 28
0
        public void AssociateWith(LambdaExpression memberQuery)
        {
            MemberExpression searchFor = RootMemberFinder.Find(memberQuery, memberQuery.Parameters[0]);

            if (searchFor == null)
            {
                throw new InvalidOperationException("Subquery does not originate with a member access");
            }
            if (searchFor != memberQuery.Body)
            {
                ParameterExpression replaceWith = Expression.Parameter(searchFor.Type, "root");
                Expression          body        = ExpressionReplacer.Replace(memberQuery.Body, searchFor, replaceWith);
                this.AddOperation(searchFor.Member, Expression.Lambda(body, new ParameterExpression[] { replaceWith }));
            }
        }
Ejemplo n.º 29
0
        public void AssociateWith(LambdaExpression memberQuery)
        {
            var rootMember = RootMemberFinder.Find(memberQuery, memberQuery.Parameters[0]);

            if (rootMember == null)
            {
                throw new InvalidOperationException("Subquery does not originate with a member access");
            }
            if (rootMember != memberQuery.Body)
            {
                var memberParam = Expression.Parameter(rootMember.Type, "root");
                var newBody     = ExpressionReplacer.Replace(memberQuery.Body, rootMember, memberParam);
                this.AddOperation(rootMember.Member, Expression.Lambda(newBody, memberParam));
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// 在 Select 中应用 <see cref="ExtendAs{T}(IEntity, Expression{Func{object}})"/> 来扩展返回的结果。
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <typeparam name="TResult"></typeparam>
        /// <param name="source"></param>
        /// <param name="selector"></param>
        /// <returns></returns>
        public static IQueryable <TResult> ExtendSelect <TSource, TResult>(this IQueryable <TSource> source, Expression <Func <TSource, TResult> > selector)
        {
            var parExp = Expression.Parameter(typeof(TSource), "t");

            var method = typeof(Extensions).GetMethod(nameof(Extensions.ExtendAs)).MakeGenericMethod(typeof(TResult));

            var newExp      = ExpressionReplacer.Replace(selector.Body, parExp);
            var newSelector = Expression.Lambda <Func <object> >(newExp);

            var callExp = Expression.Call(null, method, parExp, newSelector);
            var lambda  = Expression.Lambda(callExp, parExp);

            var expression = Expression.Call(typeof(Queryable), nameof(Queryable.Select), new[] { typeof(TSource), typeof(TResult) }, source.Expression, lambda);

            return(source.Provider.CreateQuery <TResult>(expression));
        }