Пример #1
0
        internal static JintEngine CreateEngine(ScriptedPatchRequest patch)
        {
            AssertValidScript(patch.Script);
            var wrapperScript = String.Format(@"
function ExecutePatchScript(docInner){{
  (function(doc){{
	{0}{1}
  }}).apply(docInner);
}};
", patch.Script, patch.Script.EndsWith(";") ? String.Empty : ";");

            var jintEngine = new JintEngine()
                             .AllowClr(false);


            jintEngine.Run(GetFromResources("Raven.Database.Json.Map.js"));

            jintEngine.Run(GetFromResources("Raven.Database.Json.RavenDB.js"));

            jintEngine.SetFunction("LoadDocument", ((Func <string, object>)(value =>
            {
                var loadedDoc = loadDocumentStatic(value);
                if (loadedDoc == null)
                {
                    return(null);
                }
                loadedDoc[Constants.DocumentIdFieldName] = value;
                return(ToJsObject(jintEngine.Global, loadedDoc));
            })));

            jintEngine.Run(wrapperScript);

            return(jintEngine);
        }
Пример #2
0
        static void Main(string[] args)
        {
            var       assembly = Assembly.Load("Jint.Tests");
            Stopwatch sw       = new Stopwatch();

            string     script = new StreamReader(assembly.GetManifestResourceStream("Jint.Tests.Parse.coffeescript-format.js")).ReadToEnd();
            JintEngine jint   = new JintEngine()
                                // .SetDebugMode(true)
                                .DisableSecurity()
                                .SetFunction("print", new Action <string>(Console.WriteLine))
                                .SetFunction("stop", new Action(delegate() { Console.WriteLine(); }));

            sw.Reset();
            sw.Start();

            jint.Run(script);
            try
            {
                var result = jint.Run("CoffeeScript.compile('number = 42', {bare: true})");
            }
            catch (JintException e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("{0}ms", sw.ElapsedMilliseconds);
        }
Пример #3
0
        static void Main(string[] args)
        {
            var       assembly = Assembly.Load("Jint.Tests");
            Stopwatch sw       = new Stopwatch();

            // string script = new StreamReader(assembly.GetManifestResourceStream("Jint.Tests.Parse.coffeescript-debug.js")).ReadToEnd();
            JintEngine jint = new JintEngine()
                              // .SetDebugMode(true)
                              .DisableSecurity()
                              .SetFunction("print", new Action <string>(Console.WriteLine))
                              .SetFunction("write", new Action <string>(t => Console.WriteLine(t)))
                              .SetFunction("stop", new Action(delegate() { Console.WriteLine(); }));

            sw.Reset();
            sw.Start();

            try
            {
                Console.WriteLine(jint.Run("2+3"));
                Console.WriteLine("after0");
                Console.WriteLine(jint.Run(")(---"));
                Console.WriteLine("after1");
                Console.WriteLine(jint.Run("FOOBAR"));
                Console.WriteLine("after2");
            }
            catch (JintException e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("{0}ms", sw.ElapsedMilliseconds);
        }
Пример #4
0
        static void Main(string[] args)
        {
            var assembly = Assembly.Load("Jint.Tests");
            Stopwatch sw = new Stopwatch();

            string script = new StreamReader(assembly.GetManifestResourceStream("Jint.Tests.Parse.coffeescript-format.js")).ReadToEnd();
            JintEngine jint = new JintEngine()
                // .SetDebugMode(true)
                .DisableSecurity()
                .SetFunction("print", new Action<string>(Console.WriteLine))
                .SetFunction("stop", new Action( delegate() { Console.WriteLine(); }));
            sw.Reset();
            sw.Start();

            jint.Run(script);
            try
            {
                var result = jint.Run("CoffeeScript.compile('number = 42', {bare: true})");
            }
            catch (JintException e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("{0}ms", sw.ElapsedMilliseconds);
        }
Пример #5
0
        static void Main(string[] args)
        {

            var assembly = Assembly.Load("Jint.Tests");
            Stopwatch sw = new Stopwatch();

            // string script = new StreamReader(assembly.GetManifestResourceStream("Jint.Tests.Parse.coffeescript-debug.js")).ReadToEnd();
            JintEngine jint = new JintEngine()
                // .SetDebugMode(true)
                .DisableSecurity()
                .SetFunction("print", new Action<string>(Console.WriteLine))
                .SetFunction("write", new Action<string>(t => Console.WriteLine(t)))
                .SetFunction("stop", new Action(delegate() { Console.WriteLine(); }));
            sw.Reset();
            sw.Start();

            try
            {
                Console.WriteLine(jint.Run("2+3"));
                Console.WriteLine("after0");
                Console.WriteLine(jint.Run(")(---"));
                Console.WriteLine("after1");
                Console.WriteLine(jint.Run("FOOBAR"));
                Console.WriteLine("after2");

            }
            catch (JintException e)
            {
                Console.WriteLine(e.Message);
            }

            Console.WriteLine("{0}ms", sw.ElapsedMilliseconds);
        }
Пример #6
0
        /// <summary>
        /// 计算
        /// </summary>
        /// <param name="expression">表达式</param>
        /// <example>(100 + (200 - 50) * 3) = 550m</example>
        /// <returns>计算结果</returns>
        public static decimal Calc(string expression)
        {
            decimal num;

            try
            {
                num = Convert.ToDecimal(engine.Run(expression));
            }
            catch
            {
                throw new Exception("计算错误");
            }
            return(num);
        }
Пример #7
0
        public void OnLoad()
        {
            try
            {
                _engine.Run(File.ReadAllText(PluginFile));

                Enabled = true;

                _engine.Run("onLoad();");
            }
            catch (Exception)
            {
            }
        }
Пример #8
0
        public void TestPerformance()
        {
            string[] tests = { "3d-cube", "3d-morph", "3d-raytrace", "access-binary-trees", "access-fannkuch", "access-nbody", "access-nsieve", "bitops-3bit-bits-in-byte", "bitops-bits-in-byte", "bitops-bitwise-and", "bitops-nsieve-bits", "controlflow-recursive", "crypto-aes", "crypto-md5", "crypto-sha1", "date-format-tofte", "date-format-xparb", "math-cordic", "math-partial-sums", "math-spectral-norm", "regexp-dna", "string-base64", "string-fasta", "string-tagcloud", "string-unpack-code", "string-validate-input" };

            var       assembly = Assembly.GetExecutingAssembly();
            Stopwatch sw       = new Stopwatch();

            foreach (var test in tests)
            {
                string script;

                try {
                    script = new StreamReader(assembly.GetManifestResourceStream("Jint.Tests.SunSpider." + test + ".js")).ReadToEnd();
                    if (String.IsNullOrEmpty(script))
                    {
                        continue;
                    }
                }
                catch {
                    Console.WriteLine("{0}: ignored", test);
                    continue;
                }

                JintEngine jint = new JintEngine()
                                  //.SetDebugMode(true)
                                  .DisableSecurity();

                sw.Reset();
                sw.Start();

                jint.Run(script);

                Console.WriteLine("{0}: {1}ms", test, sw.ElapsedMilliseconds);
            }
        }
Пример #9
0
        //
        private void execScript(string path)
        {
            if (!sourceCodes.ContainsKey(path))
            {
                if (!File.Exists(path))
                {
                    return;
                }


                var          fstream = new FileStream(path, FileMode.Open);
                StreamReader reader  = new StreamReader(fstream);
                var          code    = reader.ReadToEnd();
                sourceCodes.Add(path, code);
            }
            var src = sourceCodes[path];

            try
            {
                //just run.
                jint.Run(src);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }

            if (canvas != null)
            {
                canvas.InvalidateVisual();
            }
        }
Пример #10
0
        static void Main(string[] args)
        {
            Stopwatch sw = new Stopwatch();

            // string script = new StreamReader(assembly.GetManifestResourceStream("Jint.Tests.Parse.coffeescript-debug.js")).ReadToEnd();
            JintEngine jint = new JintEngine()
                              // .SetDebugMode(true)
                              .DisableSecurity()
                              .SetFunction("print", new Action <object>(Console.WriteLine));

            sw.Reset();
            jint.SetMaxRecursions(50);
            jint.SetMaxSteps(10 * 1000);

            sw.Start();
            try
            {
                Console.WriteLine(
                    jint.Run(File.ReadAllText(@"C:\Work\ravendb-2.0\SharedLibs\Sources\jint-22024d8a6e7a\Jint.Play\test.js")));
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
            }
            finally
            {
                Console.WriteLine("{0}ms", sw.ElapsedMilliseconds);
            }
        }
Пример #11
0
        static void Main(string[] args)
        {

            Stopwatch sw = new Stopwatch();

            // string script = new StreamReader(assembly.GetManifestResourceStream("Jint.Tests.Parse.coffeescript-debug.js")).ReadToEnd();
            JintEngine jint = new JintEngine()
                // .SetDebugMode(true)
                .DisableSecurity()
                .SetFunction("print", new Action<string>(Console.WriteLine))
                .SetFunction("write", new Action<string>(t => Console.WriteLine(t)))
                .SetFunction("stop", new Action(delegate() { Console.WriteLine(); }));
            sw.Reset();
	        jint.SetMaxRecursions(50);
	        jint.SetMaxSteps(10*1000);

			sw.Start();
			try
			{
				Console.WriteLine(
					jint.Run(File.ReadAllText(@"C:\Work\ravendb-1.2\SharedLibs\Sources\jint-22024d8a6e7a\Jint.Play\test.js")));
			}
			catch (Exception e)
			{
				Console.WriteLine(e);
			}
	        finally 
	        {
				Console.WriteLine("{0}ms", sw.ElapsedMilliseconds);
			}

        }
Пример #12
0
    private void Run()
    {
        JintEngine engine = new JintEngine();

        engine.SetFunction("GTest", new Jint.Delegates.Func <object, double>(LUA_GTest));
        engine.Run("GTest([['3,3']])");
    }
Пример #13
0
        public override void Load(string code)
        {
            Engine = new JintEngine(Options.Ecmascript5)
                     .AllowClr(true);

            Engine.SetParameter("Commands", chatCommands)
            .SetParameter("DataStore", DataStore.GetInstance())
            .SetParameter("Find", Find.GetInstance())
            .SetParameter("GlobalData", GlobalData)
            .SetParameter("Plugin", this)
            .SetParameter("Server", Server.GetInstance())
            .SetParameter("ServerConsoleCommands", consoleCommands)
            .SetParameter("Util", Util.GetInstance())
            .SetParameter("Web", Web)
            .SetParameter("World", World.GetInstance())
            .SetFunction("importClass", new importit(importClass));

            try {
                Program = JintEngine.Compile(code, false);

                Globals = (from statement in Program.Statements
                           where statement.GetType() == typeof(FunctionDeclarationStatement)
                           select((FunctionDeclarationStatement)statement).Name).ToList <string>();

                Engine.Run(Program);
                State = PluginState.Loaded;
            } catch (Exception ex) {
                Logger.LogException(ex);
                State = PluginState.FailedToLoad;
            }

            PluginLoader.GetInstance().OnPluginLoaded(this);
        }
            public void Invoke(string methodName, object[] parameters)
            {
                var jint = new JintEngine();

                jint.DisableSecurity();
                jint.Visitor.Usings.CopyFrom(_extension._usings);
                jint.SetParameter("ExtensionHooks", _extension.Hooks);
                jint.Run(_extension._script);
                jint.CallFunction(methodName, parameters);
            }
Пример #15
0
        static void Main(string[] args)
        {
            JsGlobal   dummy;
            JintEngine eng  = new JintEngine();
            JsArray    root = null;


            root = new JsArray();
            eng.GlobalScope["PersistentRoot"] = root;


            eng.SetDebugMode(true);
            eng.SetFunction("log"
                            , new Jint.Delegates.Func <JsInstance, JsInstance>((JsInstance obj) =>
            {
                Console.WriteLine(obj == null?"NULL":obj.Value == null?"NULL 2":obj.Value.ToString());
                return(JsUndefined.Instance);
            }));


//            ((JsFunction)eng.GlobalScope["log"]).Execute(eng.Visitor, null, new JsInstance[] { new JsUndefined() });

            //   Console.WriteLine("\r\n" + eng.Run(File.ReadAllText(@"Scripts\func_jsonifier.js")));
            Console.WriteLine("\r\n" + eng.Run(File.ReadAllText(@"Scripts\test.js")));
            while (true)
            {
                Console.Write("] ");
                var l = Console.ReadLine();
                if (l.Length == 0)
                {
                    break;
                }
                var res = eng.Run(l);
                Console.WriteLine(res == null ? "<.NET NULL>" : res.ToString());
            }
            Console.WriteLine("Saving...");
            //            Console.ReadLine();
            //    root.Modify();
            //   s.Close();
            //    Console.Write("Enter to close");
            //  Console.ReadLine();
        }
Пример #16
0
        public static Dictionary <string, double> CalculateCommissions(string formula, int typeOfSale, string orderDate, double totalListPrice, double salePrice, double ytdSale, double totalEquipmentPrice, double totalToolingPrice, bool isXpert40orXactMachine)
        {
            var calculationEngine = new JintEngine();

            var functionCall = GetFunctionCall(typeOfSale, orderDate, totalListPrice, salePrice, ytdSale, totalEquipmentPrice, totalToolingPrice, isXpert40orXactMachine);

            Console.WriteLine(functionCall);

            calculationEngine.SetDebugMode(true).Run(formula);
            return((calculationEngine.Run(functionCall) as JsObject).ToDictionary(x => x.Key, x => x.Value.ToNumber()));
        }
Пример #17
0
        static void Main(string[] args)
        {
            var jint   = new JintEngine().DisableSecurity();
            var script = new StreamReader(@"scripts\test.js").ReadToEnd();

            jint.SetFunction("print", new Action <object>(Console.WriteLine));

            jint.Run(script);

            Console.ReadKey();
        }
Пример #18
0
        private void button1_Click(object sender, RoutedEventArgs e)
        {
            /* This is a terrible example of how to write
             * Silverlight, the focus is not on that, but on how to use Jint.
             * Please use MVVM in your own projects
             * */

            string name = userName.Text;

            engine.Run("alert('Hello " + name + ", from dynamically interpereted JavaScript on WP7!')");
        }
Пример #19
0
        public object execute(params KeyValuePair <string, object>[] parameters)
        {
            JintEngine executor = new JintEngine();

            foreach (KeyValuePair <String, object> KeyVal in parameters)
            {
                executor.SetParameter(KeyVal.Key, KeyVal.Value);
            }
            executor.AllowClr = true;
            executor.DisableSecurity();
            return(executor.Run(@compiledCode, false));
        }
Пример #20
0
 public bool Execute(string script, out object result)
 {
     try
     {
         result = m_engine.Run(script);
     }
     catch (Exception e)
     {
         result = null;
         Console.WriteLine("Script failed with error:\n*********************************************\n\t" + e.InnerException.Message + "\n*********************************************" + e.StackTrace);
         return(false);
     }
     return(true);
 }
Пример #21
0
        public ScriptRunner(ServiceManager svc, ExtensionClientManager clientManager)
        {
            _svc           = svc;
            _clientManager = clientManager;
            _engine.DisableSecurity();
            _engine.SetFunction("__svc_jsonCall", new Func <string, string, string>(ServiceManagerJsonCall));
            _engine.SetFunction("__ext_jsonCall", new Func <string, string, string, string>(ExtensionJsonCall));

            _preScript = string.Concat(
                Resources.json2,
                Resources.scriptrunner,
                JavaScriptInterface.GenerateJavaScriptWrapper(svc),
                clientManager.GetJavaScriptWrappers()
                );
            try
            {
                _engine.Run(_preScript);
            }
            catch (Exception ex)
            {
                LastException = ex;
            }
        }
Пример #22
0
    void Start()
    {
        JintEngine e = new JintEngine();

        e.SetFunction("log",
                      new Jint.Delegates.Action <object>((a) => Debug.Log(a)));

        e.SetFunction("add",
                      new Jint.Delegates.Func <double, double, double>((a, b) => a + b));

        TextAsset script = (TextAsset)Resources.Load("Test");

        e.Run(script.text);
    }
Пример #23
0
 public object RunString(string code)
 {
     try
     {
         return(engine.Run(code));
     }
     catch (Exception ex)
     {
         Log.Error(ex.InnerException != null ? (ex.Message + ": " + ex.InnerException.Message) : ex.Message);
         Log.Display();
         //Environment.Exit(1);
         return(null);
     }
 }
Пример #24
0
        static void Main2(string[] args)
        {
            List <MyClass> myClasses = new List <MyClass>();

            myClasses.Add(new MyClass("Some text", 2));
            myClasses.Add(new MyClass("More text", 1));

            var jintEngine = new JintEngine();

            jintEngine.SetParameter("myClasses", myClasses);

            Console.WriteLine("Result: {0}", jintEngine.Run("return myClasses[0].Description"));
            System.Console.ReadKey();
        }
Пример #25
0
 public override void Compile()
 {
     this.executor = null;
     this.executor = new JintEngine();
     foreach (MethodInfo method in this.GetType().GetMethods())
     {
         if (method.GetCustomAttributes(typeof(JSFunction), true) != null)
         {
             executor.SetFunction(method.Name, delegateOf(method));
         }
     }
     executor.AllowClr = true;
     executor.DisableSecurity();
     executor.Run(SourceCode, false);
 }
Пример #26
0
        public override void Load(string code = "")
        {
            try
            {
                Engine = new JintEngine(Options.Ecmascript5)
                         .AllowClr(true);

                Engine.SetParameter("Plugin", this)
                .SetParameter("Server", Fougerite.Server.GetServer())
                .SetParameter("DataStore", DataStore.GetInstance())
                .SetParameter("Data", Data.GetData())
                .SetParameter("Web", new Fougerite.Web())
                .SetParameter("Util", Util.GetUtil())
                .SetParameter("World", World.GetWorld())
                    #pragma warning disable 618
                .SetParameter("PluginCollector", GlobalPluginCollector.GetPluginCollector())
                    #pragma warning restore 618
                .SetParameter("Loom", Fougerite.Loom.Current)
                .SetParameter("JSON", Fougerite.JsonAPI.GetInstance)
                .SetParameter("MySQL", Fougerite.MySQLConnector.GetInstance)
                .SetParameter("SQLite", Fougerite.SQLiteConnector.GetInstance)
                .SetFunction("importClass", new importit(importClass));
                Program = JintEngine.Compile(code, false);

                Globals = (from statement in Program.Statements
                           where statement.GetType() == typeof(FunctionDeclarationStatement)
                           select((FunctionDeclarationStatement)statement).Name).ToList <string>();

                Engine.Run(Program);

                object author  = GetGlobalObject("Author");
                object about   = GetGlobalObject("About");
                object version = GetGlobalObject("Version");
                Author  = author == null || (string)author == "undefined" ? "Unknown" : author.ToString();
                About   = about == null || (string)about == "undefined" ? "" : about.ToString();
                Version = version == null || (string)version == "undefined" ? "1.0" : version.ToString();

                State = PluginState.Loaded;
            }
            catch (Exception ex)
            {
                Logger.LogError("[Error] Failed to load lua plugin: " + ex);
                State = PluginState.FailedToLoad;
                PluginLoader.GetInstance().CurrentlyLoadingPlugins.Remove(Name);
            }

            PluginLoader.GetInstance().OnPluginLoaded(this);
        }
Пример #27
0
        private static void ExecuteSunSpiderScript(string scriptName)
        {
            const string prefix = "Jint.Tests.SunSpider.";
            var script = prefix + scriptName;

            var assembly = Assembly.GetExecutingAssembly();
            var program = new StreamReader(assembly.GetManifestResourceStream(script)).ReadToEnd();

            var jint = new JintEngine(Options.Ecmascript5); // The SunSpider scripts doesn't work with strict mode
            var sw = new Stopwatch();
            sw.Start();

            jint.Run(program);

            Console.WriteLine(sw.Elapsed);
        }
Пример #28
0
        public static void Initialize(SmugglerOptions options)
        {
            if (options != null && !string.IsNullOrEmpty(options.TransformScript))
            {
                jint = new JintEngine()
                       .AllowClr(false)
                       .SetDebugMode(false)
                       .SetMaxRecursions(50)
                       .SetMaxSteps(10 * 1000);

                jint.Run(string.Format(@"
					function Transform(docInner){{
						return ({0}).apply(this, [docInner]);
					}};"                    , options.TransformScript));
            }
        }
Пример #29
0
        public override void Load(string code)
        {
            try {
                if (CoreConfig.GetInstance().GetBoolValue("javascript", "checkHash") && !code.VerifyMD5Hash())
                {
                    Logger.LogDebug($"[{GetType().Name}] MD5Hash not found for: {Name}");
                    State = PluginState.HashNotFound;
                }
                else
                {
                    Engine = new JintEngine(Options.Ecmascript5)
                             .AllowClr(true);

                    Engine.SetParameter("DataStore", DataStore.GetInstance())
                    .SetParameter("GlobalData", GlobalData)
                    .SetParameter("Plugin", this)
                    .SetParameter("Util", Util.GetInstance())
                    .SetParameter("Web", Web)
                    .SetFunction("importClass", new importit(importClass));

                    AssignVariables();

                    Program = JintEngine.Compile(code, false);

                    Globals = (from statement in Program.Statements
                               where statement.GetType() == typeof(FunctionDeclarationStatement)
                               select((FunctionDeclarationStatement)statement).Name).ToList();

                    Engine.Run(Program);

                    object author  = GetGlobalObject("Author");
                    object about   = GetGlobalObject("About");
                    object version = GetGlobalObject("Version");
                    Author  = author == null ? "" : author.ToString();
                    About   = about == null ? "" : about.ToString();
                    Version = version == null ? "" : version.ToString();

                    State = PluginState.Loaded;
                }
            } catch (Exception ex) {
                Logger.LogException(ex);
                State = PluginState.FailedToLoad;
            }

            PluginLoader.GetInstance().OnPluginLoaded(this);
        }
Пример #30
0
        private static void ExecuteSunSpiderScript(string scriptName)
        {
            const string prefix = "Jint.Tests.SunSpider.";
            var          script = prefix + scriptName;

            var assembly = Assembly.GetExecutingAssembly();
            var program  = new StreamReader(assembly.GetManifestResourceStream(script)).ReadToEnd();

            var jint = new JintEngine(Options.Ecmascript5); // The SunSpider scripts doesn't work with strict mode
            var sw   = new Stopwatch();

            sw.Start();

            jint.Run(program);

            Console.WriteLine(sw.Elapsed);
        }
Пример #31
0
        public static void Initialize(SmugglerOptions options)
        {
            if (options != null && !string.IsNullOrEmpty(options.TransformScript))
            {
                jint = new JintEngine()
                       .AllowClr(false)
                       .SetDebugMode(false)
                       .SetMaxRecursions(50)
                       .SetMaxSteps(options.MaxStepsForTransformScript);

                jint.Run(string.Format(@"
					function Transform(docInner){{
						return ({0}).apply(this, [docInner]);
					}};"                    , options.TransformScript));
            }

            propertiesTypeByName = new Dictionary <string, JTokenType>();
        }
Пример #32
0
        public static void Initialize(SmugglerOptions options)
        {
            if (options != null && !string.IsNullOrEmpty(options.TransformScript))
            {
                jint = new JintEngine()
                       .AllowClr(false)
                       .SetDebugMode(false)
                       .SetMaxRecursions(50)
                       .SetMaxSteps(options.MaxStepsForTransformScript);

                jint.Run(string.Format(@"
					function Transform(docInner){{
						return ({0}).apply(this, [docInner]);
					}};"                    , options.TransformScript));
            }

            propertiesByValue = new Dictionary <JsInstance, KeyValuePair <RavenJValue, object> >();
        }
Пример #33
0
        public Plugin(DirectoryInfo directory, string name, string code)
        {
            Name          = name;
            Code          = code;
            RootDirectory = directory;
            Timers        = new Dictionary <String, TimedEvent>();

            Engine = new JintEngine();
            Engine.AllowClr(true);

            InitGlobals();
            Engine.Run(code);
            try
            {
                Engine.CallFunction("On_PluginInit");
            }
            catch { }
        }
Пример #34
0
        public static void Main(String[] args)
        {
            Logger logger = new ConsoleLogger();

            Logging.SetLogger(logger);

            string     script = System.IO.File.ReadAllText(args[0]);
            JintEngine engine = new JintEngine();

            engine.SetParameter("language", "cs");
#if TEST_WINPHONE
            engine.SetParameter("platform", "winphone");
#else
            engine.SetParameter("platform", "windows");
#endif
            engine.SetParameter("util", new Util(engine));
            engine.Run(script);
        }
Пример #35
0
        static void Main(string[] args)
        {

            Stopwatch sw = new Stopwatch();

            // string script = new StreamReader(assembly.GetManifestResourceStream("Jint.Tests.Parse.coffeescript-debug.js")).ReadToEnd();
            JintEngine jint = new JintEngine()
                // .SetDebugMode(true)
                .DisableSecurity()
                .SetFunction("print", new Action<string>(Console.WriteLine))
                .SetFunction("write", new Action<string>(t => Console.WriteLine(t)))
                .SetFunction("stop", new Action(delegate() { Console.WriteLine(); }));
            sw.Reset();
            sw.Start();

            Console.WriteLine(jint.Run("Math.floor(1.5)"));
           

            Console.WriteLine("{0}ms", sw.ElapsedMilliseconds);
        }
Пример #36
0
        protected object Test(Options options, string script, Action<JintEngine> action)
        {
            var jint = new JintEngine(options)
                .AllowClr()
                .SetFunction("assert", new Action<object, object>(Assert.AreEqual))
                .SetFunction("fail", new Action<string>(Assert.Fail))
                .SetFunction("istrue", new Action<bool>(Assert.IsTrue))
                .SetFunction("isfalse", new Action<bool>(Assert.IsFalse))
                .SetFunction("print", new Action<string>(Console.WriteLine))
                .SetFunction("alert", new Action<string>(Console.WriteLine))
                .SetFunction("loadAssembly", new Action<string>(assemblyName => Assembly.Load(assemblyName)))
                .DisableSecurity();

            action(jint);

            var sw = new Stopwatch();
            sw.Start();

            var result = jint.Run(script);

            Console.WriteLine(sw.Elapsed);

            return result;
        }
Пример #37
0
 public void SecurityExceptionsShouldNotBeCaught() {
     const string script = @"
         try {
             var sb = new System.Text.StringBuilder();
             fail('should not have reached this code');
         } 
         catch (e) {
             fail('should not have reached this code');
         }                
     ";
     var engine = new JintEngine();
     engine.Run(script);
 }
Пример #38
0
        public void ShouldHandleArrayIndexOf()
        {

            var jint = new JintEngine()
            .SetDebugMode(true)
            .SetFunction("assert", new Action<object, object>(Assert.AreEqual))
            .SetFunction("print", new Action<string>(System.Console.WriteLine));

            jint.Run(@"
                var days = ['mon', 'tue', 'wed'];
                assert(1, days.indexOf('tue'));            
            ");
        }
Пример #39
0
        public void ClrNullShouldBeConverted() {

            var jint = new JintEngine()
            .SetDebugMode(true)
            .SetFunction("assert", new Action<object, object>(Assert.AreEqual))
            .SetFunction("print", new Action<string>(System.Console.WriteLine))
            .SetParameter("foo", null);

            // strict equlity ecma 262.3 11.9.6 x === y: If type of (x) is null return true.
            jint.Run(@"
                assert(true, foo == null);
                assert(true, foo === null);
            ");
        }
Пример #40
0
        public void ShouldBreakInLoops() {
            var jint = new JintEngine()
                .SetDebugMode(true);
            jint.BreakPoints.Add(new BreakPoint(4, 22)); // x += 1;

            jint.Step += (sender, info) => Assert.IsNotNull(info.CurrentStatement);

            bool brokeInLoop = false;

            jint.Break += (sender, info) => {
                Assert.IsNotNull(info.CurrentStatement);
                Assert.IsTrue(info.CurrentStatement is ExpressionStatement);
                Assert.AreEqual(7, Convert.ToInt32(info.Locals["x"].Value));

                brokeInLoop = true;
            };

            jint.Run(@"
                var x = 7;
                for(var i=0; i<3; i++) { 
                    x += i; 
                    return;
                }
            ");

            Assert.IsTrue(brokeInLoop);
        }
Пример #41
0
        public void ShouldRunInRun() {
            var filename = Path.GetTempFileName();
            File.WriteAllText(filename, "a='bar'");

            var engine = new JintEngine().AddPermission(new FileIOPermission(PermissionState.Unrestricted));
            engine.AllowClr();
            engine.SetFunction("load", new Action<string>(delegate(string fileName) { using (var reader = File.OpenText(fileName)) { engine.Run(reader); } }));
            engine.SetFunction("print", new Action<string>(Console.WriteLine));
            engine.Run("var a='foo'; load('" + JintEngine.EscapteStringLiteral(filename) + "'); print(a);");

            File.Delete(filename);
        }
Пример #42
0
        public void ShouldEvaluateIndexersAsClrFields() {
            var box = new Box { width = 10, height = 20 };

            var jint = new JintEngine()
            .SetDebugMode(true)
            .AllowClr()
            .SetParameter("box", box);

            Assert.AreEqual(10, jint.Run("return box.width"));
            Assert.AreEqual(10, jint.Run("return box['width']"));
            jint.Run("box['height'] = 30;");

            Assert.AreEqual(30, box.height);

            jint.Run("box.height = 18;");

            Assert.AreEqual(18, box.height);

        }
Пример #43
0
        public void ShouldNotThrowOverflowExpcetion() {
            var jint = new JintEngine();
            jint.SetParameter("box", new Box());
            jint.Run("box.Write(new Date);");

        }
Пример #44
0
        public void ShouldHandleClrArrays() {
            var values = new int[] { 2, 3, 4, 5, 6, 7 };
            var jint = new JintEngine()
            .SetDebugMode(true)
            .SetParameter("a", values)
            .AllowClr();

            Assert.AreEqual(3, jint.Run("a[1];"));
            jint.Run("a[1] = 4");
            Assert.AreEqual(4, jint.Run("a[1];"));
            Assert.AreEqual(4, values[1]);

        }
Пример #45
0
        public void ShouldHandleClrDictionaries() {
            var dic = new Dictionary<string, int> { { "a", 1 }, { "b", 2 }, { "c", 3 } };

            var jint = new JintEngine()
            .AllowClr()
            .SetDebugMode(true)
            .SetParameter("dic", dic);

            Assert.AreEqual(1, jint.Run("return dic['a'];"));
            jint.Run("dic['a'] = 4");
            Assert.AreEqual(4, jint.Run("return dic['a'];"));
            Assert.AreEqual(4, dic["a"]);
        }
Пример #46
0
        public void ShouldHandleMultipleRunsInSameScope() {
            var jint = new JintEngine()
                .SetFunction("assert", new Action<object, object>(Assert.AreEqual))
                .SetFunction("print", new Action<string>(System.Console.WriteLine));

            jint.Run(@" var g = []; function foo() { assert(0, g.length); }");
            jint.Run(@" foo();");
        }
Пример #47
0
        public void ShouldHandleStrictMode() {
            //Strict mode enabled
            var engine = new JintEngine(Options.Strict)
            .SetFunction("assert", new Action<object, object>(Assert.AreEqual))
            ;
            engine.Run(@"
            try{
                var test1=function(eval){}
                //should not execute the next statement
                assert(true, false);
            }
            catch(e){
                assert(true, true);
            }
            try{
                (function() {
                    function test2(eval){}
                    //should not execute the next statement
                    assert(true, false);
                })();
            }
            catch(e){
                assert(true, true);
            }");

            //Strict mode disabled
            engine = new JintEngine(Options.Ecmascript3)
            .SetFunction("assert", new Action<object, object>(Assert.AreEqual))
            ;
            engine.Run(@"
            try{
                var test1=function(eval){}
                assert(true, true);
            }
            catch(e){
                assert(true, false);
            }
            try{
                (function() {
                    function test2(eval){}
                    assert(true, true);
                })();
            }
            catch(e){
                assert(true, false);
            }");
        }
Пример #48
0
        public void ShouldExecuteEcmascript5TestsScripts() {
            var assembly = Assembly.GetExecutingAssembly();
            var extensions = new StreamReader(assembly.GetManifestResourceStream("Jint.Tests.extensions.js")).ReadToEnd();

            var resources = new List<string>();
            foreach (var resx in assembly.GetManifestResourceNames()) {
                // Ignore scripts not in /Scripts
                if (!resx.Contains(".ecma_5.") || resx.Contains(".Scripts.")) {
                    continue;
                }

                resources.Add(resx);
            }

            resources.Sort();

            //Run the shell first if defined
            string additionalShell = null;
            if (resources[resources.Count - 1].EndsWith("shell.js")) {
                additionalShell = resources[resources.Count - 1];
                resources.RemoveAt(resources.Count - 1);
                additionalShell = new StreamReader(assembly.GetManifestResourceStream(additionalShell)).ReadToEnd();
            }

            foreach (var resx in resources) {
                var program = new StreamReader(assembly.GetManifestResourceStream(resx)).ReadToEnd();
                Console.WriteLine(Path.GetFileNameWithoutExtension(resx));

                var jint = new JintEngine()
                .SetDebugMode(true)
                .SetFunction("print", new Action<string>(System.Console.WriteLine));

                jint.Run(extensions);
                //jint.Run(shell);
                jint.Run("test = _test;");
                if (additionalShell != null) {
                    jint.Run(additionalShell);
                }

                try {
                    jint.Run(program);
                }
                catch (Exception e) {
                    jint.Run("print('Error in : ' + gTestfile)");
                    Console.WriteLine(e.Message);
                }
            }
        }
Пример #49
0
        public void ShouldNotWrapJsInstancesIfExpected() {
            var engine = new JintEngine()
            .SetFunction("evaluate", new Func<JsNumber, JsInstance, JsString>(GiveMeJavascript));

            const string script = @"
                var r = evaluate(3, [1,2]);
                return r;
            ";

            var r = engine.Run(script, false);

            Assert.IsTrue(r is JsString);
            Assert.AreEqual("31,2", r.ToString());
        }
Пример #50
0
 public void ShouldNotReproduceBug85418() {
     var engine = new JintEngine();
     engine.SetParameter("a", 4);
     Assert.AreEqual(4, engine.Run("a"));
     Assert.AreEqual(4d, engine.Run("4"));
     Assert.AreEqual(true, engine.Run("a == 4"));
     Assert.AreEqual(true, engine.Run("4 == 4"));
     Assert.AreEqual(true, engine.Run("a == a"));
 }
Пример #51
0
        public void ShouldRetainGlobalsThroughRuns() {
            var jint = new JintEngine();

            jint.Run("var i = 3; function square(x) { return x*x; }");

            Assert.AreEqual(3d, jint.Run("return i;"));
            Assert.AreEqual(9d, jint.Run("return square(i);"));
        }
Пример #52
0
        public void ObjectShouldBePassedToDelegates() {
            var engine = new JintEngine();
            engine.SetFunction("render", new Action<object>(s => Console.WriteLine(s)));

            const string script =
                @"
                var contact = {
                    'Name': 'John Doe',
                    'PhoneNumbers': [ 
                    {
                       'Location': 'Home',
                       'Number': '555-555-1234'
                    },
                    {
                        'Location': 'Work',
                        'Number': '555-555-9999 Ext. 123'
                    }
                    ]
                };

                render(contact.Name);
                render(contact.toString());
                render(contact);
            ";

            engine.Run(script);
        }
Пример #53
0
        public void ShouldBreakOnCondition() {
            JintEngine jint = new JintEngine()
            .SetDebugMode(true);
            jint.BreakPoints.Add(new BreakPoint(4, 22, "x == 2;")); // return x*x;

            jint.Step += (sender, info) => Assert.IsNotNull(info.CurrentStatement);

            bool brokeOnReturn = false;

            jint.Break += (sender, info) => {
                Assert.IsNotNull(info.CurrentStatement);
                Assert.IsTrue(info.CurrentStatement is ReturnStatement);
                Assert.AreEqual(2, Convert.ToInt32(info.Locals["x"].Value));

                brokeOnReturn = true;
            };

            jint.Run(@"
                var i = 3; 
                function square(x) { 
                    return x*x; 
                }
                
                square(1);
                square(2);
                square(3);
            ");

            Assert.IsTrue(brokeOnReturn);
        }
Пример #54
0
        public void ShouldThrowErrorWhenAssigningUndeclaredVariableInStrictMode() {
            var engine = new JintEngine(Options.Ecmascript5 | Options.Strict)
                .SetFunction("assert", new Action<object, object>(Assert.AreEqual));
            var x = engine.Run(@"
                try {
                    x = 1;
                    return x;
                } catch(e) {
                    return 'error';
                }
            ");

            Assert.AreEqual("error", x);
        }
Пример #55
0
        public void ShouldHandleNativeTypes() {

            var jint = new JintEngine()
            .SetDebugMode(true)
            .SetFunction("assert", new Action<object, object>(Assert.AreEqual))
            .SetFunction("print", new Action<string>(System.Console.WriteLine))
            .SetParameter("foo", "native string");

            jint.Run(@"
                assert(7, foo.indexOf('string'));            
            ");
        }
Пример #56
0
 public void ShouldReturnDelegateForFunctions() {
     const string script = "var ccat=function (arg1,arg2){ return arg1+' '+arg2; }";
     JintEngine engine = new JintEngine().SetFunction("print", new Action<string>(Console.WriteLine));
     engine.Run(script);
     Assert.AreEqual("Nicolas Penin", engine.CallFunction("ccat", "Nicolas", "Penin"));
 }
Пример #57
0
        public void RunMozillaTests(string folder) {
            var assembly = Assembly.GetExecutingAssembly();
            var shell = new StreamReader(assembly.GetManifestResourceStream("Jint.Tests.shell.js")).ReadToEnd();
            var extensions = new StreamReader(assembly.GetManifestResourceStream("Jint.Tests.extensions.js")).ReadToEnd();

            var resources = new List<string>();
            foreach (var resx in assembly.GetManifestResourceNames()) {
                // Ignore scripts not in /Scripts
                if (!resx.Contains(".ecma_3.") || !resx.Contains(folder)) {
                    continue;
                }

                resources.Add(resx);
            }

            resources.Sort();

            //Run the shell first if defined
            string additionalShell = null;
            if (resources[resources.Count - 1].EndsWith("shell.js")) {
                additionalShell = resources[resources.Count - 1];
                resources.RemoveAt(resources.Count - 1);
                additionalShell = new StreamReader(assembly.GetManifestResourceStream(additionalShell)).ReadToEnd();
            }

            foreach (var resx in resources) {
                var program = new StreamReader(assembly.GetManifestResourceStream(resx)).ReadToEnd();
                Console.WriteLine(Path.GetFileNameWithoutExtension(resx));

                StringBuilder output = new StringBuilder();
                StringWriter sw = new StringWriter(output);

                var jint = new JintEngine(Options.Ecmascript5) // These tests doesn't work with strict mode
                .SetDebugMode(true)
                .SetFunction("print", new Action<string>(sw.WriteLine));

                jint.Run(extensions);
                jint.Run(shell);
                jint.Run("test = _test;");
                if (additionalShell != null) {
                    jint.Run(additionalShell);
                }

                try {
                    jint.Run(program);
                    string result = sw.ToString();
                    if (result.Contains("FAILED")) {
                        Assert.Fail(result);
                    }
                }
                catch (Exception e) {
                    jint.Run("print('Error in : ' + gTestfile)");
                    Assert.Fail(e.Message);
                }
            }
        }
Пример #58
0
 public void ShouldNotAccessClr() {
     const string script = @"
         var sb = new System.Text.StringBuilder();
         sb.Append('hi, mom');
         sb.Append(3);	
         sb.Append(true);
         return sb.ToString();
         ";
     var engine = new JintEngine();
     Assert.AreEqual("hi, mom3True", engine.Run(script));
 }
Пример #59
0
        public void TestPerformance()
        {
            string[] tests = { "3d-cube", "3d-morph", "3d-raytrace", "access-binary-trees", "access-fannkuch", "access-nbody", "access-nsieve", "bitops-3bit-bits-in-byte", "bitops-bits-in-byte", "bitops-bitwise-and", "bitops-nsieve-bits", "controlflow-recursive", "crypto-aes", "crypto-md5", "crypto-sha1", "date-format-tofte", "date-format-xparb", "math-cordic", "math-partial-sums", "math-spectral-norm", "regexp-dna", "string-base64", "string-fasta", "string-tagcloud", "string-unpack-code", "string-validate-input" };

            var assembly = Assembly.GetExecutingAssembly();
            Stopwatch sw = new Stopwatch();

            foreach (var test in tests) {
                string script;

                try {
                    script = new StreamReader(assembly.GetManifestResourceStream("Jint.Tests.SunSpider." + test + ".js")).ReadToEnd();
                    if (String.IsNullOrEmpty(script)) {
                        continue;
                    }
                }
                catch {
                    Console.WriteLine("{0}: ignored", test);
                    continue;
                }

                JintEngine jint = new JintEngine()
                    //.SetDebugMode(true)
                    .DisableSecurity();

                sw.Reset();
                sw.Start();

                jint.Run(script);

                Console.WriteLine("{0}: {1}ms", test, sw.ElapsedMilliseconds);
            }
        }
Пример #60
0
        public void ShouldEvaluateIndexersAsClrProperties()
        {
            var box = new Box { Width = 10, Height = 20 };

            var jint = new JintEngine()
            .SetDebugMode(true)
            .SetParameter("box", box);

            Assert.AreEqual(10, jint.Run("return box.Width"));
            Assert.AreEqual(10, jint.Run("return box['Width']"));
            jint.Run("box['Height'] = 30;");

            Assert.AreEqual(30, box.Height);

            jint.Run("box.Height = 18;");
            Assert.AreEqual(18, box.Height);
        }