Ejemplo n.º 1
0
        private CompiledCode CompileInternal(CompilerOptions compilerOptions, ErrorListener errorListener)
        {
            ErrorSink  errorSink = new ErrorListenerProxySink(this, errorListener);
            ScriptCode code      = compilerOptions != null?_unit.Compile(compilerOptions, errorSink) : _unit.Compile(errorSink);

            return((code != null) ? new CompiledCode(_engine, code) : null);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Triggered when a resource is (re)imported in the project library.
        /// </summary>
        /// <param name="path">Path of the imported resource, relative to the project's resource folder.</param>
        private void OnEntryImported(string path)
        {
            LibraryEntry entry = ProjectLibrary.GetEntry(path);

            if (entry == null || entry.Type != LibraryEntryType.File)
            {
                return;
            }

            FileEntry fileEntry = (FileEntry)entry;

            if (fileEntry.ResType != ResourceType.ScriptCode)
            {
                return;
            }

            ScriptCode codeFile = ProjectLibrary.Load <ScriptCode>(path);

            if (codeFile == null)
            {
                return;
            }

            if (codeFile.EditorScript)
            {
                isEditorAssemblyDirty = true;
            }
            else
            {
                isGameAssemblyDirty = true;
            }
        }
Ejemplo n.º 3
0
        private ScriptCode /*!*/ CompileRubySource(SourceUnit /*!*/ sourceUnit, LoadFlags flags)
        {
            Assert.NotNull(sourceUnit);

            // TODO: check file timestamp
            string       fullPath = Platform.GetFullPath(sourceUnit.Path);
            CompiledFile compiledFile;

            if (TryGetCompiledFile(fullPath, out compiledFile))
            {
                Utils.Log(String.Format("{0}: {1}", ++_cacheHitCount, sourceUnit.Path), "LOAD_CACHED");

                return(compiledFile.CompiledCode);
            }
            else
            {
                Utils.Log(String.Format("{0}: {1}", ++_compiledFileCount, sourceUnit.Path), "LOAD_COMPILED");

                RubyCompilerOptions options = new RubyCompilerOptions(_context.RubyOptions)
                {
                    FactoryKind = (flags & LoadFlags.LoadIsolated) != 0 ? TopScopeFactoryKind.WrappedFile : TopScopeFactoryKind.File
                };

                long       ts1          = Stopwatch.GetTimestamp();
                ScriptCode compiledCode = sourceUnit.Compile(options, _context.RuntimeErrorSink);
                long       ts2          = Stopwatch.GetTimestamp();
                Interlocked.Add(ref _ScriptCodeGenerationTimeTicks, ts2 - ts1);

                AddCompiledFile(fullPath, compiledCode);

                return(compiledCode);
            }
        }
Ejemplo n.º 4
0
        private List <Scope> GenerateScriptScopes()
        {
            List <Scope> scopes = new List <Scope>(_scriptCodes.Length);
            ScriptModule sm     = ScriptDomainManager.CurrentManager.Host.DefaultModule as ScriptModule;

            for (int i = 0; i < _scriptCodes.Length; i++)
            {
                ScriptCode scriptCode = _scriptCodes[i];

                // Force creation of names used in other script codes into all optimized dictionaries
                ScopeAllocator        allocator = _allocators[scriptCode.LanguageContext];
                IAttributesCollection iac       = CreateLanguageDictionary(scriptCode.LanguageContext, allocator);
                Scope scope = new Scope(sm.Scope, iac);

                // module context is filled later:
                CodeContext codeContext = new CodeContext(scope, scriptCode.LanguageContext);

                IModuleDictionaryInitialization ici = iac as IModuleDictionaryInitialization;
                if (ici != null)
                {
                    ici.InitializeModuleDictionary(codeContext);
                }

                scopes.Add(scope);
                _codeContexts.Add(codeContext);
            }
            return(scopes);
        }
Ejemplo n.º 5
0
        public JasminePageBuilder() : base()
        {
            Title = "Jasmine Spec Runner";
            CssReferences.Add("http://pivotal.github.com/jasmine/lib/jasmine.css");
            ScriptReferences.Add("http://pivotal.github.com/jasmine/lib/jasmine.js");
            ScriptReferences.Add("http://pivotal.github.com/jasmine/lib/jasmine-html.js");
            ScriptCode.Add(
                @"
(function() {
      var jasmineEnv = jasmine.getEnv();
      jasmineEnv.updateInterval = 1000;

      var htmlReporter = new jasmine.HtmlReporter();

      jasmineEnv.addReporter(htmlReporter);

      jasmineEnv.specFilter = function(spec) {
        return htmlReporter.specFilter(spec);
      };

      var currentWindowOnload = window.onload;

      window.onload = function() {
        if (currentWindowOnload) {
          currentWindowOnload();
        }
        execJasmine();
      };

      function execJasmine() {
        jasmineEnv.execute();
      }

    })();");
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Reimports the script code resource according to the currently set import options.
        /// </summary>
        private void TriggerReimport()
        {
            ScriptCode scriptCode   = (ScriptCode)InspectedObject;
            string     resourcePath = ProjectLibrary.GetPath(scriptCode);

            ProjectLibrary.Reimport(resourcePath, importOptions, true);
        }
Ejemplo n.º 7
0
        private CompiledCode CompileInternal(CompilerOptions compilerOptions, ErrorListener errorListener)
        {
            ErrorSink  errorSink = new ErrorListenerProxySink(this, errorListener);
            ScriptCode code      = _unit.Compile(compilerOptions ?? _unit.LanguageContext.GetCompilerOptions(), errorSink);

            return((code != null) ? new CompiledCode(_engine, code) : null);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Retrieves import options for the resource we're currently inspecting.
        /// </summary>
        /// <returns>Script code import options object.</returns>
        private ScriptCodeImportOptions GetImportOptions()
        {
            ScriptCode scriptCode          = InspectedObject as ScriptCode;
            ScriptCodeImportOptions output = null;

            if (scriptCode != null)
            {
                LibraryEntry libEntry = ProjectLibrary.GetEntry(ProjectLibrary.GetPath(scriptCode));
                if (libEntry != null && libEntry.Type == LibraryEntryType.File)
                {
                    FileEntry fileEntry = (FileEntry)libEntry;
                    output = fileEntry.Options as ScriptCodeImportOptions;
                }
            }

            if (output == null)
            {
                if (importOptions == null)
                {
                    output = new ScriptCodeImportOptions();
                }
                else
                {
                    output = importOptions;
                }
            }

            return(output);
        }
Ejemplo n.º 9
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());
            }
        }
Ejemplo n.º 10
0
        private void ExecuteRubySourceUnit(SourceUnit /*!*/ sourceUnit, Scope /*!*/ globalScope, LoadFlags flags)
        {
            Assert.NotNull(sourceUnit, globalScope);

            // TODO: check file timestamp
            string       fullPath = Platform.GetFullPath(sourceUnit.Path);
            CompiledFile compiledFile;

            if (TryGetCompiledFile(fullPath, out compiledFile))
            {
                Utils.Log(String.Format("{0}: {1}", ++_cacheHitCount, sourceUnit.Path), "LOAD_CACHED");
                compiledFile.CompiledCode.Run(globalScope);
            }
            else
            {
                Utils.Log(String.Format("{0}: {1}", ++_compiledFileCount, sourceUnit.Path), "LOAD_COMPILED");

                RubyCompilerOptions options = new RubyCompilerOptions(_context.RubyOptions)
                {
                    IsIncluded = true,
                    IsWrapped  = (flags & LoadFlags.LoadIsolated) != 0,
                };

                long       ts1          = Stopwatch.GetTimestamp();
                ScriptCode compiledCode = sourceUnit.Compile(options, _context.RuntimeErrorSink);
                long       ts2          = Stopwatch.GetTimestamp();
                Interlocked.Add(ref _ScriptCodeGenerationTimeTicks, ts2 - ts1);

                AddCompiledFile(fullPath, compiledCode);

                CompileAndRun(globalScope, compiledCode, _context.Options.InterpretedMode);
            }
        }
Ejemplo n.º 11
0
        private ScriptCode /*!*/ CompileRubySource(SourceUnit /*!*/ sourceUnit, LoadFlags flags)
        {
            Assert.NotNull(sourceUnit);

            // TODO: check file timestamp
            string fullPath = Platform.GetFullPath(sourceUnit.Path);

#if FEATURE_FILESYSTEM
            CompiledFile compiledFile;
            if (TryGetCompiledFile(fullPath, out compiledFile))
            {
                Utils.Log(String.Format("{0}: {1}", ++_cacheHitCount, sourceUnit.Path), "LOAD_CACHED");

                return(compiledFile.CompiledCode);
            }

            Utils.Log(String.Format("{0}: {1}", ++_compiledFileCount, sourceUnit.Path), "LOAD_COMPILED");
#endif

            RubyCompilerOptions options = new RubyCompilerOptions(_context.RubyOptions)
            {
                FactoryKind = (flags & LoadFlags.LoadIsolated) != 0 ? TopScopeFactoryKind.WrappedFile : TopScopeFactoryKind.File
            };

            ScriptCode compiledCode = sourceUnit.Compile(options, _context.RuntimeErrorSink);

#if FEATURE_FILESYSTEM
            AddCompiledFile(fullPath, compiledCode);
#endif
            return(compiledCode);
        }
Ejemplo n.º 12
0
        internal void SaveCompiledCode()
        {
            string savePath = _context.RubyOptions.SavePath;

            if (savePath != null)
            {
                lock (_compiledFileMutex) {
                    var assemblyPath = Path.Combine(savePath, Path.GetFileName(_context.RubyOptions.MainFile) + ".dll");

                    Utils.Log(String.Format("SAVING to {0}", Path.GetFullPath(assemblyPath)), "LOADER");

                    // TODO: allocate eagerly (as soon as config gets fixed)
                    if (_compiledFiles == null)
                    {
                        _compiledFiles = new Dictionary <string, CompiledFile>();
                    }

                    ScriptCode[] codes = new ScriptCode[_compiledFiles.Count];
                    int          i     = 0;
                    foreach (CompiledFile file in _compiledFiles.Values)
                    {
                        codes[i++] = file.CompiledCode;
                    }

                    ScriptCode.SaveToAssembly(assemblyPath, codes);
                }
            }
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Creates a script for some code, or returns the cached scripts if it exists.
 /// </summary>
 /// <param name="sc">Information about the code.</param>
 /// <returns>The script.</returns>
 private static PythonScript GetCodeScript(ScriptCode source)
 {
     if (!codeScripts.ContainsKey(source))
     {
         codeScripts.Add(source, new PythonScript(source.ModuleName, source.Code, source.ExternalScripts));
     }
     return(codeScripts[source]);
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Creates a new assembly for generating a module, ensuring a unique filename like "filename.N.exe" for the generated assembly
        /// </summary>
        AssemblyGen CreateModuleAssembly(ScriptCode scriptCode)
        {
            var su = scriptCode.CompilerContext.SourceUnit;
            var ag = CreateModuleAssembly(su.Id);

            ag.SetSourceUnit(su);
            return(ag);
        }
Ejemplo n.º 15
0
        internal CompiledCode(ScriptEngine engine, ScriptCode code)
        {
            Assert.NotNull(engine);
            Assert.NotNull(code);

            _engine = engine;
            _code   = code;
        }
Ejemplo n.º 16
0
        public static void InitElementChildren(Type elementType, object element, List <Tuple <ChildElementAttribute, PropertyInfo> > childElementProperties)
        {
            StringBuilder sb = new StringBuilder();

            foreach (var item in childElementProperties.Where(row => row.Item1.ChildCategory == ChildCategory.ChildrenColection).OrderBy(row => row.Item1.Order))
            {
                sb.AppendFormat(itemFormat, item.Item2.Name).AppendLine();
            }
            Element elementInstance = element as Element;

            elementInstance.Items     = null;
            elementInstance.ItemTypes = null;

            List <Element> elementList = new List <Element>();

            foreach (var item in childElementProperties.Where(row => row.Item1.ChildCategory == ChildCategory.ChildrenList || row.Item1.ChildCategory == ChildCategory.ChildrenColection))
            {
                object o = item.Item2.GetValue(element, null);
                if (o != null)
                {
                    IEnumerable <Element> elements = o as IEnumerable <Element>;

                    if (elements != null && elements.Count() > 0)
                    {
                        foreach (Element tempelement in elements)
                        {
                            //++???????????
                            // tempelement.PrepareChildrenElements();
                        }
                        if (item.Item1.ChildCategory == ChildCategory.ChildrenColection)
                        {
                            elementList.AddRange(elements);
                        }
                    }
                }
            }
            if (elementList.Count > 0)
            {
                elementInstance.Items     = elementList.ToArray();
                elementInstance.ItemTypes = elementList.Select(row => row.ElementType).ToArray();
            }

            string code = string.Format(format, elementType.Name, sb.ToString());

            CSharpCompilerWraper codeWrapper = new CSharpCompilerWraper();

            codeWrapper.FrameworkVersion  = FrameworkVersion.Version20;
            codeWrapper.CustomeAssemblies = null;

            ScriptCode scriptCode = new ScriptCode();

            scriptCode.SourceCode = code;
            scriptCode.StartUpList.Add(new StartUpInfo()
            {
                ClassName = "Justin.BI.DBLibrary.Compiler.MondrianCompiler", Instance = element, MethordName = "InitChildren", order = 0, MethordParameters = new object[] { element }
            });
            // codeWrapper.Run(scriptCode, null);
        }
        public void MultipleInterpolations()
        {
            IScript script = parser.Parse(ScriptCode.Create(
                                              "$value=320",
                                              "$\"There are {7+4} more ways to {\"do it\"} but lets keep it at that.\""
                                              ));

            Assert.AreEqual("There are 11 more ways to do it but lets keep it at that.", script.Execute());
        }
Ejemplo n.º 18
0
        public void CompareIntWithSubProperty()
        {
            IScript script = parser.Parse(ScriptCode.Create(
                                              "$test=0",
                                              "$test>this.property.length"
                                              ), new Variable("this", this));

            Assert.DoesNotThrow(() => script.Execute());
        }
        public void Interpolation()
        {
            IScript script = parser.Parse(ScriptCode.Create(
                                              "$value=320",
                                              "$\"Like {$value} reasons to hate it.\""
                                              ));

            Assert.AreEqual("Like 320 reasons to hate it.", script.Execute());
        }
Ejemplo n.º 20
0
        public void DefaultParameterValueNotSpecified()
        {
            IScript script = parser.Parse(ScriptCode.Create(
                                              "parameter($value, \"int\", 5)",
                                              "return($value*$value)"
                                              ));

            Assert.AreEqual(25, script.Execute());
        }
Ejemplo n.º 21
0
        public void DefaultParameterValueSpecified()
        {
            IScript script = parser.Parse(ScriptCode.Create(
                                              "parameter($value, \"int\", 5)",
                                              "return($value*$value)"
                                              ));

            Assert.AreEqual(9, script.Execute(new Variable("value", 3)));
        }
        public void EscapeBracketInInterpolation()
        {
            IScript script = parser.Parse(ScriptCode.Create(
                                              "$value=320",
                                              "$\"Use {{} to {\"interpolate\"}.\""
                                              ));

            Assert.AreEqual("Use {} to interpolate.", script.Execute());
        }
Ejemplo n.º 23
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);
        }
Ejemplo n.º 24
0
        public void CallMethodWithOutParameter()
        {
            IScript script = parser.Parse(ScriptCode.Create(
                                              "$variable=0",
                                              "$test.outparameter(ref($variable))",
                                              "return($variable)"
                                              ), new Variable("test", this));

            Assert.AreEqual(42, script.Execute());
        }
Ejemplo n.º 25
0
        protected override CodeGen CreateCodeGen(ScriptCode scriptCode)
        {
            LanguageInfo li = _languages[scriptCode.LanguageContext];

            return(li.TypeGen.DefineMethod(CompilerHelpers.PublicStatic,
                                           "Initialize",
                                           typeof(object),
                                           new Type[] { typeof(CodeContext) },
                                           null));
        }
Ejemplo n.º 26
0
 public HtmlPageBuilder(HtmlPageBuilder builder) : this()
 {
     ScriptReferences.AddRange(builder.ScriptReferences);
     ScriptCode.AddRange(builder.ScriptCode);
     CssReferences.AddRange(builder.CssReferences);
     CssCode.AddRange(builder.CssCode);
     Title         = builder.Title;
     BodyContent   = builder.BodyContent;
     HeaderContent = builder.HeaderContent;
 }
Ejemplo n.º 27
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));
        }
        public void SetEntryAsProperty()
        {
            IScript script = parser.Parse(ScriptCode.Create(
                                              "$value = {}",
                                              "$value.number=60",
                                              "return($value.number)"
                                              ));


            Assert.AreEqual(60, script.Execute());
        }
        public void InitializeDictionary()
        {
            IScript script = parser.Parse(ScriptCode.Create(
                                              "$dic={",
                                              "  \"value\": 70",
                                              "}",
                                              "return($dic[\"value\"])"
                                              ));

            Assert.AreEqual(70, script.Execute <int>());
        }
