示例#1
0
        public void CompilerTest(string /*!*/ code, ErrorSink /*!*/ sink)
        {
            Debug.Assert(code != null && sink != null);
            SourceUnit source;

            string name = _driver.TestRuntime.TestName;

            if (_driver.SaveToAssemblies)
            {
                string path = Path.Combine(Snippets.Shared.SnippetsDirectory, name + ".rb");
                Directory.CreateDirectory(Snippets.Shared.SnippetsDirectory);
                File.WriteAllText(path, code);
                source = _driver.TestRuntime.Context.CreateFileUnit(path);
            }
            else
            {
                source = _driver.TestRuntime.Context.CreateSnippet(code, name + ".rb", SourceCodeKind.File);
            }

            ScriptCode compiledCode = source.Compile(new RubyCompilerOptions(Context.RubyOptions), sink);

            if (compiledCode != null)
            {
                compiledCode.Run(new Scope());
            }
        }
示例#2
0
        internal static PythonModule ExecuteSourceUnit(PythonContext context, SourceUnit /*!*/ sourceUnit)
        {
            ScriptCode   compiledCode = sourceUnit.Compile();
            Scope        scope        = compiledCode.CreateScope();
            PythonModule res          = ((PythonScopeExtension)context.EnsureScopeExtension(scope)).Module;

            compiledCode.Run(scope);
            return(res);
        }
示例#3
0
        internal object CompileAndRun(Scope /*!*/ globalScope, ScriptCode /*!*/ code, bool tryEvaluate)
        {
            long ts1 = Stopwatch.GetTimestamp();

            code.EnsureCompiled();
            long ts2 = Stopwatch.GetTimestamp();

            Interlocked.Add(ref _ILGenerationTimeTicks, ts2 - ts1);

            return(code.Run(globalScope));
        }
示例#4
0
        internal Scope Execute(Scope globalScope, ScriptCode /*!*/ code)
        {
            if (globalScope == null || code.LanguageContext != _context)
            {
                if (globalScope == null)
                {
                    globalScope = code.CreateScope();
                }

                if (code.SourceUnit.Path != null)
                {
                    LoadedScripts[Platform.GetFullPath(code.SourceUnit.Path)] = globalScope;
                }
                code.Run(globalScope);
                return(globalScope);
            }
            else
            {
                code.Run(globalScope);
                return(null);
            }
        }
示例#5
0
        /// <summary>
        /// Execute code within a given module context and returns the result.
        /// The module must be local with respect to the compiled code object.
        /// </summary>
        public object Evaluate(IScriptModule module)
        {
            IScriptModule localModule;

            if (module == null)
            {
                localModule = ScriptDomainManager.CurrentManager.Host.DefaultModule;
            }
            else
            {
                localModule = module;
            }

            return(_code.Run((ScriptModule)localModule));
        }
示例#6
0
        /// <summary>
        /// Execute code within a given module context and returns the result.
        /// The module must be local with respect to the compiled code object.
        /// </summary>
        public object Evaluate(IScriptModule module)
        {
            ScriptModule localModule;

            if (module == null)
            {
                localModule = RemoteWrapper.TryGetLocal <ScriptModule>(ScriptDomainManager.CurrentManager.Host.DefaultModule);
            }
            else
            {
                localModule = RemoteWrapper.GetLocalArgument <ScriptModule>(module, "module");
            }

            return(_code.Run(localModule));
        }
