private void CreateFunctionInfo(MSAst.LambdaExpression generatorFactoryLambda) { if (_lambdaInfo.CompilerSupport != null && _lambdaInfo.CompilerSupport.DoesExpressionNeedReduction(generatorFactoryLambda)) { _functionInfo = _lambdaInfo.CompilerSupport.QueueExpressionForReduction( Ast.Call( typeof(RuntimeOps).GetMethod("CreateFunctionInfo"), generatorFactoryLambda, AstUtils.Constant(_alias), AstUtils.Constant(_debugMarkerLocationMap, typeof(object)), AstUtils.Constant(_variableScopeMap, typeof(object)), AstUtils.Constant(_variableInfos, typeof(object)), Ast.Constant(_lambdaInfo.CustomPayload, typeof(object)) ) ); } else { _functionInfo = Ast.Constant( DebugContext.CreateFunctionInfo( generatorFactoryLambda.Compile(), _alias, _debugMarkerLocationMap, _variableScopeMap, _variableInfos, _lambdaInfo.CustomPayload), typeof(FunctionInfo)); } }
public Lambda(LambdaExpression lambdaExpression) { if (lambdaExpression == null) throw new ArgumentNullException("lambdaExpression"); _lambdaExpression = lambdaExpression; _delegate = _lambdaExpression.Compile(); }
public ObjectOutputParameterExpression(LambdaExpression lambda, Type valueType, string alias) : base(ExpressionType, lambda.Type) { if (lambda.Parameters.Count != 2) throw Error.BadArgument("S0055: Lambda must have 2 arguments"); setValueDelegate = lambda.Compile(); Alias = alias; ValueType = valueType; }
public static Object CalculateLabda(LambdaExpression lambda, Object[] lambdaParams) { var compiledLambda = lambda.Compile(); var invokeMethod = compiledLambda.GetType().GetMethod("Invoke"); if (invokeMethod != null) return invokeMethod.Invoke(compiledLambda, lambdaParams); else throw new Exception(); }
public ResultTransformer(LambdaExpression itemTransformation, LambdaExpression listTransformation) { if (itemTransformation != null) { _itemTransformation = itemTransformation.Compile(); } if (listTransformation != null) { _listTransformation = listTransformation.Compile(); } }
public static object DoCalculateLambda(LambdaExpression lambda, IDictionary<string, object> paramNameToValue) { IEnumerable<object> requiredParamValues; if (lambda.Parameters.Count == paramNameToValue.Count) requiredParamValues = paramNameToValue.Values; else requiredParamValues = from requiredParam in lambda.Parameters join allParam in paramNameToValue on requiredParam.Name equals allParam.Key select allParam.Value; return lambda.Compile().DynamicInvoke(requiredParamValues.ToArray()); }
private static void CheckInputCorrectness(LambdaExpression lambda, params object[] lambdaParams) { try { lambda.Compile(); } catch (Exception originalException) { var message = string.Format("Lambda '{0}' is not compilable", lambda); throw new InvalidLambdaException(lambda,message,originalException); } TypeUtils.CheckParamValuesAreSuitableToLambda(lambda, lambdaParams); }
public static object Evaluate(LambdaExpression expression, object target) { if (target == null) return null; Delegate func = expression.Compile(); object result = null; try { result = func.DynamicInvoke(target); } catch (Exception) { ; } return result; }
public static void EmitDynamicCallPreamble(DynamicExpression dyn, IPersistentMap spanMap, string methodName, Type returnType, List<ParameterExpression> paramExprs, Type[] paramTypes, CljILGen ilg, out LambdaExpression lambda, out Type delType, out MethodBuilder mbLambda) { Expression call = dyn; GenContext context = Compiler.CompilerContextVar.deref() as GenContext; if (context != null && context.DynInitHelper != null) call = context.DynInitHelper.ReduceDyn(dyn); 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); } }
public Delegate Compile(LambdaExpression expression) { return expression.Compile(); }
public object Run(LambdaExpression lambda, params object[] inline_parameter_values) { Delegate f = lambda.Compile(); if (inline_parameter_values != null && inline_parameter_values.Length > 0) return f.DynamicInvoke(inline_parameter_values); List<object> parameterList = new List<object>(); if (lambda.Parameters != null && lambda.Parameters.Count > 0) { foreach (ParameterExpression pe in lambda.Parameters) { if (this.ParameterValue.ContainsKey(pe.Name)) parameterList.Add(this.ParameterValue[pe.Name]); else if (GlobalParameterValue.ContainsKey(pe.Name)) parameterList.Add(GlobalParameterValue[pe.Name]); else throw new ExprException(string.Format("The value for {0} is undefined.", pe.Name)); } } return f.DynamicInvoke(parameterList.ToArray()); }
public DecodedExpression(LambdaExpression expression) { _expression = expression; _delegate = _expression.Compile(); }
private Delegate CompilePropertyInjectorLambda(LambdaExpression expression) { Delegate compiledDelegate = null; this.TryCompileLambdaInDynamicAssembly(expression, ref compiledDelegate); return compiledDelegate ?? expression.Compile(); }
internal static Delegate/*!*/ CompileLambda(LambdaExpression/*!*/ lambda, bool debugMode, bool noAdaptiveCompilation) { if (debugMode) { #if !SILVERLIGHT // try to use PDBs and fallback to CustomGenerator if not allowed to: if (_HasPdbPermissions) { try { return CompilerHelpers.CompileToMethod(lambda, DebugInfoGenerator.CreatePdbGenerator(), true); } catch (SecurityException) { // do not attempt next time in this app-domain: _HasPdbPermissions = false; } } #endif return CompilerHelpers.CompileToMethod(lambda, new CustomGenerator(), false); } else if (noAdaptiveCompilation) { Delegate result = lambda.Compile(); // DLR closures should not be used: Debug.Assert(!(result.Target is Closure) || ((Closure)result.Target).Locals == null); return result; } else { return lambda.LightCompile(false); } }
public object InvokeBase(LambdaExpression expression, MethodInfo method, object mockObject) { var bi = new BaseInvocation { Method = method, BaseInvocationResult = null }; System.Diagnostics.Debug.WriteLine("Original Expression: " + expression); //refactor method call to call into our intercepting invoker var call = (MethodCallExpression)expression.Body; var interceptMethod = this.GetType().GetMethod("InvokeBaseIntercept", BindingFlags.NonPublic | BindingFlags.Instance); expression = Expression.Lambda( Expression.Call( Expression.Constant(this), interceptMethod, Expression.Constant(bi), Expression.Constant(call.Method), Expression.Constant(mockObject), Expression.NewArrayInit(typeof(object), call.Arguments.Select(arg => arg.CastTo<object>()).ToArray()) ), expression.Parameters ); System.Diagnostics.Debug.WriteLine("Rewritten Expression: " + expression); //do the invocation (could result in recursive invocations expression.Compile().InvokePreserveStack(mockObject); return bi.BaseInvocationResult.ReturnValue; }
private Delegate CompileLambda(LambdaExpression code, EventHandler<LightLambdaCompileEventArgs> handler) { #if EMIT_PDB if (_lambda.EmitDebugSymbols) { return CompilerHelpers.CompileToMethod(code, DebugInfoGenerator.CreatePdbGenerator(), true); } #endif if (_lambda.ShouldInterpret) { Delegate result = CompilerHelpers.LightCompile(code, _lambda.GlobalParent.PyContext.Options.CompilationThreshold); // If the adaptive compiler decides to compile this function, we // want to store the new compiled target. This saves us from going // through the interpreter stub every call. var lightLambda = result.Target as LightLambda; if (lightLambda != null) { lightLambda.Compile += handler; } return result; } return code.Compile(); }
// The resulting lambda processes N samples, using buffers provided for Input and Output: // void Process(int N, double t0, double T, double[] Input0 ..., double[] Output0 ...) // { ... } private Delegate DefineProcess() { // Map expressions to identifiers in the syntax tree. List <KeyValuePair <Expression, LinqExpr> > inputs = new List <KeyValuePair <Expression, LinqExpr> >(); List <KeyValuePair <Expression, LinqExpr> > outputs = new List <KeyValuePair <Expression, LinqExpr> >(); // Lambda code generator. CodeGen code = new CodeGen(); // Create parameters for the basic simulation info (N, t, Iterations). ParamExpr SampleCount = code.Decl <int>(Scope.Parameter, "SampleCount"); ParamExpr t = code.Decl(Scope.Parameter, Simulation.t); // Create buffer parameters for each input... foreach (Expression i in Input) { inputs.Add(new KeyValuePair <Expression, LinqExpr>(i, code.Decl <double[]>(Scope.Parameter, i.ToString()))); } // ... and output. foreach (Expression i in Output) { outputs.Add(new KeyValuePair <Expression, LinqExpr>(i, code.Decl <double[]>(Scope.Parameter, i.ToString()))); } // Create globals to store previous values of inputs. foreach (Expression i in Input.Distinct()) { AddGlobal(i.Evaluate(t_t0)); } // Define lambda body. // int Zero = 0 LinqExpr Zero = LinqExpr.Constant(0); // double h = T / Oversample LinqExpr h = LinqExpr.Constant(TimeStep / (double)Oversample); // Load the globals to local variables and add them to the map. foreach (KeyValuePair <Expression, GlobalExpr <double> > i in globals) { code.Add(LinqExpr.Assign(code.Decl(i.Key), i.Value)); } foreach (KeyValuePair <Expression, LinqExpr> i in inputs) { code.Add(LinqExpr.Assign(code.Decl(i.Key), code[i.Key.Evaluate(t_t0)])); } // Create arrays for linear systems. int M = Solution.Solutions.OfType <NewtonIteration>().Max(i => i.Equations.Count(), 0); int N = Solution.Solutions.OfType <NewtonIteration>().Max(i => i.UnknownDeltas.Count(), 0) + 1; LinqExpr JxF = code.DeclInit <double[][]>("JxF", LinqExpr.NewArrayBounds(typeof(double[]), LinqExpr.Constant(M))); for (int j = 0; j < M; ++j) { code.Add(LinqExpr.Assign(LinqExpr.ArrayAccess(JxF, LinqExpr.Constant(j)), LinqExpr.NewArrayBounds(typeof(double), LinqExpr.Constant(N)))); } // for (int n = 0; n < SampleCount; ++n) ParamExpr n = code.Decl <int>("n"); code.For( () => code.Add(LinqExpr.Assign(n, Zero)), LinqExpr.LessThan(n, SampleCount), () => code.Add(LinqExpr.PreIncrementAssign(n)), () => { // Prepare input samples for oversampling interpolation. Dictionary <Expression, LinqExpr> dVi = new Dictionary <Expression, LinqExpr>(); foreach (Expression i in Input.Distinct()) { LinqExpr Va = code[i]; // Sum all inputs with this key. IEnumerable <LinqExpr> Vbs = inputs.Where(j => j.Key.Equals(i)).Select(j => j.Value); LinqExpr Vb = LinqExpr.ArrayAccess(Vbs.First(), n); foreach (LinqExpr j in Vbs.Skip(1)) { Vb = LinqExpr.Add(Vb, LinqExpr.ArrayAccess(j, n)); } // dVi = (Vb - Va) / Oversample code.Add(LinqExpr.Assign( Decl <double>(code, dVi, i, "d" + i.ToString().Replace("[t]", "")), LinqExpr.Multiply(LinqExpr.Subtract(Vb, Va), LinqExpr.Constant(1.0 / (double)Oversample)))); } // Prepare output sample accumulators for low pass filtering. Dictionary <Expression, LinqExpr> Vo = new Dictionary <Expression, LinqExpr>(); foreach (Expression i in Output.Distinct()) { code.Add(LinqExpr.Assign( Decl <double>(code, Vo, i, i.ToString().Replace("[t]", "")), LinqExpr.Constant(0.0))); } // int ov = Oversample; // do { -- ov; } while(ov > 0) ParamExpr ov = code.Decl <int>("ov"); code.Add(LinqExpr.Assign(ov, LinqExpr.Constant(Oversample))); code.DoWhile(() => { // t += h code.Add(LinqExpr.AddAssign(t, h)); // Interpolate the input samples. foreach (Expression i in Input.Distinct()) { code.Add(LinqExpr.AddAssign(code[i], dVi[i])); } // Compile all of the SolutionSets in the solution. foreach (SolutionSet ss in Solution.Solutions) { if (ss is LinearSolutions) { // Linear solutions are easy. LinearSolutions S = (LinearSolutions)ss; foreach (Arrow i in S.Solutions) { code.DeclInit(i.Left, i.Right); } } else if (ss is NewtonIteration) { NewtonIteration S = (NewtonIteration)ss; // Start with the initial guesses from the solution. foreach (Arrow i in S.Guesses) { code.DeclInit(i.Left, i.Right); } // int it = iterations LinqExpr it = code.ReDeclInit <int>("it", Iterations); // do { ... --it } while(it > 0) code.DoWhile((Break) => { // Solve the un-solved system. Solve(code, JxF, S.Equations, S.UnknownDeltas); // Compile the pre-solved solutions. if (S.KnownDeltas != null) { foreach (Arrow i in S.KnownDeltas) { code.DeclInit(i.Left, i.Right); } } // bool done = true LinqExpr done = code.ReDeclInit("done", true); foreach (Expression i in S.Unknowns) { LinqExpr v = code[i]; LinqExpr dv = code[NewtonIteration.Delta(i)]; // done &= (|dv| < |v|*epsilon) code.Add(LinqExpr.AndAssign(done, LinqExpr.LessThan(LinqExpr.Multiply(Abs(dv), LinqExpr.Constant(1e4)), LinqExpr.Add(Abs(v), LinqExpr.Constant(1e-6))))); // v += dv code.Add(LinqExpr.AddAssign(v, dv)); } // if (done) break code.Add(LinqExpr.IfThen(done, Break)); // --it; code.Add(LinqExpr.PreDecrementAssign(it)); }, LinqExpr.GreaterThan(it, Zero)); //// bool failed = false //LinqExpr failed = Decl(code, code, "failed", LinqExpr.Constant(false)); //for (int i = 0; i < eqs.Length; ++i) // // failed |= |JxFi| > epsilon // code.Add(LinqExpr.OrAssign(failed, LinqExpr.GreaterThan(Abs(eqs[i].ToExpression().Compile(map)), LinqExpr.Constant(1e-3)))); //code.Add(LinqExpr.IfThen(failed, ThrowSimulationDiverged(n))); } } // Update the previous timestep variables. foreach (SolutionSet S in Solution.Solutions) { foreach (Expression i in S.Unknowns.Where(i => globals.Keys.Contains(i.Evaluate(t_t0)))) { code.Add(LinqExpr.Assign(code[i.Evaluate(t_t0)], code[i])); } } // Vo += i foreach (Expression i in Output.Distinct()) { LinqExpr Voi = LinqExpr.Constant(0.0); try { Voi = code.Compile(i); } catch (Exception Ex) { Log.WriteLine(MessageType.Warning, Ex.Message); } code.Add(LinqExpr.AddAssign(Vo[i], Voi)); } // Vi_t0 = Vi foreach (Expression i in Input.Distinct()) { code.Add(LinqExpr.Assign(code[i.Evaluate(t_t0)], code[i])); } // --ov; code.Add(LinqExpr.PreDecrementAssign(ov)); }, LinqExpr.GreaterThan(ov, Zero)); // Output[i][n] = Vo / Oversample foreach (KeyValuePair <Expression, LinqExpr> i in outputs) { code.Add(LinqExpr.Assign(LinqExpr.ArrayAccess(i.Value, n), LinqExpr.Multiply(Vo[i.Key], LinqExpr.Constant(1.0 / (double)Oversample)))); } // Every 256 samples, check for divergence. if (Vo.Any()) { code.Add(LinqExpr.IfThen(LinqExpr.Equal(LinqExpr.And(n, LinqExpr.Constant(0xFF)), Zero), LinqExpr.Block(Vo.Select(i => LinqExpr.IfThenElse(IsNotReal(i.Value), ThrowSimulationDiverged(n), LinqExpr.Assign(i.Value, RoundDenormToZero(i.Value))))))); } }); // Copy the global state variables back to the globals. foreach (KeyValuePair <Expression, GlobalExpr <double> > i in globals) { code.Add(LinqExpr.Assign(i.Value, code[i.Key])); } LinqExprs.LambdaExpression lambda = code.Build(); Delegate ret = lambda.Compile(); return(ret); }
internal static Delegate/*!*/ CompileLambda(LambdaExpression/*!*/ lambda, bool debugMode, bool noAdaptiveCompilation) { if (debugMode) { #if !SILVERLIGHT // try to use PDBs and fallback to CustomGenerator if not allowed to: if (_HasPdbPermissions) { try { return CompilerHelpers.CompileToMethod(lambda, DebugInfoGenerator.CreatePdbGenerator(), true); } catch (SecurityException) { // do not attempt next time in this app-domain: _HasPdbPermissions = false; } } #endif return CompilerHelpers.CompileToMethod(lambda, new CustomGenerator(), false); } else if (noAdaptiveCompilation) { return lambda.Compile(); } else { return lambda.LightCompile(); } }
public override void DefineFunc(object ID, System.Linq.Expressions.LambdaExpression Corpse) { Functions[ScopeFunctions[(int)ID].Name] = Corpse.Compile(); }
public static NestedItem[] QueryNestedItems(LambdaExpression q) { return new Store().QueryNestedItems((Func<NestedItem, bool>)q.Compile()).ToArray(); }
private Delegate CompileLambda(LambdaExpression code, EventHandler<LightLambdaCompileEventArgs> handler) { if (_debuggable) { return CompilerHelpers.CompileToMethod(code, DebugInfoGenerator.CreatePdbGenerator(), true); } else if (_shouldInterpret) { Delegate result = CompilerHelpers.LightCompile(code); // If the adaptive compiler decides to compile this function, we // want to store the new compiled target. This saves us from going // through the interpreter stub every call. var lightLambda = result.Target as Microsoft.Scripting.Interpreter.LightLambda; if (lightLambda != null) { lightLambda.Compile += handler; } return result; } return code.Compile(); }
protected override void VisitLambda (LambdaExpression lambda) { Push (lambda.Compile ()); }
private void Parse(LambdaExpression expression) { Value = expression.Compile().DynamicInvoke(); Type valueType = Value.GetType(); if (valueType.IsEntity()) { Value = Engine.GetTable(valueType) .FindField(Field.BindedTo ?? Field.FieldName).GetValue(Value); } }
private Delegate CompileExpression(Type sourceType, Type destinationType, LambdaExpression expression) { if (this.options.Debug.DebugInformationEnabled) { this.DebugInformation = new DebugInformation { MappingExpression = expression }; } if (this.options.Compilation.CompileToDynamicAssembly && !mapProcessor.NonPublicMembersAccessed) { var typeBuilder = DefineMappingType(string.Format("From_{0}_to_{1}_{2}", sourceType.Name, destinationType.Name, Guid.NewGuid().ToString("N"))); var methodBuilder = typeBuilder.DefineMethod("Map", MethodAttributes.Public | MethodAttributes.Static); expression.CompileToMethod(methodBuilder); var resultingType = typeBuilder.CreateType(); var function = Delegate.CreateDelegate(expression.Type, resultingType.GetMethod("Map")); return function; } else { // Much simpler, but the resulting delegate incurs an invocation overhead from experience return expression.Compile(); } }
EvaluationResult Lambda(LambdaExpression expression) { if(expression == context && expression.Parameters.Count == 0) return Evaluate(expression.Body); return Success(expression.Type, expression.Compile()); }
private Delegate CompileLambda(LambdaExpression code, EventHandler<LightLambdaCompileEventArgs> handler) { if (_lambda.ShouldInterpret) { Delegate result = CompilerHelpers.LightCompile(code, _lambda.GlobalParent.TotemContext.Options.CompilationThreshold); // If the adaptive compiler decides to compile this function, we // want to store the new compiled target. This saves us from going // through the interpreter stub every call. var lightLambda = result.Target as LightLambda; if (lightLambda != null) { lightLambda.Compile += handler; } return result; } return code.Compile(); }
public Handler(LambdaExpression handler) { _handler = handler.Compile(); _parameters = handler.Parameters; }
private void UnaryResultExpression(MethodCallExpression expr, LambdaExpression lambda) { var memberAccess = (MemberExpression)expr.Arguments.First(); object value; if (lambda.ReturnType != null && lambda.ReturnType != typeof(void)) { value = lambda.Compile().DynamicInvoke(_object); } else { var memberValue = GetMemberValue(memberAccess); var paramValue = expr.Arguments.Skip(1).Select(arg=>ExpressionValue.GetExpressionValue(arg)).ToArray(); value = ApplyOperation.Apply(expr, memberValue, paramValue); } _parsed.Add(NameAndValues.Create ( name : memberAccess.Member.Name, value : value )); }
public object CompileSys() => _sysExpr.Compile();
/// <summary> /// Fallback to generate the evaluator dynamically. Hitting this is a massive performance problem. /// </summary> private static object EvaluateLambda(LambdaExpression lambda) { if (FailOnLambdaCompile) throw new InvalidOperationException(string.Format("Tried to compile an expression while running tests: {0}: {1}\n{2}", lambda.Body.NodeType, lambda.Body.GetType().FullName, lambda.Body)); Delegate fn = lambda.Compile(); return fn.DynamicInvoke(null); }
internal static Delegate/*!*/ CompileLambda(LambdaExpression/*!*/ lambda, bool debugMode, bool noAdaptiveCompilation, int compilationThreshold) { #if FEATURE_REFEMIT if (debugMode) { return CompileDebug(lambda); } #endif if (noAdaptiveCompilation) { Delegate result = lambda.Compile(); // DLR closures should not be used: Debug.Assert(!(result.Target is Closure) || ((Closure)result.Target).Locals == null); return result; } return lambda.LightCompile(compilationThreshold); }
private static Delegate CompileExpression(Type sourceType, Type destinationType, LambdaExpression expression) { if (IsPublicClass(sourceType) && IsPublicClass(destinationType)) { if (moduleBuilder == null) { var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName("ThisMemberFunctionsAssembly_" + Guid.NewGuid().ToString("N")), AssemblyBuilderAccess.Run); moduleBuilder = assemblyBuilder.DefineDynamicModule("Module"); } var typeBuilder = moduleBuilder.DefineType(string.Format("From_{0}_to_{1}_{2}", sourceType.Name, destinationType.Name, Guid.NewGuid().ToString("N"), TypeAttributes.Public)); var methodBuilder = typeBuilder.DefineMethod("Map", MethodAttributes.Public | MethodAttributes.Static); expression.CompileToMethod(methodBuilder); var resultingType = typeBuilder.CreateType(); var function = Delegate.CreateDelegate(expression.Type, resultingType.GetMethod("Map")); return function; } else { return expression.Compile(); } }