public void TestExpressionVariables() { ExpressionContext context1 = new ExpressionContext(); context1.Imports.Add(new Import(typeof(Math))); var exp1 = new DynamicExpression("sin(pi)", ExpressionLanguage.Flee); var boundExp1 = exp1.Bind(context1); ExpressionContext context2 = new ExpressionContext(); context2.Imports.Add(new Import(typeof(Math))); var exp2 = new DynamicExpression<double>("cos(pi/2)", ExpressionLanguage.Flee); var boundExp2 = exp2.Bind(context2); ExpressionContext context3 = new ExpressionContext(); context3.Variables.Add("a", boundExp1); context3.Variables.Add("b", boundExp2); var exp3 = new DynamicExpression("cast(a, double) + b", ExpressionLanguage.Flee); double a = Math.Sin(Math.PI); double b = Math.Cos(Math.PI / 2); Assert.AreEqual(a + b, exp3.Invoke(context3)); ExpressionContext context4 = new ExpressionContext(); context4.Variables.Add("a", boundExp1); context4.Variables.Add("b", boundExp2); var exp4 = new DynamicExpression<double>("(cast(a, double) * b) + (b - cast(a, double))", ExpressionLanguage.Flee); Assert.AreEqual((a * b) + (b - a), exp4.Invoke(context4)); }
private static PromoDynamicExpressionTree GetPromotionDynamicExpression() { var customerConditionBlock = new BlockCustomerCondition(); customerConditionBlock.AvailableChildren = new DynamicExpression[] { new ConditionIsEveryone(), new ConditionIsFirstTimeBuyer(), new ConditionIsRegisteredUser() }.ToList(); var catalogConditionBlock = new BlockCatalogCondition(); catalogConditionBlock.AvailableChildren = new DynamicExpression[] { new ConditionEntryIs(), new ConditionCurrencyIs(), new ConditionCodeContains(), new ConditionCategoryIs(), }.ToList(); var cartConditionBlock = new BlockCartCondition(); cartConditionBlock.AvailableChildren = new DynamicExpression[] { new ConditionCartSubtotalLeast(), new ConditionAtNumItemsInCart(), new ConditionAtNumItemsInCategoryAreInCart(), new ConditionAtNumItemsOfEntryAreInCart() }.ToList(); var rewardBlock = new RewardBlock(); rewardBlock.AvailableChildren = new DynamicExpression[] { new RewardCartGetOfAbsSubtotal(), new RewardItemGetFreeNumItemOfProduct(), new RewardItemGetOfAbs(), new RewardItemGetOfAbsForNum(), new RewardItemGetOfRel(), new RewardItemGetOfRelForNum(), new RewardItemGiftNumItem(), new RewardShippingGetOfAbsShippingMethod(), new RewardShippingGetOfRelShippingMethod ()}.ToList(); var rootBlocks = new DynamicExpression[] { customerConditionBlock, catalogConditionBlock, cartConditionBlock, rewardBlock }.ToList(); var retVal = new PromoDynamicExpressionTree() { Children = rootBlocks, }; return retVal; }
public void Test() { string translatedString = "uppercase(\"hello\")"; var expr = new DynamicExpression(translatedString, ExpressionLanguage.Csharp); var context = new ExpressionContext(null, new CustomOwner(), true); var boundExpression = expr.Bind(context); object res = boundExpression.Invoke(); }
public ConditionsController(IConditionService conditionService) { _initialCondition = new ConditionExpressionTree(); var conditions = new DynamicExpression[] { new ConditionAgeIs(), new ConditionGenderIs(), new ConditionFirstNameIs(), new ConditionLastNameIs(), new ConditionOrdersIs() }.ToList(); var rootBlock = new BlockConditionAndOr { AvailableChildren = conditions }; _initialCondition.Children = new DynamicExpression[] { rootBlock }; _conditionService = conditionService; }
/// <summary> /// Visits the children of the <see cref="DynamicExpression" />. /// </summary> /// <param name="node">The expression to visit.</param> /// <returns>The modified expression, if it or any subexpression was modified; /// otherwise, returns the original expression.</returns> protected internal virtual Expression VisitDynamic(DynamicExpression node) { Expression[] a = VisitArguments((IArgumentProvider)node); if (a == null) { return node; } return node.Rewrite(a); }
private static ConditionExpressionTree GetContentDynamicExpression() { var conditions = new DynamicExpression[] { new ConditionGeoTimeZone(), new ConditionGeoZipCode(), new ConditionStoreSearchedPhrase(), new ConditionAgeIs(), new ConditionGenderIs(), new ConditionGeoCity(), new ConditionGeoCountry(), new ConditionGeoState(), new ConditionLanguageIs() }.ToList(); var rootBlock = new BlockContentCondition { AvailableChildren = conditions }; var retVal = new ConditionExpressionTree() { Children = new DynamicExpression[] { rootBlock } }; return retVal; }
public void SameTypes() { var dynamicExpression = new DynamicExpression("Variable", ExpressionLanguage.Csharp); var context = new ExpressionContext(); context.Variables.Add(new Variable("Variable") { Value = 1 }); Assert.AreSame( dynamicExpression.Bind(context), dynamicExpression.Bind(context) ); }
public void TestFieldWithSameNameAsVariable() { ExpressionContext context = new ExpressionContext(null, new Monitor()); context.Variables.Add("doubleA", new ExpressionOwner()); this.AssertCompileException("doubleA.doubleA", context); // But it should work for a public member context = new ExpressionContext(); Monitor m = new Monitor(); context.Variables.Add("I", m); var e = new DynamicExpression("i.i", ExpressionLanguage.Flee); Assert.AreEqual(m.I, (int)e.Invoke(context)); }
protected void Resolve(ExpressionContext expressionContext, string expression, object expected, BoundExpressionOptions options) { if (expression == null) throw new ArgumentNullException("expression"); object actual = new DynamicExpression( expression, ExpressionLanguage.Flee ).Invoke( expressionContext ?? new ExpressionContext(), options ); Assert.AreEqual(expected, actual); }
public void DifferentTypesDifferentCache() { var dynamicExpression = new DynamicExpression("Variable", ExpressionLanguage.Flee); var context1 = new ExpressionContext(); context1.Variables.Add(new Variable("Variable") { Value = 1 }); var context2 = new ExpressionContext(); context2.Variables.Add(new Variable("Variable") { Value = 1d }); Assert.AreNotSame( dynamicExpression.Bind(context1), dynamicExpression.Bind(context2) ); }
public void UnusedDifferentTypesAreSame() { var dynamicExpression = new DynamicExpression("1", ExpressionLanguage.Csharp); var context1 = new ExpressionContext(); context1.Variables.Add(new Variable("Variable") { Value = 1 }); var context2 = new ExpressionContext(); context2.Variables.Add(new Variable("Variable") { Value = 1d }); Assert.AreSame( dynamicExpression.Bind(context1), dynamicExpression.Bind(context2) ); }
public void TestGenericEvaluate() { ExpressionContext context = default(ExpressionContext); context = new ExpressionContext(); var e1 = new DynamicExpression<int>("1000", ExpressionLanguage.Flee); Assert.AreEqual(1000, e1.Invoke(context)); var e2 = new DynamicExpression<double>("1000.25", ExpressionLanguage.Flee); Assert.AreEqual(1000.25, e2.Invoke(context)); var e3 = new DynamicExpression<double>("1000", ExpressionLanguage.Flee); Assert.AreEqual(1000.0, e3.Invoke(context)); var e4 = new DynamicExpression<ValueType>("1000", ExpressionLanguage.Flee); ValueType vt = e4.Invoke(context); Assert.AreEqual(1000, vt); var e5 = new DynamicExpression<object>("1000 + 2.5", ExpressionLanguage.Flee); object o = e5.Invoke(context); Assert.AreEqual(1000 + 2.5, o); }
protected void Resolve(ExpressionContext expressionContext, string expression, IExpression expectedResult) { if (expression == null) throw new ArgumentNullException("expression"); var boundExpression = new DynamicExpression( expression, ExpressionLanguage.Flee ).Bind( expressionContext ?? new ExpressionContext() ); string expected = new ExpressionPrinter(expectedResult).ToString(); string actual = new ExpressionPrinter(((BoundExpression)boundExpression).ResolvedExpression).ToString(); // TODO: Implement equals. if (expected != actual) { Console.WriteLine(PrintSideToSide("Expected:\r\n" + expected, "Actual:\r\n" + actual)); Assert.AreEqual(expected, actual); } }
private void TestReferenceTypeVariables() { ExpressionContext context = new ExpressionContext(); VariableCollection variables = context.Variables; variables.Add("a", "string"); variables.Add("b", 100); var e = new DynamicExpression<string>("a + b + a.tostring()", ExpressionLanguage.Flee); string result = e.Invoke(context); Assert.AreEqual("string" + 100 + "string", result); variables["a"].Value = "test"; variables["b"].Value = 1; result = e.Invoke(context); Assert.AreEqual("test" + 1 + "test", result); // Test null value variables.Add("nullvar", null); var e2 = new DynamicExpression<bool>("nullvar = null", ExpressionLanguage.Flee); Assert.IsTrue(e2.Invoke(context)); }
public void TestStringNewlineEscape() { var e = new DynamicExpression<string>("\"a\\r\\nb\"", ExpressionLanguage.Flee); string s = e.Invoke(); string expected = string.Format("a{0}b", ControlChars.CrLf); Assert.AreEqual(expected, s); }
private void DoTestOverloadResolution(string expression, ExpressionContext context, int expectedResult) { try { var e = new DynamicExpression<int>(expression, ExpressionLanguage.Flee); int result = e.Invoke(context); Assert.AreEqual(expectedResult, result); } catch (Exception) { Assert.AreEqual(-1, expectedResult); } }
private void EmitComplexCall(ObjExpr objx, CljILGen ilg) { // TOD: We have gotten rid of light-compile. Simplify this. // This is made more complex than I'd like by light-compiling. // Without light-compile, we could just: // Emit the target expression // Emit the arguments (and build up the parameter list for the lambda) // Create the lambda, compile to a methodbuilder, and call it. // Light-compile forces us to // create a lambda at the beginning because we must // compile it to a delegate, to get the type // write code to grab the delegate from a cache // Then emit the target expression // emit the arguments (but note we need already to have built the parameter list) // Call the delegate // Combined, this becomes // Build the parameter list // Build the dynamic call and lambda (slightly different for light-compile vs full) // if light-compile // build the delegate // cache it // emit code to retrieve and cast it // emit the target expression // emit the args // emit the call (slightly different for light compile vs full) // // Build the parameter list List <ParameterExpression> paramExprs = new List <ParameterExpression>(_args.Count + 1); List <Type> paramTypes = new List <Type>(_args.Count + 1); Type targetType = GetTargetType(); if (!targetType.IsPrimitive) { targetType = typeof(object); } paramExprs.Add(Expression.Parameter(targetType)); paramTypes.Add(targetType); int i = 0; foreach (HostArg ha in _args) { i++; Expr e = ha.ArgExpr; Type argType = e.HasClrType && e.ClrType != null && e.ClrType.IsPrimitive ? e.ClrType : typeof(object); switch (ha.ParamType) { case HostArg.ParameterType.ByRef: { Type byRefType = argType.MakeByRefType(); paramExprs.Add(Expression.Parameter(byRefType, ha.LocalBinding.Name)); paramTypes.Add(byRefType); break; } case HostArg.ParameterType.Standard: if (argType.IsPrimitive && ha.ArgExpr is MaybePrimitiveExpr) { paramExprs.Add(Expression.Parameter(argType, ha.LocalBinding != null ? ha.LocalBinding.Name : "__temp_" + i)); paramTypes.Add(argType); } else { paramExprs.Add(Expression.Parameter(typeof(object), ha.LocalBinding != null ? ha.LocalBinding.Name : "__temp_" + i)); paramTypes.Add(typeof(object)); } break; default: throw Util.UnreachableCode(); } } // Build dynamic call and lambda Type returnType = HasClrType ? ClrType : typeof(object); InvokeMemberBinder binder = new ClojureInvokeMemberBinder(ClojureContext.Default, _methodName, paramExprs.Count, IsStaticCall); // This is what I want to do. //DynamicExpression dyn = Expression.Dynamic(binder, typeof(object), paramExprs); // Unfortunately, the Expression.Dynamic method does not respect byRef parameters. // The workaround appears to be to roll your delegate type and then use Expression.MakeDynamic, as below. List <Type> callsiteParamTypes = new List <Type>(paramTypes.Count + 1) { typeof(System.Runtime.CompilerServices.CallSite) }; callsiteParamTypes.AddRange(paramTypes); Type dynType = Microsoft.Scripting.Generation.Snippets.Shared.DefineDelegate("__interop__", returnType, callsiteParamTypes.ToArray()); DynamicExpression dyn = Expression.MakeDynamic(dynType, binder, paramExprs); EmitDynamicCallPreamble(dyn, _spanMap, "__interop_" + _methodName + RT.nextID(), returnType, paramExprs, paramTypes.ToArray(), ilg, out LambdaExpression lambda, out Type delType, out MethodBuilder mbLambda); // Emit target + args EmitTargetExpression(objx, ilg); i = 0; foreach (HostArg ha in _args) { i++; Expr e = ha.ArgExpr; Type argType = e.HasClrType && e.ClrType != null && e.ClrType.IsPrimitive ? e.ClrType : typeof(object); switch (ha.ParamType) { case HostArg.ParameterType.ByRef: EmitByRefArg(ha, objx, ilg); break; case HostArg.ParameterType.Standard: if (argType.IsPrimitive && ha.ArgExpr is MaybePrimitiveExpr mpe) { mpe.EmitUnboxed(RHC.Expression, objx, ilg); } else { ha.ArgExpr.Emit(RHC.Expression, objx, ilg); } break; default: throw Util.UnreachableCode(); } } EmitDynamicCallPostlude(lambda, delType, mbLambda, ilg); }
public void TestNonPublicImports() { // ...until we set an owner that is in the same module var context = new ExpressionContext(null, new OverloadTestExpressionOwner()); context.Imports.Add(new Import(typeof(TestImport))); var e = new DynamicExpression("DoStuff()", ExpressionLanguage.Flee); Assert.AreEqual(100, (int)e.Invoke(context)); }
protected override Expression VisitDynamic(DynamicExpression node) { throw new ExpressionParseException(0, $"Dynamic expressions are not allowed in binding expressions."); }
public void TestMemberAccess() { AccessTestExpressionOwner owner = new AccessTestExpressionOwner(); ExpressionContext context = new ExpressionContext(null, owner); // Private field, access should be denied this.AssertCompileException("privateField1", context); // Private field but with override allowing access var e = new DynamicExpression("privateField2", ExpressionLanguage.Flee); // Private field but with override denying access this.AssertCompileException("privateField3", context, new BoundExpressionOptions { AllowPrivateAccess = true }); // Public field, access should be denied this.AssertCompileException("PublicField1", context); // Public field, access should be allowed e = new DynamicExpression("publicField1", ExpressionLanguage.Flee); }
public virtual void Visit(DynamicExpression expression, TranslationContext context, bool negated = false) { }
protected internal override Expression VisitDynamic(DynamicExpression node) { Out(FormatBinder(node.Binder)); VisitExpressions('(', node.Arguments, ')'); return(node); }
internal MSAst.Expression TransformAndDynamicConvert(Expression expression, Type /*!*/ type) { Debug.Assert(expression != null); MSAst.Expression res = expression; // Do we need conversion? if (!CanAssign(type, expression.Type)) { // ensure we're reduced before we check for dynamic expressions. var reduced = expression.Reduce(); if (reduced is LightDynamicExpression) { reduced = reduced.Reduce(); } // Add conversion step to the AST MSAst.DynamicExpression ae = reduced as MSAst.DynamicExpression; ReducableDynamicExpression rde = reduced as ReducableDynamicExpression; if ((ae != null && ae.Binder is PythonBinaryOperationBinder) || (rde != null && rde.Binder is PythonBinaryOperationBinder)) { // create a combo site which does the conversion PythonBinaryOperationBinder binder; IList <MSAst.Expression> args; if (ae != null) { binder = (PythonBinaryOperationBinder)ae.Binder; args = ArrayUtils.ToArray(ae.Arguments); } else { binder = (PythonBinaryOperationBinder)rde.Binder; args = rde.Args; } ParameterMappingInfo[] infos = new ParameterMappingInfo[args.Count]; for (int i = 0; i < infos.Length; i++) { infos[i] = ParameterMappingInfo.Parameter(i); } res = DynamicExpression.Dynamic( GlobalParent.PyContext.BinaryOperationRetType( binder, GlobalParent.PyContext.Convert( type, ConversionResultKind.ExplicitCast ) ), type, args ); } else { res = GlobalParent.Convert( type, ConversionResultKind.ExplicitCast, reduced ); } } return(res); }
protected override Expression VisitDynamic(DynamicExpression node) => throw ExpressionNotSupported(node);
internal static void Deconstruct(this DynamicExpression expr, out ExpressionType nodeType, out Type type, out BinderTypes binderType) => (nodeType, type, binderType) = (
protected override Expression VisitDynamic(DynamicExpression node) { return(base.VisitDynamic(node)); }
private DynamicMetaObject /*!*/ MakeSetMember(SetMemberBinder /*!*/ member, DynamicMetaObject /*!*/ value) { PythonContext state = PythonContext.GetPythonContext(member); DynamicMetaObject self = Restrict(Value.GetType()); if (Value.GetType() != typeof(PythonType) && DynamicHelpers.GetPythonType(Value).IsSystemType) { // built-in subclass of .NET type. Usually __setattr__ is handled by MetaUserObject // but we can have a built-in subtype that's not a user type. PythonTypeSlot pts; if (Value.TryGetCustomSetAttr(state.SharedContext, out pts)) { Debug.Assert(pts.GetAlwaysSucceeds); ParameterExpression tmp = Ast.Variable(typeof(object), "boundVal"); return(BindingHelpers.AddDynamicTestAndDefer( member, new DynamicMetaObject( Ast.Block( new[] { tmp }, DynamicExpression.Dynamic( state.Invoke(new CallSignature(2)), typeof(object), AstUtils.Constant(state.SharedContext), Ast.Block( Ast.Call( typeof(PythonOps).GetMethod("SlotTryGetValue"), AstUtils.Constant(state.SharedContext), AstUtils.Convert(AstUtils.WeakConstant(pts), typeof(PythonTypeSlot)), AstUtils.Convert(Expression, typeof(object)), AstUtils.Convert(AstUtils.WeakConstant(DynamicHelpers.GetPythonType(Value)), typeof(PythonType)), tmp ), tmp ), Ast.Constant(member.Name), value.Expression ) ), self.Restrictions ), new DynamicMetaObject[] { this, value }, TestUserType() )); } } return(BindingHelpers.AddDynamicTestAndDefer( member, new DynamicMetaObject( Ast.Call( typeof(PythonOps).GetMethod("PythonTypeSetCustomMember"), AstUtils.Constant(PythonContext.GetPythonContext(member).SharedContext), self.Expression, AstUtils.Constant(member.Name), AstUtils.Convert( value.Expression, typeof(object) ) ), self.Restrictions.Merge(value.Restrictions) ), new DynamicMetaObject[] { this, value }, TestUserType() )); }
private void ThreadRunParse(object o) { ExpressionContext context = (ExpressionContext)o; // Test parse for (int i = 0; i <= 40 - 1; i++) { var e = new DynamicExpression("1+1*200", ExpressionLanguage.Flee); } }
public override T VisitDynamicExpression(DynamicExpression node) { throw new NotImplementedException(); }
internal static DynamicMetaObject Call(DynamicMetaObjectBinder /*!*/ call, DynamicMetaObject target, DynamicMetaObject /*!*/[] /*!*/ args) { Assert.NotNull(call, args); Assert.NotNullItems(args); if (target.NeedsDeferral()) { return(call.Defer(ArrayUtils.Insert(target, args))); } foreach (DynamicMetaObject mo in args) { if (mo.NeedsDeferral()) { RestrictTypes(args); return(call.Defer( ArrayUtils.Insert(target, args) )); } } DynamicMetaObject self = target.Restrict(target.GetLimitType()); ValidationInfo valInfo = BindingHelpers.GetValidationInfo(target); PythonType pt = DynamicHelpers.GetPythonType(target.Value); PythonContext pyContext = PythonContext.GetPythonContext(call); // look for __call__, if it's present dispatch to it. Otherwise fall back to the // default binder PythonTypeSlot callSlot; if (!typeof(Delegate).IsAssignableFrom(target.GetLimitType()) && pt.TryResolveSlot(pyContext.SharedContext, "__call__", out callSlot)) { ConditionalBuilder cb = new ConditionalBuilder(call); Expression body; callSlot.MakeGetExpression( pyContext.Binder, PythonContext.GetCodeContext(call), self, GetPythonType(self), cb ); if (!cb.IsFinal) { cb.FinishCondition(GetCallError(call, self)); } Expression[] callArgs = ArrayUtils.Insert( PythonContext.GetCodeContext(call), cb.GetMetaObject().Expression, DynamicUtils.GetExpressions(args) ); body = DynamicExpression.Dynamic( PythonContext.GetPythonContext(call).Invoke( BindingHelpers.GetCallSignature(call) ), typeof(object), callArgs ); body = Ast.TryFinally( Ast.Block( Ast.Call(typeof(PythonOps).GetMethod("FunctionPushFrame"), Ast.Constant(pyContext)), body ), Ast.Call(typeof(PythonOps).GetMethod("FunctionPopFrame")) ); return(BindingHelpers.AddDynamicTestAndDefer( call, new DynamicMetaObject(body, self.Restrictions.Merge(BindingRestrictions.Combine(args))), args, valInfo )); } return(null); }
protected override Expression VisitDynamic(DynamicExpression node) { throw new NotSupportedException(); }
protected override Expression VisitDynamic(DynamicExpression node) { return(Visit(Reduce(node))); }
private static string VisitDynamic(DynamicExpression node) { throw new NotImplementedException(); }
public void TestMultiTreadedEvaluate() { System.Threading.Thread t1 = new System.Threading.Thread(ThreadRunEvaluate); t1.Name = "Thread1"; System.Threading.Thread t2 = new System.Threading.Thread(ThreadRunEvaluate); t2.Name = "Thread2"; var e = new DynamicExpression("1+1*200", ExpressionLanguage.Flee); t1.Start(e); t2.Start(e); t1.Join(); t2.Join(); }
protected override Expression VisitDynamic(DynamicExpression node) { return(GiveUp(node)); }
public void TestNestedTypeImport() { ExpressionContext context = new ExpressionContext(); // Should be able to import public nested type context.Imports.Add(new Import(typeof(NestedA.NestedPublicB))); var e = new DynamicExpression("DoStuff()", ExpressionLanguage.Flee); Assert.AreEqual(100, (int)e.Invoke(context)); // Should be able to import nested internal type now context = new ExpressionContext(null, new OverloadTestExpressionOwner()); context.Imports.Add(new Import(typeof(NestedA.NestedInternalB))); e = new DynamicExpression("DoStuff()", ExpressionLanguage.Flee); Assert.AreEqual(100, (int)e.Invoke(context)); }
// Member is excluded in the base so it is automatically excluded for this type without any way to override that behavior protected virtual Expression VisitDynamic(DynamicExpression node) { return default(Expression); }
public void TestOnDemandVariables() { var e = new DynamicExpression("a + b", ExpressionLanguage.Flee); Assert.AreEqual(100 + 100, (int)e.Invoke(new TestExpressionContext())); }
public void TestOnDemandVariables() { var e = new DynamicExpression("a + b", ExpressionLanguage.Flee); Assert.Equal(100 + 100, (int)e.Invoke(new TestExpressionContext())); }
public void TestValueTypeOwner() { TestStruct owner = new TestStruct(100); ExpressionContext context = this.CreateGenericContext(owner); var options = new BoundExpressionOptions { AllowPrivateAccess = true }; var e = new DynamicExpression<int>("mya.compareto(100)", ExpressionLanguage.Flee); int result = e.Invoke(context, options); Assert.AreEqual(0, result); e = new DynamicExpression<int>("myA", ExpressionLanguage.Flee); result = e.Invoke(context, options); Assert.AreEqual(100, result); e = new DynamicExpression<int>("DoStuff()", ExpressionLanguage.Flee); result = e.Invoke(context); Assert.AreEqual(100, result); DateTime dt = DateTime.Now; context = this.CreateGenericContext(dt); e = new DynamicExpression<int>("Month", ExpressionLanguage.Flee); result = e.Invoke(context); Assert.AreEqual(dt.Month, result); var e2 = new DynamicExpression<string>("tolongdatestring()", ExpressionLanguage.Flee); Assert.AreEqual(dt.ToLongDateString(), e2.Invoke(context)); }
private static IQueryable ExpandQueryableOrderBy(IQueryable source, string[] statements) { var expression = source.Expression; var parameter = Expression.Parameter(source.ElementType, String.Empty); for (int idx = 0; idx < statements.Length; idx++) { bool isAscending = true; // Try LINQ ascending/descending suffix string memberReference = ParseStatement(statements[idx], out isAscending); bool isFirstOrderBy = (idx == 0); var methodName = (isFirstOrderBy ? "OrderBy" : "ThenBy") + (isAscending ? String.Empty : "Descending"); // Unravel nested property accesses var memberElements = memberReference.Split('.'); Expression memberExpression = parameter; foreach (string memberElement in memberElements) { if (string.IsNullOrEmpty(memberElement)) { throw new ArgumentException(Strings.EntityDataSourceView_EmptyPropertyName); } memberExpression = Expression.Property(memberExpression, memberElement.Trim()); } expression = Expression.Call(typeof(Queryable), methodName, new Type[] { source.ElementType, memberExpression.Type }, new Expression[] { expression, Expression.Quote(DynamicExpression.Lambda(memberExpression, parameter)) }); } return(source.Provider.CreateQuery(expression)); }
/// <summary> /// 动态Linq方式实现行转列 /// </summary> /// <param name="list">数据</param> /// <param name="DimensionList">维度列</param> /// <param name="DynamicColumn">动态列</param> /// <param name="AllNumberField">取值列</param> /// <returns>行转列后数据</returns> public static List <dynamic> DynamicLinq <T>(List <T> list, List <string> DimensionList, string DynamicColumn, List <string> AllNumberField, out List <string> AllDynamicColumn) where T : class { //获取所有动态列 var columnGroup = list.GroupBy(DynamicColumn, "new(it as Vm)") as IEnumerable <IGrouping <dynamic, dynamic> >; List <string> AllColumnList = new List <string>(); foreach (var item in columnGroup) { if (!string.IsNullOrEmpty(item.Key)) { AllColumnList.Add(item.Key); } } AllDynamicColumn = AllColumnList; var dictFunc = new Dictionary <string, Func <T, bool> >(); foreach (var column in AllColumnList) { var func = DynamicExpression.ParseLambda <T, bool>(string.Format("{0}==\"{1}\"", DynamicColumn, column)).Compile(); dictFunc[column] = func; } //获取实体所有属性 Dictionary <string, PropertyInfo> PropertyInfoDict = new Dictionary <string, PropertyInfo>(); Type type = typeof(T); var propertyInfos = type.GetProperties(BindingFlags.Instance | BindingFlags.Public); //数值列 //List<string> AllNumberField = new List<string>(); foreach (var item in propertyInfos) { PropertyInfoDict[item.Name] = item; } //分组 var dataGroup = list.GroupBy(string.Format("new ({0})", string.Join(",", DimensionList)), "new(it as Vm)") as IEnumerable <IGrouping <dynamic, dynamic> >; List <dynamic> listResult = new List <dynamic>(); IDictionary <string, object> itemObj = null; T vm2 = default(T); foreach (var group in dataGroup) { itemObj = new ExpandoObject(); var listVm = group.Select(e => e.Vm as T).ToList(); //维度列赋值 vm2 = listVm.FirstOrDefault(); foreach (var key in DimensionList) { itemObj[key] = PropertyInfoDict[key].GetValue(vm2); } foreach (var column in AllColumnList) { vm2 = listVm.FirstOrDefault(dictFunc[column]); if (vm2 != null) { foreach (string name in AllNumberField) { itemObj[column] = PropertyInfoDict[name].GetValue(vm2); } } } listResult.Add(itemObj); } return(listResult); }
protected override Expression VisitDynamic(DynamicExpression node) { onReturn(); return(node); }
private void TestValueTypeVariables() { ExpressionContext context = new ExpressionContext(); VariableCollection variables = context.Variables; variables.Add("a", 100); variables.Add("b", -100); variables.Add("c", DateTime.Now); var e1 = new DynamicExpression<int>("a+b", ExpressionLanguage.Flee); int result = e1.Invoke(context); Assert.AreEqual(100 + -100, result); variables["B"].Value = 1000; result = e1.Invoke(context); Assert.AreEqual(100 + 1000, result); var e2 = new DynamicExpression<string>("c.tolongdatestring() + c.Year.tostring()", ExpressionLanguage.Flee); Assert.AreEqual(DateTime.Now.ToLongDateString() + DateTime.Now.Year, e2.Invoke(context)); // Test null value //variables["a"].Value = null; //e1 = new DynamicExpression<int>("a", ExpressionLanguage.Flee); //Assert.AreEqual(0, e1.Invoke(context)); }
private DynamicMetaObject InvokeWorker(DynamicMetaObjectBinder /*!*/ callAction, DynamicMetaObject /*!*/[] args) { PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "Method Invoke " + args.Length); PerfTrack.NoteEvent(PerfTrack.Categories.BindingTarget, "Method"); CallSignature signature = BindingHelpers.GetCallSignature(callAction); DynamicMetaObject self = Restrict(typeof(Method)); BindingRestrictions restrictions = self.Restrictions; DynamicMetaObject func = GetMetaFunction(self); DynamicMetaObject call; if (Value.im_self == null) { // restrict to null self (Method is immutable so this is an invariant test) restrictions = restrictions.Merge( BindingRestrictions.GetExpressionRestriction( Ast.Equal( GetSelfExpression(self), AstUtils.Constant(null) ) ) ); if (args.Length == 0) { // this is an error, we pass null which will throw the normal error call = new DynamicMetaObject( Ast.Call( typeof(PythonOps).GetMethod(nameof(PythonOps.MethodCheckSelf)), PythonContext.GetCodeContext(callAction), self.Expression, AstUtils.Constant(null) ), restrictions ); } else { // this may or may not be an error call = new DynamicMetaObject( Ast.Block( MakeCheckSelf(callAction, signature, args), DynamicExpression.Dynamic( PythonContext.GetPythonContext(callAction).Invoke( BindingHelpers.GetCallSignature(callAction) ).GetLightExceptionBinder(callAction.SupportsLightThrow()), typeof(object), ArrayUtils.Insert(PythonContext.GetCodeContext(callAction), DynamicUtils.GetExpressions(ArrayUtils.Insert(func, args))) ) ), BindingRestrictions.Empty ); /*call = func.Invoke(callAction, ArrayUtils.Insert(func, args)); * call = new MetaObject( * Ast.Comma( * Ast.Call( * typeof(PythonOps).GetMethod("MethodCheckSelf"), * self.Expression, * args[0].Expression * ), * call.Expression * ), * call.Restrictions * );*/ } } else { // restrict to non-null self (Method is immutable so this is an invariant test) restrictions = restrictions.Merge( BindingRestrictions.GetExpressionRestriction( Ast.NotEqual( GetSelfExpression(self), AstUtils.Constant(null) ) ) ); DynamicMetaObject im_self = GetMetaSelf(self); DynamicMetaObject[] newArgs = ArrayUtils.Insert(func, im_self, args); CallSignature newSig = new CallSignature(ArrayUtils.Insert(new Argument(ArgumentType.Simple), signature.GetArgumentInfos())); call = new DynamicMetaObject( DynamicExpression.Dynamic( PythonContext.GetPythonContext(callAction).Invoke( newSig ).GetLightExceptionBinder(callAction.SupportsLightThrow()), typeof(object), ArrayUtils.Insert(PythonContext.GetCodeContext(callAction), DynamicUtils.GetExpressions(newArgs)) ), BindingRestrictions.Empty ); /* * call = func.Invoke( * new CallBinder( * PythonContext.GetBinderState(callAction), * newSig * ), * newArgs * );*/ } if (call.HasValue) { return(new DynamicMetaObject( call.Expression, restrictions.Merge(call.Restrictions), call.Value )); } else { return(new DynamicMetaObject( call.Expression, restrictions.Merge(call.Restrictions) )); } }
private static void CalcHashCodeDynamic(DynamicExpression node, Context context) { throw new NotSupportedException(); }
public void TestLongBranchLogical1() { string expressionText = this.GetIndividualTest("LongBranch1"); ExpressionContext context = new ExpressionContext(); VariableCollection vc = context.Variables; vc.Add("M0100_ASSMT_REASON", "0"); vc.Add("M0220_PRIOR_NOCHG_14D", "1"); vc.Add("M0220_PRIOR_UNKNOWN", "1"); vc.Add("M0220_PRIOR_UR_INCON", "1"); vc.Add("M0220_PRIOR_CATH", "1"); vc.Add("M0220_PRIOR_INTRACT_PAIN", "1"); vc.Add("M0220_PRIOR_IMPR_DECSN", "1"); vc.Add("M0220_PRIOR_DISRUPTIVE", "1"); vc.Add("M0220_PRIOR_MEM_LOSS", "1"); vc.Add("M0220_PRIOR_NONE", "1"); vc.Add("M0220_PRIOR_UR_INCON_bool", true); vc.Add("M0220_PRIOR_CATH_bool", true); vc.Add("M0220_PRIOR_INTRACT_PAIN_bool", true); vc.Add("M0220_PRIOR_IMPR_DECSN_bool", true); vc.Add("M0220_PRIOR_DISRUPTIVE_bool", true); vc.Add("M0220_PRIOR_MEM_LOSS_bool", true); vc.Add("M0220_PRIOR_NONE_bool", true); vc.Add("M0220_PRIOR_NOCHG_14D_bool", true); vc.Add("M0220_PRIOR_UNKNOWN_bool", true); var e = new DynamicExpression(expressionText, ExpressionLanguage.Flee); // We only care that the expression is valid and can be evaluated object result = e.Invoke(context); }
public static Type GetExpressionResultType(Type type, string propertyOrExpression) { LambdaExpression lambda = DynamicExpression.ParseLambda(type, null, propertyOrExpression, null); return(lambda.Body.Type); }
public void TestLongBranchLogical2() { string expressionText = this.GetIndividualTest("LongBranch2"); ExpressionContext context = new ExpressionContext(); var e = new DynamicExpression<bool>(expressionText, ExpressionLanguage.Flee); Assert.IsFalse(e.Invoke(context)); }
public DynamicExpressionProxy(DynamicExpression node) { _node = node; }
private void EmitComplexCall(RHC rhc, ObjExpr objx, CljILGen ilg) { // See the notes on MethodExpr.EmitComplexCall on why this is so complicated List <ParameterExpression> paramExprs = new List <ParameterExpression>(_args.Count + 1); List <Type> paramTypes = new List <Type>(_args.Count + 1); paramExprs.Add(Expression.Parameter(typeof(Type))); paramTypes.Add(typeof(Type)); int i = 0; foreach (HostArg ha in _args) { i++; Expr e = ha.ArgExpr; Type argType = e.HasClrType && e.ClrType != null && e.ClrType.IsPrimitive ? e.ClrType : typeof(object); switch (ha.ParamType) { case HostArg.ParameterType.ByRef: { Type byRefType = argType.MakeByRefType(); paramExprs.Add(Expression.Parameter(byRefType, ha.LocalBinding.Name)); paramTypes.Add(byRefType); break; } case HostArg.ParameterType.Standard: if (argType.IsPrimitive && ha.ArgExpr is MaybePrimitiveExpr) { paramExprs.Add(Expression.Parameter(argType, ha.LocalBinding != null ? ha.LocalBinding.Name : "__temp_" + i)); paramTypes.Add(argType); } else { paramExprs.Add(Expression.Parameter(typeof(object), ha.LocalBinding != null ? ha.LocalBinding.Name : "__temp_" + i)); paramTypes.Add(typeof(object)); } break; default: throw Util.UnreachableCode(); } } // Build dynamic call and lambda Type returnType = HasClrType ? ClrType : typeof(object); CreateInstanceBinder binder = new ClojureCreateInstanceBinder(ClojureContext.Default, _args.Count); #if CLR2 // Not covariant. Sigh. List <Expression> paramsAsExprs = new List <Expression>(paramExprs.Count); paramsAsExprs.AddRange(paramExprs.ToArray()); DynamicExpression dyn = Expression.Dynamic(binder, typeof(object), paramsAsExprs); #else DynamicExpression dyn = Expression.Dynamic(binder, typeof(object), paramExprs); #endif LambdaExpression lambda; Type delType; MethodBuilder mbLambda; MethodExpr.EmitDynamicCallPreamble(dyn, _spanMap, "__interop_ctor_" + RT.nextID(), returnType, paramExprs, paramTypes.ToArray(), ilg, out lambda, out delType, out mbLambda); // Emit target + args EmitTargetExpression(objx, ilg); i = 0; foreach (HostArg ha in _args) { i++; Expr e = ha.ArgExpr; Type argType = e.HasClrType && e.ClrType != null && e.ClrType.IsPrimitive ? e.ClrType : typeof(object); switch (ha.ParamType) { case HostArg.ParameterType.ByRef: MethodExpr.EmitByRefArg(ha, objx, ilg); break; case HostArg.ParameterType.Standard: if (argType.IsPrimitive && ha.ArgExpr is MaybePrimitiveExpr) { ((MaybePrimitiveExpr)ha.ArgExpr).EmitUnboxed(RHC.Expression, objx, ilg); } else { ha.ArgExpr.Emit(RHC.Expression, objx, ilg); } break; default: throw Util.UnreachableCode(); } } MethodExpr.EmitDynamicCallPostlude(lambda, delType, mbLambda, ilg); }
public void ValidSyntaxCheck() { DynamicExpression.CheckSyntax( "1", ExpressionLanguage.Flee ); }
static public void EmitDynamicCallPreamble(DynamicExpression dyn, IPersistentMap spanMap, string methodName, Type returnType, IList <ParameterExpression> paramExprs, Type[] paramTypes, CljILGen ilg, out LambdaExpression lambda, out Type delType, out MethodBuilder mbLambda) { GenContext context = Compiler.CompilerContextVar.deref() as GenContext; DynInitHelper.SiteInfo siteInfo; Expression call; if (context != null && context.DynInitHelper != null) { call = context.DynInitHelper.ReduceDyn(dyn, out siteInfo); } else { throw new InvalidOperationException("Don't know how to handle callsite in this case"); } if (returnType == typeof(void)) { call = Expression.Block(call, Expression.Default(typeof(object))); returnType = typeof(object); } else if (returnType != call.Type) { call = Expression.Convert(call, returnType); } call = GenContext.AddDebugInfo(call, spanMap); delType = Microsoft.Scripting.Generation.Snippets.Shared.DefineDelegate("__interop__", returnType, paramTypes); lambda = Expression.Lambda(delType, call, paramExprs); mbLambda = null; if (context == null) { // light compile Delegate d = lambda.Compile(); int key = RT.nextID(); CacheDelegate(key, d); ilg.EmitInt(key); ilg.Emit(OpCodes.Call, Method_MethodExpr_GetDelegate); ilg.Emit(OpCodes.Castclass, delType); } else { mbLambda = context.TB.DefineMethod(methodName, MethodAttributes.Static | MethodAttributes.Public, CallingConventions.Standard, returnType, paramTypes); //lambda.CompileToMethod(mbLambda); // Now we get to do all this code create by hand. // the primary code is // (loc1 = fb).Target.Invoke(loc1,*args); // if return type if void, pop the value and push a null // if return type does not match the call site, add a conversion CljILGen ilg2 = new CljILGen(mbLambda.GetILGenerator()); ilg2.EmitFieldGet(siteInfo.FieldBuilder); ilg2.Emit(OpCodes.Dup); LocalBuilder siteVar = ilg2.DeclareLocal(siteInfo.SiteType); ilg2.Emit(OpCodes.Stloc, siteVar); ilg2.EmitFieldGet(siteInfo.SiteType.GetField("Target")); ilg2.Emit(OpCodes.Ldloc, siteVar); for (int i = 0; i < paramExprs.Count; i++) { ilg2.EmitLoadArg(i); } var invokeMethod = siteInfo.DelegateType.GetMethod("Invoke"); ilg2.EmitCall(invokeMethod); if (returnType == typeof(void)) { ilg2.Emit(OpCodes.Pop); ilg2.EmitNull(); } else if (returnType != invokeMethod.ReturnType) { EmitConvertToType(ilg2, invokeMethod.ReturnType, returnType, false); } ilg2.Emit(OpCodes.Ret); /* * return Expression.Block( * new[] { site }, * Expression.Call( * Expression.Field( * Expression.Assign(site, access), * cs.GetType().GetField("Target") * ), * node.DelegateType.GetMethod("Invoke"), * ClrExtensions.ArrayInsert(site, node.Arguments) * ) */ } }
private WatchItem Debugger_RefreshWatch(ScriptExecutionContext context, DynamicExpression dynExpr) { try { SymbolRef L = dynExpr.FindSymbol(context); DynValue v = dynExpr.Evaluate(context); return new WatchItem() { IsError = dynExpr.IsConstant(), LValue = L, Value = v, Name = dynExpr.ExpressionCode }; } catch (Exception ex) { return new WatchItem() { IsError = true, Value = DynValue.NewString(ex.Message), Name = dynExpr.ExpressionCode }; } }
private DynamicMetaObject /*!*/ InvokeWorker(DynamicMetaObjectBinder /*!*/ invoke, Expression /*!*/ codeContext, DynamicMetaObject /*!*/[] args) { PerfTrack.NoteEvent(PerfTrack.Categories.Binding, "OldClass Invoke"); DynamicMetaObject self = Restrict(typeof(OldInstance)); Expression[] exprArgs = new Expression[args.Length + 1]; for (int i = 0; i < args.Length; i++) { exprArgs[i + 1] = args[i].Expression; } ParameterExpression tmp = Ast.Variable(typeof(object), "callFunc"); exprArgs[0] = tmp; return(new DynamicMetaObject( // we could get better throughput w/ a more specific rule against our current custom old class but // this favors less code generation. Ast.Block( new ParameterExpression[] { tmp }, Ast.Condition( Expression.Not( Expression.TypeIs( Expression.Assign( tmp, Ast.Call( typeof(PythonOps).GetMethod("OldInstanceTryGetBoundCustomMember"), codeContext, self.Expression, AstUtils.Constant("__call__") ) ), typeof(OperationFailed) ) ), Ast.Block( Utils.Try( Ast.Call(typeof(PythonOps).GetMethod("FunctionPushFrameCodeContext"), codeContext), Ast.Assign( tmp, DynamicExpression.Dynamic( PythonContext.GetPythonContext(invoke).Invoke( BindingHelpers.GetCallSignature(invoke) ), typeof(object), ArrayUtils.Insert(codeContext, exprArgs) ) ) ).Finally( Ast.Call(typeof(PythonOps).GetMethod("FunctionPopFrame")) ), tmp ), Utils.Convert( BindingHelpers.InvokeFallback(invoke, codeContext, this, args).Expression, typeof(object) ) ) ), self.Restrictions.Merge(BindingRestrictions.Combine(args)) )); }
protected void DoTest(DynamicExpression expression, ExpressionContext expressionContext, string result, Type resultType, CultureInfo testCulture) { if (ReferenceEquals(resultType, typeof(object))) { Type expectedType = Type.GetType(result, false, true); if (expectedType == null) { // Try to get the type from the Tests assembly result = string.Format("{0}.{1}", typeof(ExpressionTests).Namespace, result); expectedType = this.GetType().Assembly.GetType(result, true, true); } object expressionResult = expression.Invoke(expressionContext, new BoundExpressionOptions { AllowPrivateAccess = true, ResultType = resultType }); if (object.ReferenceEquals(expectedType, typeof(void))) { Assert.IsNull(expressionResult); } else { Assert.That(expressionResult, Is.InstanceOf(expectedType)); } } else { TypeConverter tc = TypeDescriptor.GetConverter(resultType); object expectedResult = tc.ConvertFromString(null, CultureInfo.CurrentCulture, result); object actualResult = expression.Invoke(expressionContext, new BoundExpressionOptions { AllowPrivateAccess = true, ResultType = resultType }); expectedResult = RoundIfReal(expectedResult); actualResult = RoundIfReal(actualResult); Assert.AreEqual(expectedResult, actualResult); } }
protected override Expression VisitDynamic(DynamicExpression node) { return(Rewrite(node, node.Arguments, node.Update)); }