示例#7
0
        private void AstLocations1()
        {
            // DumpExpression uses private reflection:
            if (_driver.PartialTrust)
            {
                return;
            }

            var sourceUnit = Context.CreateSnippet(@"
def add a,b
  a + b
end

add 1, 1
add 'foo', 'bar'
", SourceCodeKind.Expression);

            var options = new RubyCompilerOptions();
            var parser  = new Parser();
            var tokens  = new List <KeyValuePair <SourceSpan, Tokens> >();

            parser.TokenSink = (token, span) => { tokens.Add(new KeyValuePair <SourceSpan, Tokens>(span, token)); };
            var ast = parser.Parse(sourceUnit, options, Context.RuntimeErrorSink);

            const int Id = 0x12345678;

            var lambda = CallSiteTracer.Transform <DlrMainCallTarget>(ast, sourceUnit, options, Id);
            var code   = new ScriptCode(lambda, sourceUnit);

            var locations = new List <int>();

            CallSiteTracer.Register((context, args, result, id, location) => {
                locations.Add(location);
                Debug.Assert(id == Id);
                Debug.Assert(location > 0);

                //Console.WriteLine("-- {0} ---------", location);
                //Console.WriteLine(this);
                //Console.WriteLine(AstUtils.DumpExpression(result.Restrictions.ToExpression()));
                //Console.WriteLine();
                //Console.WriteLine(AstUtils.DumpExpression(result.Expression));
                //Console.WriteLine("----------------");
            });

            code.Run();

            Debug.Assert(locations.Count == 4 && locations[0] == 31 && locations[1] == 19 && locations[2] == 41 && locations[3] == 19);
        }
示例#8
0
            public object load_module(CodeContext /*!*/ context, string fullname)
            {
                bool             ispackage;
                string           modpath;
                PythonModule     mod;
                PythonContext    pythonContext = context.LanguageContext;
                PythonDictionary dict;
                ScriptCode       script = null;

                byte[] code = GetModuleCode(context, fullname, out ispackage, out modpath);
                if (code == null)
                {
                    return(null);
                }

                mod = pythonContext.CompileModule(modpath, fullname,
                                                  new SourceUnit(pythonContext, new MemoryStreamContentProvider(pythonContext, code, modpath), modpath, SourceCodeKind.File),
                                                  ModuleOptions.None, out script);

                dict = mod.__dict__;
                // we do these here because we don't want CompileModule to initialize the module until we've set
                // up some additional stuff
                dict.Add("__name__", fullname);
                dict.Add("__loader__", this);
                dict.Add("__package__", null);

                if (ispackage)
                {
                    // add __path__ to the module *before* the code
                    // gets executed
                    string subname  = GetSubName(fullname);
                    string fullpath = string.Format("{0}{1}{2}{3}",
                                                    _archive,
                                                    Path.DirectorySeparatorChar,
                                                    _prefix.Length > 0 ? _prefix : string.Empty,
                                                    subname);

                    PythonList pkgpath = PythonOps.MakeList(fullpath);
                    dict.Add("__path__", pkgpath);
                }

                script.Run(mod.Scope);
                return(mod);
            }
        private object InvokeTarget(Scope scope)
        {
            if (scope == _optimizedContext.GlobalScope && !_optimizedContext.LanguageContext.EnableTracing)
            {
                EnsureCompiled();

                Exception e        = PythonOps.SaveCurrentException();
                var       funcCode = EnsureFunctionCode(_optimizedTarget, false, true);
                PushFrame(_optimizedContext, funcCode);
                try {
                    if (Ast.CompilerContext.SourceUnit.Kind == SourceCodeKind.Expression)
                    {
                        return(OptimizedEvalWrapper(funcCode));
                    }
                    return(_optimizedTarget(funcCode));
                } finally {
                    PythonOps.RestoreCurrentException(e);
                    PopFrame();
                }
            }

            // if we're running against a different scope or we need tracing then re-compile the code.
            if (_unoptimizedCode == null)
            {
                // TODO: Copy instead of mutate
                ((PythonCompilerOptions)Ast.CompilerContext.Options).Optimized = false;
                Interlocked.CompareExchange(
                    ref _unoptimizedCode,
                    Ast.MakeLookupCode().ToScriptCode(),
                    null
                    );
            }

            // This is a brand new ScriptCode which also handles all appropriate ScriptCode
            // things such as pushing a function code or updating the stack trace for
            // exec/eval code.  Therefore we don't need to do any of that here.
            return(_unoptimizedCode.Run(scope));
        }
示例#10
0
        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));
            }
        }
示例#11
0
 /// <summary>
 /// Executes code in a default scope.
 /// </summary>
 public dynamic Execute()
 {
     return(_code.Run(DefaultScope.Scope));
 }
示例#12
0
 /// <summary>
 /// Execute code within a given scope and returns the result.
 /// </summary>
 public dynamic Execute(ScriptScope scope)
 {
     ContractUtils.RequiresNotNull(scope, nameof(scope));
     return(ScriptCode.Run(scope.Scope));
 }
示例#13
0
            public object load_module(CodeContext /*!*/ context, string fullname)
            {
                fullname = MakeValidPath(fullname, resolved_subpath);

                string code = null;
                GenericModuleCodeType moduleType;
                bool             ispackage    = false;
                string           modpath      = null;
                string           fullFileName = null;
                PythonModule     mod;
                PythonDictionary dict = null;

                // Go through available import types by search-order
                foreach (var order in _search_order)
                {
                    string tempCode = this.resolver.GetScriptSource(fullname.Replace(".", "/") + order.Key);

                    if (tempCode != null)
                    {
                        moduleType   = order.Value;
                        code         = tempCode;
                        modpath      = fullname;
                        fullFileName = fullname.Replace(".", "/") + order.Key;

                        if ((order.Value & GenericModuleCodeType.Package) == GenericModuleCodeType.Package)
                        {
                            ispackage = true;
                        }

                        break;
                    }
                }

                // of no code was loaded
                if (code == null)
                {
                    return(null);
                }

                ScriptCode scriptCode = null;

                mod = context.LanguageContext.CompileModule(fullFileName, fullname,
                                                            new SourceUnit(context.LanguageContext, new SourceStringContentProvider(code), modpath, SourceCodeKind.File),
                                                            ModuleOptions.None, out scriptCode);

                dict = mod.Get__dict__();

                // Set values before execute script
                dict.Add("__name__", fullname.Split('.').Last());
                dict.Add("__loader__", this);
                dict.Add("__package__", null);

                if (ispackage)
                {
                    // Add path
                    string fullpath = RESOLVER_PATH_NAME + "." + string.Format(fullname.Replace("/", "."));

                    //_rel_path = fullpath;
                    paths.Add(fullpath);

                    List pkgpath = PythonOps.MakeList(fullpath);

                    if (dict.ContainsKey("__path__"))
                    {
                        dict["__path__"] = pkgpath;
                    }
                    else
                    {
                        dict.Add("__path__", pkgpath);
                    }
                }
                else
                {
                    StringBuilder packageName  = new StringBuilder();
                    string[]      packageParts = fullname.Split(new char[] { '/' });
                    for (int i = 0; i < packageParts.Length - 1; i++)
                    {
                        if (i > 0)
                        {
                            packageName.Append(".");
                        }

                        packageName.Append(packageParts[i]);
                    }

                    dict["__package__"] = packageName.ToString();
                }

                scriptCode.Run(mod.Scope);
                return(mod);
            }
示例#14
0
 /// <summary>
 /// Executes code in a default scope.
 /// </summary>
 public object Execute()
 {
     return(_code.Run(DefaultScope.Scope));
 }