Ejemplo n.º 30
0
 public void MixedMultiLineAndLineComments()
 {
     Assert.DoesNotThrow(() => {
         parser.Parse(ScriptCode.Create(
                          "/* ----",
                          "// bla bla bla ",
                          "// bla bla bla ",
                          "*/"
                          ));
     });
 }
Ejemplo n.º 31
0
        /// <summary>
        /// Scrapes the HTML page and populates the "Code" structure.
        /// </summary>
        public void GetScriptTags() {
            var scriptTags = HtmlPage.Document.GetElementsByTagName("script");
            foreach (ScriptObject scriptTag in scriptTags) {
                var e = (HtmlElement)scriptTag;
                var type = (string)e.GetAttribute("type");

                if (type == null || !LanguageFound(GetLanguageNameFrom(type)))
                    continue;

                if (DynamicApplication.Current.InitParams.ContainsKey("xamlid")) {
                    if (e.CssClass == null || !e.CssClass.Contains(DynamicApplication.Current.InitParams["xamlid"]))
                        continue;
                } else if (e.CssClass != string.Empty)
                    continue;

                var src = (string)e.GetAttribute("src");
                bool defer = (bool)e.GetProperty("defer");

                string language = GetLanguageNameFrom(type).ToLower();

                _LangConfig.LanguagesUsed[language] = true;

                var sc = new ScriptCode(language, defer);
                if (src != null) {
                    sc.External = DynamicApplication.MakeUri(src);
                } else {
                    var innerHtml = (string)e.GetProperty("innerHTML");
                    if (innerHtml != null)
                        sc.Inline = RemoveMargin(innerHtml);
                }
                Code.Add(sc);
            }
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Scrapes the HTML page and populates the "Code" structure.
        /// </summary>
        public void FetchScriptTags() {
            if (!HtmlPage.IsEnabled)
                return;

            var scriptTags = HtmlPage.Document.GetElementsByTagName("script");

            foreach (ScriptObject scriptTag in scriptTags) {
                var e = (HtmlElement)scriptTag;
                var type = (string)e.GetAttribute("type");
                var src = (string)e.GetAttribute("src");

                string language = null;

                // Find the language by either mime-type or script's file extension
                if (type != null)
                    language = GetLanguageByType(type);
                else if (src != null)
                    language = GetLanguageByExtension(Path.GetExtension(src));

                // Only move on if the language was found
                if (language != null) {

                    var initParams = DynamicApplication.Current.InitParams;

                    // Process this script-tag if ...
                    if (
                        // it's class is "*" ... OR
                        (e.CssClass == "*") ||

                        // the xamlid initparam is set and matches this tag's class ... OR
                        (initParams.ContainsKey("xamlid") && initParams["xamlid"] != null &&
                         e.CssClass != null && e.CssClass == initParams["xamlid"]) ||

                        // the xamlid initparam is not set and this tag does not have a class
                        (!initParams.ContainsKey("xamlid") && (e.CssClass == null || e.CssClass.Length == 0))
                    ) {
                        bool defer = (bool)e.GetProperty("defer");

                        _LangConfig.LanguagesUsed[language] = true;

                        var sc = new ScriptCode(language, defer);

                        if (src != null) {
                            sc.External = DynamicApplication.MakeUri(src);
                        } else {

                            var innerHtml = (string)e.GetProperty("innerHTML");
                            if (innerHtml != null) {
                                // IE BUG: inline script-tags have an extra newline at the front,
                                // so remove it ...
                                if (HtmlPage.BrowserInformation.Name == "Microsoft Internet Explorer" && innerHtml.IndexOf("\r\n") == 0) {
                                    innerHtml = innerHtml.Substring(2);
                                }

                                sc.Inline = innerHtml;
                            }
                        }

                        Code.Add(sc);
                    }

                // Lastly, check to see if this is a zip file
                } else if (src != null && ((type != null && type == "application/x-zip-compressed") || Path.GetExtension(src) == ".zip")) {
                    
                    ZipPackages.Add(DynamicApplication.MakeUri(src));

                }
            }
        }
Ejemplo n.º 33
0
        /// <summary>
        /// Scrapes the HTML page and populates the "Code" structure.
        /// </summary>
        public void GetScriptTags() {
            var scriptTags = HtmlPage.Document.GetElementsByTagName("script");
            foreach (ScriptObject scriptTag in scriptTags) {
                var e = (HtmlElement)scriptTag;
                var type = (string)e.GetAttribute("type");

                if (type == null || !LanguageFound(GetLanguageNameFrom(type)))
                    continue;

                if (DynamicApplication.Current.InitParams.ContainsKey("xamlid")) {
                    if (e.CssClass == null || !e.CssClass.Contains(DynamicApplication.Current.InitParams["xamlid"]))
                        continue;
                } else if (e.CssClass != string.Empty)
                    continue;

                var src = (string)e.GetAttribute("src");
                bool defer = (bool)e.GetProperty("defer");
                bool deferDefault = src != null;
                defer = defer ^ deferDefault;

                string language = GetLanguageNameFrom(type).ToLower();

                _LangConfig.LanguagesUsed[language] = true;

                if (!Code.ContainsKey(type) || Code[type] == null) {
                    Code[type] = new Dictionary<bool, ScriptCode>();
                }
                if (!Code[type].ContainsKey(defer) || Code[type][defer] == null) {
                    var sc = new ScriptCode(language, defer);
                    Code[type][defer] = sc;
                }

                if (src != null) {
                    Code[type][defer].External.Add(MakeUriAbsolute(new Uri(src, UriKind.RelativeOrAbsolute)));
                } else {
                    var innerHtml = (string)e.GetProperty("innerHTML");
                    if (innerHtml != null)
                        Code[type][defer].Inline.Add(RemoveMargin(innerHtml));
                }
            }
        }
Ejemplo n.º 34
0
 internal CompiledCode(ScriptCode code)
 {
     Debug.Assert(code != null);
     _code = code;
 }