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); }
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)); }
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)); }
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])); }
//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)); }
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)); }
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)); }
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)); }
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))); }
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); } }
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; } } }
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); }
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 })); } }
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)); } }
/// <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)); }
private static void GetGeneralMemberAssignments(object source, object target, Type sourceType, Type targetType, ParameterExpression sourceParExp, ParameterExpression targetParExp, List <BinaryExpression> assignments, ConvertMapper mapper) { foreach (var property in targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance)) { try { if (source is ILazyManager lazyMgr && !lazyMgr.IsValueCreated(property.Name)) { continue; } Expression sourceExp = null; //在映射器里查找转换表达式 if (mapper != null) { sourceExp = mapper.GetMapExpression(property); if (sourceExp != null) { sourceExp = (ExpressionReplacer.Replace(sourceExp, sourceParExp) as LambdaExpression).Body; } } if (sourceExp == null) { var sourceProperty = sourceType.GetProperty(property.Name, BindingFlags.Public | BindingFlags.Instance); if (sourceProperty == null || !sourceProperty.CanRead || !property.CanWrite) { continue; } sourceExp = GetPropertyExpression(sourceParExp, target, property, sourceProperty); } var descExp = Expression.MakeMemberAccess(targetParExp, property); assignments.Add(Expression.Assign(descExp, sourceExp)); } catch { continue; } } }
/// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="V"></typeparam> /// <param name="queryable">数据库查询。</param> /// <param name="target">目标数据,为新增的数据。</param> /// <param name="predicate"></param> /// <returns></returns> internal static List <int> FindRepeatRows <T, V>(IQueryable <T> queryable, IEnumerable <V> target, Expression <Func <T, V, bool> > predicate) { var parExp = Expression.Parameter(typeof(T), "v"); var lambda = predicate as LambdaExpression; var expression = ExpressionReplacer.Replace(lambda.Body, lambda.Parameters[0], parExp); lambda = Expression.Lambda(expression, lambda.Parameters[1]); expression = Expression.Call(typeof(Enumerable), "Any", new[] { typeof(V) }, Expression.Constant(target, typeof(IEnumerable <V>)), lambda); lambda = Expression.Lambda(expression, parExp); expression = Expression.Call(typeof(Queryable), "Where", new[] { typeof(T) }, queryable.Expression, lambda); lambda = Expression.Lambda(expression, parExp); var list = queryable.Provider.Execute <IEnumerable <T> >(lambda).ToList(); var func = predicate.Compile(); return(FindIndex(list, target, func)); }
internal Expression BuildExtension(Type parentType, string key, Expression parentExpression) { var extensionInfo = CompatibleTypes(parentType) .Select(t => RegisteredExtensions.TryGetValue(t)?.TryGetC(key)) .NotNull() .FirstEx(() => $"No Extension found for '{parentType.TypeName()}' and key '{key}'"); var lambda = extensionInfo.Lambda; var targetType = lambda.Parameters[0].Type; var pe = targetType.IsAssignableFrom(parentExpression.Type) ? parentExpression : targetType.IsAssignableFrom(parentExpression.Type.CleanType()) ? parentExpression.ExtractEntity(false) : targetType.IsAssignableFrom(parentExpression.Type.BuildLite()) ? parentExpression.BuildLite() : targetType == parentExpression.Type.Nullify() ? parentExpression.Nullify() : targetType == parentExpression.Type.UnNullify() ? parentExpression.UnNullify() : parentExpression; return(ExpressionReplacer.Replace(Expression.Invoke(extensionInfo.Lambda, pe))); }
public void Test004() { var xgr = new ExpressionGenerator(); var q = Enumerable.Range(0, 1).Select(x => new { FieldOne = 1, FieldTwo = "ABC" }).AsQueryable(); var e1 = xgr.MultiProject( q, x => x.FieldTwo + x.FieldOne, x => "GHI" + x.FieldTwo + x.FieldTwo + "DEF", (x, y) => new { InitializerOneResult = x, InitializerTwoResult = y } ); var inputPlaceholder = xgr.FromFunc(() => new { FieldOne = 1, FieldTwo = "ABC" }); var expectations = xgr.FromFunc(inputPlaceholder, x => new { InitializerOneResult = x.FieldTwo + x.FieldOne, InitializerTwoResult = "GHI" + x.FieldTwo + x.FieldTwo + "DEF" }); var inputParam = Expression.Parameter(inputPlaceholder.ReturnType); var expected = Expression.Lambda( ExpressionReplacer.Replace(expectations.Body, inputPlaceholder.Body, inputParam), inputParam ); var inner1 = e1.Expression as MethodCallExpression; var inner2 = inner1.Arguments[1] as UnaryExpression; var inner3 = inner2.Operand as LambdaExpression; var comparer = new ExpressionComparer(); Assert.IsTrue(comparer.AreEqual(expected, inner3)); }
protected internal override Expression VisitPipeline(PipelineExpression node) { // only do the root source of this one... var source = node.Source; var sourcedSource = source as ISourcedExpression; while (sourcedSource != null) { source = sourcedSource.Source; sourcedSource = source as ISourcedExpression; } var newSource = Visit(source); if (newSource != source) { return(ExpressionReplacer.Replace(node, source, newSource)); } return(node); }
private Expression BindMember(CachedEntityExpression n, Field field, Expression?prevPrimaryKey) { Expression body = GetField(field, n.Constructor, prevPrimaryKey); ConstantExpression tab = Expression.Constant(n.Constructor.cachedTable, typeof(CachedTable <>).MakeGenericType(((Table)n.Constructor.table).Type)); Expression origin = Expression.Convert(Expression.Property(Expression.Call(tab, "GetRows", null), "Item", n.PrimaryKey.UnNullify()), n.Constructor.tupleType); var result = ExpressionReplacer.Replace(body, new Dictionary <ParameterExpression, Expression> { { n.Constructor.origin, origin } }); if (!n.PrimaryKey.Type.IsNullable()) { return(result); } return(Expression.Condition( Expression.Equal(n.PrimaryKey, Expression.Constant(null, n.PrimaryKey.Type)), Expression.Constant(null, result.Type.Nullify()), result.Nullify())); }
public Expression Transform(MethodCallExpression node) { if (!ExpressionHelper.IsLinqMethod(node, "Select") || !ExpressionHelper.IsLambda(node.Arguments[1], 1)) { return(node); } var call = node.Arguments[0] as MethodCallExpression; if (call == null || !ExpressionHelper.IsLinqMethod(call, "Select") || !ExpressionHelper.IsLambda(call.Arguments[1], 1)) { return(node); } var innerLambda = ExpressionHelper.GetLambda(call.Arguments[1]); var outerLambda = ExpressionHelper.GetLambda(node.Arguments[1]); var sourceType = innerLambda.Parameters[0].Type; var resultType = outerLambda.Body.Type; var innerSelector = innerLambda.Body; var outerSelector = outerLambda.Body; var selector = ExpressionReplacer.Replace(outerSelector, outerLambda.Parameters[0], innerSelector); return(Expression.Call( typeof(Enumerable), "Select", new[] { sourceType, resultType }, call.Arguments[0], Expression.Lambda( typeof(Func <,>).MakeGenericType(sourceType, resultType), selector, innerLambda.Parameters[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); } ReadOnlyCollection <ParameterExpression> parameters = current.Parameters; Expression body = current.Body; Expression expression2 = ExpressionReplacer.Replace(other.Body, parameters); return(func(body, expression2)); }
protected internal override Expression VisitPipeline(PipelineExpression node) { var source = node.Source; var sourcedSource = source as ISourcedExpression; while (sourcedSource != null) { source = sourcedSource.Source; sourcedSource = source as ISourcedExpression; } var newSource = Visit(source); PipelineExpression newNode = node; if (newSource != source) { newNode = (PipelineExpression)ExpressionReplacer.Replace(node, source, newSource); } return(newNode.Update( newNode.Source, newNode.Projector, VisitResultOperator(newNode.ResultOperator))); }
private Expression GetHasValue(Expression exp) { if (exp is ConstantExpression && ((ConstantExpression)exp).Value == null) { return(Expression.Constant(false, typeof(bool))); } if (exp is CachedEntityExpression n && n.FieldEmbedded?.HasValue != null) { var body = n.Constructor.GetTupleProperty(n.FieldEmbedded.HasValue); ConstantExpression tab = Expression.Constant(n.Constructor.cachedTable, typeof(CachedTable <>).MakeGenericType(((Table)n.Constructor.table).Type)); Expression origin = Expression.Convert(Expression.Property(Expression.Call(tab, "GetRows", null), "Item", n.PrimaryKey.UnNullify()), n.Constructor.tupleType); var result = ExpressionReplacer.Replace(body, new Dictionary <ParameterExpression, Expression> { { n.Constructor.origin, origin } }); return(result); } throw new InvalidOperationException(""); }
public static Expression Replace(this Expression expression, IDictionary <Expression, Expression> map) { return(ExpressionReplacer.Replace(expression, map.ContainsKey, x => map[x])); }
/// <summary> /// /// </summary> /// <param name="expression"></param> /// <param name="toReplace"></param> /// <param name="replacement"></param> /// <returns></returns> public static Expression Replace(this Expression expression, Expression toReplace, Expression replacement) { return(ExpressionReplacer.Replace(expression, toReplace.Equals, x => replacement)); }
private Expression BuildExtension(Type parentType, string key, Expression parentExpression) { LambdaExpression lambda = RegisteredExtensions.GetValue(parentType)[key].Lambda; return(ExpressionReplacer.Replace(Expression.Invoke(lambda, parentExpression))); }