public bool DoOneInteractive(Frame topFrame) { bool continueInteraction; Stmt s = ReadStatement(out continueInteraction); if (continueInteraction == false) { return(false); } // 's' is null when we parse a line composed only of a NEWLINE (interactive_input grammar); // we don't generate anything when 's' is null if (s != null) { FrameCode code = OutputGenerator.GenerateSnippet(context, s, true); if (ExecWrapper != null) { CallTarget0 t = delegate() { try { code.Run(topFrame); } catch (Exception e) { DumpException(e); } return(null); }; object callable = new Function0(topFrame.__module__, "wrapper", t, new string[0], new object[0]); Ops.Call(ExecWrapper, callable); } else { code.Run(topFrame); } } return(true); }
public void ExecuteCommand(string code, IScriptModule module) { CommandDispatcher dispatcher = ScriptDomainManager.CurrentManager.GetCommandDispatcher(); if (dispatcher != null) { Exception exception = null; ICompiledCode compiled_code = CompileInteractiveCode(code, module); if (compiled_code != null) // TODO: should throw? { CallTarget0 run_code = delegate() { try { PrintInteractiveCodeResult(compiled_code.Evaluate(module)); } catch (Exception e) { exception = e; } return(null); }; dispatcher(run_code); // We catch and rethrow the exception since it could have been thrown on another thread if (exception != null) { throw exception; } } } else { ExecuteInteractiveCode(code, module); } }
public OptimizedFunctionAny(string name, MethodInfo[] infos, MethodBase[] targets, FunctionType functionType) : base(name, targets, functionType) { for (int i = 0; i < infos.Length; i++) { Debug.Assert(infos[i].IsStatic); switch (infos[i].GetParameters().Length) { case 0: target0 = IronPython.Compiler.CodeGen.CreateDelegate(infos[i], typeof(CallTarget0)) as CallTarget0; break; case 1: if (!infos[i].GetParameters()[0].ParameterType.HasElementType) { target1 = IronPython.Compiler.CodeGen.CreateDelegate(infos[i], typeof(CallTarget1)) as CallTarget1; } else { targetN = IronPython.Compiler.CodeGen.CreateDelegate(infos[i], typeof(CallTargetN)) as CallTargetN; } break; case 2: target2 = IronPython.Compiler.CodeGen.CreateDelegate(infos[i], typeof(CallTarget2)) as CallTarget2; break; case 3: target3 = IronPython.Compiler.CodeGen.CreateDelegate(infos[i], typeof(CallTarget3)) as CallTarget3; break; case 4: target4 = IronPython.Compiler.CodeGen.CreateDelegate(infos[i], typeof(CallTarget4)) as CallTarget4; break; case 5: target5 = IronPython.Compiler.CodeGen.CreateDelegate(infos[i], typeof(CallTarget5)) as CallTarget5; break; } } }
public TypedClosure(Func <R> target) : base(target, 0) { typedtarget = target; untypedtarget = (typeof(R) == typeof(object)) ? Utils.MakeUntypedTailCallSafe((Func <object>)(object) target) : Utils.MakeUntyped((Func <R>)target); }
public OptimizedFunctionAny(OptimizedFunctionAny from) : base(from) { target0 = from.target0; target1 = from.target1; target2 = from.target2; target3 = from.target3; target4 = from.target4; target5 = from.target5; targetN = from.targetN; }
public static object StringToNumber(object obj) { string str = RequiresNotNull <string>(obj); if (str.Length == 0) { return(FALSE); } Parser number_parser = new Parser(); Scanner number_scanner = new Scanner(); number_parser.scanner = number_scanner; number_scanner.SetSource(str, 0); number_parser.result = null; number_scanner.yy_push_state(3); try { CallTarget0 disp = delegate { if (number_parser.Parse()) { Debug.Assert(number_parser.result != null); return(number_parser.result); } else { return(FALSE); } }; CallTarget1 handler = delegate(object o) { throw new Continuation(); }; return(Runtime.R6RS.Exceptions.WithExceptionHandler( Closure.Create(handler), Closure.Create(disp))); } catch { return(FALSE); } }
public static object CompileCore(object expr) { // fast path for really simple stuff if (expr is SymbolId) { CallTarget0 n = delegate { return(SymbolValue(expr)); }; return(Closure.Create(n)); } AssemblyGenAttributes aga = ScriptDomainManager.Options.AssemblyGenAttributes; ScriptDomainManager.Options.AssemblyGenAttributes &= ~AssemblyGenAttributes.EmitDebugInfo; ScriptDomainManager.Options.AssemblyGenAttributes &= ~AssemblyGenAttributes.GenerateDebugAssemblies; ScriptDomainManager.Options.AssemblyGenAttributes &= ~AssemblyGenAttributes.DisableOptimizations; if (ScriptDomainManager.Options.DebugMode) { ScriptDomainManager.Options.AssemblyGenAttributes |= AssemblyGenAttributes.EmitDebugInfo; ScriptDomainManager.Options.AssemblyGenAttributes |= AssemblyGenAttributes.GenerateDebugAssemblies; ScriptDomainManager.Options.AssemblyGenAttributes |= AssemblyGenAttributes.DisableOptimizations; ScriptDomainManager.Options.DebugCodeGeneration = true; } else { ScriptDomainManager.Options.DebugCodeGeneration = false; } ScriptDomainManager.Options.AssemblyGenAttributes |= AssemblyGenAttributes.SaveAndReloadAssemblies; // if you ever want to inspect the emitted dll's comment the following out (or skip in the debugger), use with care ScriptDomainManager.Options.AssemblyGenAttributes &= ~AssemblyGenAttributes.SaveAndReloadAssemblies; var prevt = IronScheme.Compiler.Generator.AllowTransientBinding; var prevag = Compiler.Generator.CurrentAssemblyGen; if ((ScriptDomainManager.Options.AssemblyGenAttributes & AssemblyGenAttributes.SaveAndReloadAssemblies) != 0) { IronScheme.Compiler.Generator.AllowTransientBinding = false; ScriptDomainManager.CurrentManager.Snippets.CurrentAssembly = Compiler.Generator.CurrentAssemblyGen = AssemblyGen.CreateModuleAssembly(null); } else { Compiler.Generator.CurrentAssemblyGen = ScriptDomainManager.Options.DebugMode ? ScriptDomainManager.CurrentManager.Snippets.DebugAssembly : ScriptDomainManager.CurrentManager.Snippets.Assembly; } int c = Interlocked.Increment(ref evalcounter); #if DEBUG Stopwatch sw = Stopwatch.StartNew(); #endif //Console.WriteLine(new Cons(expr).PrettyPrint); try { CodeBlock cb = IronSchemeLanguageContext.CompileExpr(new Cons(expr)); cb.ExplicitCodeContextExpression = null; ScriptCode sc = Context.LanguageContext.CompileSourceCode(cb); //wrap #if DEBUG sw.Stop(); Trace.WriteLine(sw.Elapsed.TotalMilliseconds, string.Format("compile - eval-core({0:D3})", c)); sw = Stopwatch.StartNew(); #endif try { sc.LibraryGlobals = Compiler.SimpleGenerator.libraryglobals; sc.LibraryGlobalsN = Compiler.SimpleGenerator.libraryglobalsN; sc.LibraryGlobalsX = Compiler.SimpleGenerator.libraryglobalsX; ScriptModule sm = ScriptDomainManager.CurrentManager.CreateModule(string.Format("eval-core({0:D3})", c), sc); sc = sm.GetScripts()[0]; #if DEBUG sw.Stop(); Trace.WriteLine(sw.Elapsed.TotalMilliseconds, string.Format("compile*- eval-core({0:D3})", c)); #endif CallTarget0 compiled = delegate { #if DEBUG try { sw = Stopwatch.StartNew(); #endif return(sc.Run(Context.ModuleContext.Module)); #if DEBUG } finally { sw.Stop(); Trace.WriteLine(sw.Elapsed.TotalMilliseconds, string.Format("run - eval-core({0:D3})", c)); } #endif }; return(Closure.Create(compiled)); } catch (Variable.UnInitializedUsageException ex) { CallTarget0 err = delegate { return(AssertionViolation(ex.Variable.Block.Name, ex.Message, UnGenSym(ex.Variable.Name))); }; return(Closure.Create(err)); } finally { BoundExpression.Fixups.Clear(); BoundExpression.FixupTypes.Clear(); Compiler.Generator.CurrentAssemblyGen = prevag; ScriptDomainManager.Options.AssemblyGenAttributes = aga; IronScheme.Compiler.Generator.AllowTransientBinding = prevt; sc.ClearCache(); Compiler.SimpleGenerator.ClearGlobals(); Compiler.ClrGenerator.compiletimetypes.Clear(); } } catch (Continuation) { throw; } catch (Exception ex) { var who = ex.Data["Who"]; return(SyntaxError(who ?? FALSE, ex.Message, FALSE, FALSE)); } }
public static Func <R> MakeTyped <R>(CallTarget0 f) { return(() => Unbox <R>(f())); }
public static Action MakeVoidTyped(CallTarget0 f) { return(() => f()); }
public TypedClosure(Func <R> target, CallTarget0 untypedtarget) : base(target, 0) { typedtarget = target; this.untypedtarget = untypedtarget; }
protected internal static Expression GetAst(object args, CodeBlock cb, bool istailposition) { if (args is Annotation) { args = ((Annotation)args).stripped; } Cons c = args as Cons; if (c != null) { if (c.car is SymbolId) { SymbolId f = (SymbolId)c.car; Variable var = cb.Lookup(f); if (var != null && !assigns.ContainsKey(f)) { var = null; } object m; #if OPTIMIZATIONS #if !BLAH CodeBlockExpression cbe; //// needs to do the same for overloads... if (SimpleGenerator.libraryglobals.TryGetValue(f, out cbe)) { Expression[] ppp = GetAstListNoCast(c.cdr as Cons, cb); if (cbe.Block.ParameterCount < 9 && cbe.Block.ParameterCount == ppp.Length) { //inline here? we could for simple bodies, but we need to copy the entire structure if (!(cbe.Block.HasEnvironment || cbe.Block.IsClosure)) { if (cbe.Block.Body is ReturnStatement) { ReturnStatement rs = (ReturnStatement)cbe.Block.Body; if (!ScriptDomainManager.Options.DebugMode && !ScriptDomainManager.Options.LightweightDebugging && !cb.IsGlobal && IsSimpleExpression(rs.Expression)) { return(InlineCall(cb, Ast.CodeBlockExpression(RewriteBody(cbe.Block), false, cbe.IsStronglyTyped), ppp)); } } } if (cbe.Block != cb.Parent && cbe.Block != cb) // do TCE later { return(CallNormal(cbe, ppp)); } } } // varargs if (SimpleGenerator.libraryglobalsX.TryGetValue(f, out cbe)) { Expression[] ppp = GetAstListNoCast(c.cdr as Cons, cb); if (cbe.Block.ParameterCount < 9 && cbe.Block.ParameterCount - 1 <= ppp.Length) { //inline here? return(CallVarArgs(cbe, ppp)); } } // overloads CodeBlockDescriptor[] cbd; if (SimpleGenerator.libraryglobalsN.TryGetValue(f, out cbd)) { Expression[] ppp = GetAstListNoCast(c.cdr as Cons, cb); foreach (CodeBlockDescriptor d in cbd) { if (d.codeblock.Block.ParameterCount < 9) { if (ppp.Length == d.arity || (d.varargs && ppp.Length > d.arity)) { if (d.varargs) { //inline here? return(CallVarArgs(d.codeblock, ppp)); } else { //inline here? //if (d.codeblock.Block != cb.Parent && d.codeblock.Block != cb) // do TCE later, not yet { return(CallNormal(d.codeblock, ppp)); } } } } } } #endif //if (!ScriptDomainManager.Options.DebugMode) { if (f == SymbolTable.StringToId("call-with-values")) { Expression[] ppp = GetAstListNoCast(c.cdr as Cons, cb); if (ppp.Length == 2 && ppp[1] is MethodCallExpression) { MethodCallExpression consumer = ppp[1] as MethodCallExpression; if (ppp[0] is MethodCallExpression) { MethodCallExpression producer = ppp[0] as MethodCallExpression; if (consumer.Method == Closure_Make && producer.Method == Closure_Make) { CodeBlockExpression ccbe = consumer.Arguments[0] as CodeBlockExpression; CodeBlockExpression pcbe = producer.Arguments[0] as CodeBlockExpression; pcbe.Block.Bind(); ccbe.Block.Bind(); if (ccbe.Block.ParameterCount == 0) { return(InlineCall(cb, ccbe)); } else if (ccbe.Block.ParameterCount == 1) { return(InlineCall(cb, ccbe, Ast.SimpleCallHelper(typeof(Helpers).GetMethod("UnwrapValue"), InlineCall(cb, pcbe)))); } else { Variable values = cb.CreateTemporaryVariable((SymbolId)Builtins.GenSym("values"), typeof(object[])); Expression valuesarr = Ast.Read(values); Expression[] pppp = new Expression[ccbe.Block.ParameterCount]; for (int i = 0; i < pppp.Length; i++) { pppp[i] = Ast.ArrayIndex(valuesarr, Ast.Constant(i)); } return(Ast.Comma( Ast.Void( Ast.Write( values, Ast.ComplexCallHelper( Ast.SimpleCallHelper(typeof(Helpers).GetMethod("WrapValue"), InlineCall(cb, pcbe)), typeof(MultipleValues).GetMethod("ToArray", new Type[] { typeof(int) }), Ast.Constant(pppp.Length)))), InlineCall(cb, ccbe, pppp))); } } } if (consumer.Method == Closure_Make) { CodeBlockExpression ccbe = consumer.Arguments[0] as CodeBlockExpression; ccbe.Block.Bind(); Expression producer = ppp[0]; Expression exx = Ast.ConvertHelper(producer, typeof(Callable)); MethodInfo callx = GetCallable(0); if (ccbe.Block.ParameterCount == 0) { return(InlineCall(cb, ccbe)); } else if (ccbe.Block.ParameterCount == 1) { return(InlineCall(cb, ccbe, Ast.SimpleCallHelper(typeof(Helpers).GetMethod("UnwrapValue"), Ast.Call(exx, callx)))); } else { Variable values = cb.CreateTemporaryVariable((SymbolId)Builtins.GenSym("values"), typeof(object[])); Expression valuesarr = Ast.Read(values); Expression[] pppp = new Expression[ccbe.Block.ParameterCount]; for (int i = 0; i < pppp.Length; i++) { pppp[i] = Ast.ArrayIndex(valuesarr, Ast.Constant(i)); } return(Ast.Comma( Ast.Void( Ast.Write( values, Ast.ComplexCallHelper( Ast.SimpleCallHelper(typeof(Helpers).GetMethod("WrapValue"), Ast.Call(exx, callx)), typeof(MultipleValues).GetMethod("ToArray", new Type[] { typeof(int) }), Ast.Constant(pppp.Length)))), InlineCall(cb, ccbe, pppp))); } } } else { ; } } } #endif // this can be enabled once builtins are auto CPS'd. // ok I tried, but there are issues still, not sure what #if OPTIMIZATIONS // check for inline emitter InlineEmitter ie; if (TryGetInlineEmitter(f, out ie)) { Expression result = ie(GetAstList(c.cdr as Cons, cb)); // if null is returned, the method cannot be inlined if (result != null) { if (spanhint.IsValid) { result.SetLoc(spanhint); } return(result); } } #endif if (Context.Scope.TryLookupName(f, out m)) { if (var == null) { IGenerator gh = m as IGenerator; if (gh != null) { return(gh.Generate(c.cdr, cb)); } BuiltinMethod bf = m as BuiltinMethod; if (bf != null) { MethodBinder mb = bf.Binder; Expression[] pars = Array.ConvertAll(GetAstList(c.cdr as Cons, cb), e => Unwrap(e)); if (bf.AllowConstantFold && !ScriptDomainManager.Options.DebugMode) { bool constant = Array.TrueForAll(pars, e => e is ConstantExpression && e.Type != typeof(BigInteger)); if (constant) { object[] cargs = Array.ConvertAll(pars, e => GetRuntimeConstant((ConstantExpression)e)); CallTarget0 disp = delegate { return(bf.Call(cargs)); }; CallTarget1 handler = delegate(object e) { throw new CompileTimeEvaluationException(); }; try { object result = Runtime.R6RS.Exceptions.WithExceptionHandler( Closure.Create(handler), Closure.Create(disp)); var rrrr = GetCons(result, cb); if (spanhint.IsValid) { rrrr.SetLoc(spanhint); } return(rrrr); } catch (CompileTimeEvaluationException) { } } } Type[] types = GetExpressionTypes(pars); MethodCandidate mc = mb.MakeBindingTarget(CallType.None, types); if (mc != null) { if (mc.Target.NeedsContext) { pars = ArrayUtils.Insert <Expression>(Ast.CodeContext(), pars); } MethodBase meth = mc.Target.Method; var rrrr = Ast.ComplexCallHelper(meth as MethodInfo, pars); if (spanhint.IsValid) { rrrr.SetLoc(spanhint); } return(rrrr); } } Closure clos = m as Closure; if (clos != null && !SetGenerator.IsAssigned(f)) { // no provision for varargs MethodInfo[] mis = clos.Targets; if (mis.Length > 0) { MethodBinder mb = MethodBinder.MakeBinder(binder, SymbolTable.IdToString(f), mis, BinderType.Normal); Expression[] pars = Array.ConvertAll(GetAstList(c.cdr as Cons, cb), e => Unwrap(e)); if (clos.AllowConstantFold && !ScriptDomainManager.Options.DebugMode) { bool constant = Array.TrueForAll(pars, e => e is ConstantExpression && e.Type != typeof(BigInteger)); if (constant) { object[] cargs = Array.ConvertAll(pars, e => GetRuntimeConstant((ConstantExpression)e)); CallTarget0 disp = delegate { var rrrr = clos.Call(cargs); return(rrrr); }; CallTarget1 handler = delegate(object e) { throw new CompileTimeEvaluationException(); }; try { object result = Runtime.R6RS.Exceptions.WithExceptionHandler( Closure.Create(handler), Closure.Create(disp)); var rrrr = GetCons(result, cb); if (spanhint.IsValid) { rrrr.SetLoc(spanhint); } return(rrrr); } catch (CompileTimeEvaluationException) { } } } // exclude transient members if needed if (!AllowTransientBinding) { mis = Array.FindAll(mis, x => !IsTransient(x.Module)); } if (mis.Length > 0) { Type[] types = GetExpressionTypes(pars); MethodCandidate mc = mb.MakeBindingTarget(CallType.None, types); if (mc != null) { if (mc.Target.NeedsContext) { pars = ArrayUtils.Insert <Expression>(Ast.CodeContext(), pars); } MethodBase meth = mc.Target.Method; var rrrr = Ast.ComplexCallHelper(meth as MethodInfo, pars); if (spanhint.IsValid) { rrrr.SetLoc(spanhint); } return(rrrr); } } } // check for overload thing } } } } Expression ex = Unwrap(GetAst(c.car, cb)); // a 'let' if (ex is MethodCallExpression) { var ppp = GetAstList(c.cdr as Cons, cb); MethodCallExpression mcexpr = (MethodCallExpression)ex; if (mcexpr.Method == Closure_Make) { CodeBlockExpression cbe = mcexpr.Arguments[0] as CodeBlockExpression; if (ppp.Length < 9 && cbe.Block.ParameterCount == ppp.Length) { return(InlineCall(cb, cbe, istailposition, ppp)); } } // cater for varargs more efficiently, this does not seem to hit, probably needed somewhere else if (mcexpr.Method == Closure_MakeVarArgsX) { CodeBlockExpression cbe = mcexpr.Arguments[0] as CodeBlockExpression; if (ppp.Length < 9 && cbe.Block.ParameterCount <= ppp.Length) { return(CallVarArgs(cbe, ppp)); } } } if (ex is NewExpression && typeof(ITypedCallable).IsAssignableFrom(ex.Type)) { NewExpression mcexpr = ex as NewExpression; CodeBlockExpression cbe = mcexpr.Arguments[0] as CodeBlockExpression; if (cbe == null && mcexpr.Arguments[0].Type == typeof(CodeContext) && mcexpr.Arguments[0] is ConstantExpression) // implies null { cbe = mcexpr.Arguments[1] as CodeBlockExpression; } if (cbe != null) { var ppp = GetAstListNoCast(c.cdr as Cons, cb); if (ppp.Length < 9 && cbe.Block.ParameterCount == ppp.Length) { return(InlineCall(cb, cbe, istailposition, ppp)); } } } if (ex is ConstantExpression) { Builtins.SyntaxError(SymbolTable.StringToObject("generator"), "expecting a procedure", c.car, c); } Expression r = null; if (ex.Type.Name.Contains("TypedClosure")) { Expression[] pp = GetAstListNoCast(c.cdr as Cons, cb); var m = ex.Type.GetMethod("Invoke"); r = Ast.SimpleCallHelper(ex, m, pp); } else { Expression[] pp = GetAstList(c.cdr as Cons, cb); if (ex.Type != typeof(Callable)) { ex = Ast.ConvertHelper(ex, typeof(Callable)); } MethodInfo call = GetCallable(pp.Length); r = pp.Length > 8 ? Ast.Call(ex, call, Ast.NewArray(typeof(object[]), pp)) : Ast.Call(ex, call, pp); } if (spanhint.IsValid) { r.SetLoc(spanhint); } return(r); } object[] v = args as object[]; if (v != null) { return(GetConsVector(v, cb)); } else if (args is byte[]) { Expression[] ba = Array.ConvertAll(args as byte[], b => Ast.Constant(b)); return(Ast.NewArray(typeof(byte[]), ba)); } else { if (args is SymbolId) { SymbolId sym = (SymbolId)args; if (sym == SymbolTable.StringToId("uninitialized")) { return(Ast.ReadField(null, typeof(Uninitialized), "Instance")); } else { return(Read(sym, cb, typeof(object))); } } if (args == Builtins.Unspecified) { return(Ast.ReadField(null, Unspecified)); } if (args is Fraction) { Fraction f = (Fraction)args; return(Ast.Constant(new FractionConstant(f))); } if (args is ComplexFraction) { ComplexFraction f = (ComplexFraction)args; return(Ast.Constant(new ComplexFractionConstant(f))); } if (args != null && args.GetType().Name == "stx") { args = new SerializedConstant(args); } return(Ast.Constant(args)); } }
public Function0(PythonModule globals, string name, CallTarget0 target, string[] argNames, object[] defaults) : base(globals, name, argNames, defaults) { this.target = target; }
public Function0(PythonModule globals, string name, CallTarget0 target, string[] argNames, object[] defaults) : base(globals, name, argNames, defaults) { this.target = target; }
public OptimizedFunction0(OptimizedFunction0 from) : base(from) { target = from.target; }
public OptimizedFunction0(string name, MethodInfo info, MethodBase[] targets, FunctionType functionType) : base(name, targets, functionType) { target = IronPython.Compiler.CodeGen.CreateDelegate(info, typeof(CallTarget0)) as CallTarget0; }
public FastCallable0(string name, CallTarget0 target) { this.target0 = target; this.name = name; }