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); }
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); }
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); } }
protected override object RunFile(JintEngine ctx, string fileName) { if (Debugger.IsAttached) return base.RunFile(ctx, fileName); else return Timeout.Run(() => base.RunFile(ctx, fileName), ScriptTimeout); }
// Constructor public MainPage() { InitializeComponent(); engine = new JintEngine(); engine.SetFunction("alert", new Action<string>(t => MessageBox.Show(t))); }
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); } }
public JintRuntime(JintEngine engine) { if (engine == null) throw new ArgumentNullException("engine"); _engine = engine; Global = new JsGlobal(this, engine); GlobalScope = Global.GlobalScope; }
private static void ExecuteSunSpider() { const string fileName = @"..\..\..\Jint.Tests\SunSpider\Tests\access-fannkuch.js"; var jint = new JintEngine(); #if false jint.ExecuteFile(fileName); Console.WriteLine("Attach"); Console.ReadLine(); jint.ExecuteFile(fileName); #else jint.ExecuteFile(fileName); var times = new TimeSpan[20]; int timeOffset = 0; var lowest = new TimeSpan(); // Perform the iterations. for (int i = 0; ; i++) { long memoryBefore = GC.GetTotalMemory(true); var stopwatch = Stopwatch.StartNew(); jint.ExecuteFile(fileName); var elapsed = stopwatch.Elapsed; long memoryAfter = GC.GetTotalMemory(false); times[timeOffset++] = elapsed; if (timeOffset == times.Length) timeOffset = 0; if (times[times.Length - 1].Ticks != 0) { var average = new TimeSpan(times.Sum(p => p.Ticks) / times.Length); if (lowest.Ticks == 0 || average.Ticks < lowest.Ticks) lowest = average; Console.WriteLine( "This run: {0}, average: {1}, lowest: {2}, memory usage: {3}", elapsed.ToString("s\\.fffff"), average.ToString("s\\.fffff"), lowest.ToString("s\\.fffff"), NiceMemory(memoryAfter - memoryBefore) ); } } #endif }
public void ShouldNotRunInRun() { var filename = Path.GetTempFileName(); File.WriteAllText(filename, "a='bar'"); var engine = new JintEngine().AddPermission(new FileIOPermission(PermissionState.None)); engine.AllowClr(); engine.SetFunction("load", new Action<string>(p => engine.ExecuteFile(p))); engine.SetFunction("print", new Action<string>(Console.WriteLine)); engine.Execute("var a='foo'; load('" + EscapeStringLiteral(filename) + "'); print(a);"); }
static void Main(string[] args) { string line; var jint = new JintEngine(); jint.SetFunction("print", new Action<object>(s => { Console.ForegroundColor = ConsoleColor.Blue; Console.Write(s); Console.ResetColor(); })); #pragma warning disable 612,618 jint.SetFunction("import", new Action<string>(s => { Assembly.LoadWithPartialName(s); })); #pragma warning restore 612,618 jint.DisableSecurity(); while (true) { Console.Write("jint > "); StringBuilder script = new StringBuilder(); while (String.Empty != (line = Console.ReadLine())) { if (line.Trim() == "exit") { return; } if (line.Trim() == "reset") { jint = new JintEngine(); break; } if (line.Trim() == "help" || line.Trim() == "?") { Console.WriteLine(@"Jint Shell"); Console.WriteLine(@""); Console.WriteLine(@"exit - Quits the application"); Console.WriteLine(@"import(assembly) - assembly: String containing the partial name of a .NET assembly to load"); Console.WriteLine(@"reset - Initialize the current script"); Console.WriteLine(@"print(output) - Prints the specified output to the console"); Console.WriteLine(@""); break; } script.AppendLine(line); } Console.SetError(new StringWriter(new StringBuilder())); try { jint.Execute(script.ToString()); } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine(e.Message); Console.ResetColor(); } Console.WriteLine(); } }
protected override object RunFile(JintEngine ctx, string fileName) { base.RunFile(ctx, fileName); string suitePath = Path.Combine( Path.GetDirectoryName(fileName), "underscore-suite.js" ); return ctx.ExecuteFile(suitePath); }
protected override object RunFile(JintEngine ctx, string fileName) { string shellPath = Path.Combine( Path.GetDirectoryName(fileName), "shell.js" ); if (File.Exists(shellPath)) ctx.ExecuteFile(shellPath); return base.RunFile(ctx, fileName); }
private static BoundProgram Compile(string script) { var programSyntax = JintEngine.ParseProgram(script); var engine = new JintEngine(); var visitor = new BindingVisitor(engine.TypeSystem.CreateScriptBuilder(null)); programSyntax.Accept(visitor); var program = SquelchPhase.Perform(visitor.Program); DefiniteAssignmentPhase.Perform(program); return program; }
protected override void RunInclude(JintEngine engine, string fileName) { string source; if (!_includeCache.TryGetValue(fileName, out source)) { source = GetSpecialInclude(fileName) ?? File.ReadAllText(Path.Combine(_libPath, fileName)); _includeCache.Add(fileName, source); } engine.Execute(source, fileName); }
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); }
protected virtual JintEngine CreateContext(Action<string> errorAction) { var ctx = new JintEngine(); Action<string> failAction = Assert.Fail; Action<string> printAction = message => Trace.WriteLine(message); Action<string> includeAction = file => RunInclude(ctx, file); ctx.SetFunction("$FAIL", failAction); ctx.SetFunction("ERROR", errorAction); ctx.SetFunction("$ERROR", errorAction); ctx.SetFunction("$PRINT", printAction); ctx.SetFunction("$INCLUDE", includeAction); return ctx; }
public void ShouldRunInRun() { var filename = Path.GetTempFileName(); File.WriteAllText(filename, "a='bar'"); var engine = new JintEngine().AddPermission(new FileIOPermission(PermissionState.Unrestricted)); engine.AllowClr(); // The DLR compiler won't compile with permissions set engine.DisableSecurity(); engine.SetFunction("load", new Action<string>(p => engine.ExecuteFile(p))); engine.SetFunction("print", new Action<string>(Console.WriteLine)); engine.Execute("var a='foo'; load('" + EscapeStringLiteral(filename) + "'); print(a);"); File.Delete(filename); }
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); }
private static void ExecuteV8() { const string fileName = @"..\..\..\Jint.Benchmarks\Suites\V8\raytrace.js"; var jint = new JintEngine(); jint.DisableSecurity(); jint.ExecuteFile(@"..\..\..\Jint.Benchmarks\Suites\V8\base.js"); jint.SetFunction( "NotifyResult", new Action<string, string>((name, result) => { }) ); jint.SetFunction( "NotifyError", new Action<string, object>((name, error) => { }) ); string score = null; jint.SetFunction( "NotifyScore", new Action<string>(p => { score = p; }) ); jint.ExecuteFile(fileName); Console.WriteLine("Attach"); Console.ReadLine(); jint.Execute(@" BenchmarkSuite.RunSuites({ NotifyResult: NotifyResult, NotifyError: NotifyError, NotifyScore: NotifyScore, Runs: 1 });"); Console.WriteLine("Score: " + score); }
public JsGlobal(JintRuntime runtime, JintEngine engine) { if (runtime == null) throw new ArgumentNullException("runtime"); _runtime = runtime; Id.SeedGlobal(this); PrototypeSink = CreatePrototypeSink(); RootSchema = new JsSchema(); Engine = engine; // The Random instance is used by Math to generate random numbers. Random = new Random(); BuildEnvironment(); GlobalScope = CreateGlobalScope(); Marshaller = new Marshaller(runtime, this); Marshaller.Initialize(); }
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; }
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); "); }
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); }
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); }
public void ShouldHandleIndexedProperties() { const string program = @" var userObject = { }; userObject['lastLoginTime'] = new Date(); return userObject.lastLoginTime; "; object result = new JintEngine().Run(program); Assert.IsNotNull(result); Assert.IsInstanceOfType(result, typeof(DateTime)); }
public JavascriptEngine() { engine = new JintEngine(Options.Ecmascript5 | Options.Strict); engine.SetFunction("include", (Func <string, object>)Include); }
static void Main3(string[] args) { JintEngine engine = new JintEngine(); engine.DisableSecurity(); engine.Run("1;"); Marshaller marshal = engine.Global.Marshaller; JsConstructor ctor = engine.Global.Marshaller.MarshalType(typeof(Baz)); ((JsObject)engine.Global)["Baz"] = ctor; ((JsObject)engine.Global)["Int32"] = engine.Global.Marshaller.MarshalType(typeof(Int32)); JsObject o = new JsObject(); o["abc"] = new JsString("sure", engine.Global.StringClass.PrototypeProperty); engine.SetParameter("o", o); engine.SetParameter("ts1", new TimeSpan(1000)); engine.SetParameter("ts2", new TimeSpan(2000)); engine.Run(@" if (ts1 <= ts2) { System.Console.WriteLine('ts1 < ts2'); } System.Console.WriteLine('{0}',o.abc); System.Console.WriteLine('{0}',Jint.Temp.InfoType.Name); "); engine.Run(@" System.Console.WriteLine('=========FEATURES=========='); var test = new Baz(); var val; System.Console.WriteLine('test.Name: {0}', test.Name); System.Console.WriteLine('test.CurrentValue: {0}', test.CurrentValue); System.Console.WriteLine('Update object using method'); test.SetTimestamp(System.DateTime.Now); System.Console.WriteLine('test.CurrentValue: {0}', test.CurrentValue); System.Console.WriteLine('Update object using property'); test.CurrentValue = new System.DateTime(1980,1,1); System.Console.WriteLine('test.CurrentValue: {0}', test.CurrentValue); System.Console.WriteLine('Update object using field'); test.t = new System.DateTime(1980,1,2); System.Console.WriteLine('test.CurrentValue: {0}', test.CurrentValue); System.Console.WriteLine('Is instance of Baz: {0}', test instanceof Baz ? 'yes' : 'no' ); System.Console.WriteLine('Is instance of Object: {0}', test instanceof Object ? 'yes' : 'no' ); System.Console.WriteLine('Is instance of String: {0}', test instanceof String ? 'yes' : 'no' ); System.Console.WriteLine('Constant field Int32.MaxValue: {0}', Int32.MaxValue); System.Console.WriteLine('========= INHERITANCE FROM A CLR TYPE =========='); function Foo(name,desc) { Baz.call(this,name); this.Description = desc; this.SetTimestamp(System.DateTime.Now); } (function(){ var func = new Function(); func.prototype = Baz.prototype; Foo.prototype = new func(); Foo.prototype.constructor = Foo; })(); Foo.prototype.PrintInfo = function() { System.Console.WriteLine('{0}: {1} ({2})', this.Name,this.Description,this.t); } var foo = new Foo('Gib','Mega mann'); foo.PrintInfo(); System.Console.WriteLine('========= DUMP OBJECT =========='); function ___StandAlone() {} for (var prop in foo){ try { val = foo[prop]; } catch(err) { val = 'Exception: ' + err.toString(); } System.Console.WriteLine('{0} = {1}',prop,val.toString()); } System.Console.WriteLine('========= DUMP PROTOTYPE =========='); foo = Foo.prototype; for (var prop in foo){ try { val = foo[prop]; } catch(err) { val = 'Exception: ' + err.toString(); } System.Console.WriteLine('{0} = {1}',prop,val.toString()); } System.Console.WriteLine('========= DUMP OBJECT PROTOTYPE =========='); foo = Object.prototype; for (var prop in foo){ try { val = foo[prop]; } catch(err) { val = 'Exception: ' + err.toString(); } System.Console.WriteLine('{0} = {1}',prop,val.toString()); } System.Console.WriteLine('========= TYPE INFORMATION =========='); //System.Console.WriteLine('[{1}] {0}', test.GetType().FullName, test.GetType().GUID); for(var prop in Baz) { try { val = Baz[prop]; } catch (err) { val = 'Exception: ' + err.toString(); } System.Console.WriteLine('{0} = {1}',prop,val); } System.Console.WriteLine('========= PERFORMANCE =========='); "); int ticks = Environment.TickCount; engine.Run(@" var temp; for (var i = 0; i < 100000; i++) temp = new Baz('hi'); "); Console.WriteLine("new objects: {0} ms", Environment.TickCount - ticks); ticks = Environment.TickCount; engine.Run(@" var temp = new Baz(); var val = ToInt32(20); System.Console.WriteLine('Debug: {0} + {1} = {2}', '10', val, temp.Foo('10',val)); for (var i = 0; i < 100000; i++) temp.Foo('10',val); "); Console.WriteLine("method call in {0} ms", Environment.TickCount - ticks); ticks = Environment.TickCount; engine.Run(@" var temp = new Baz(); for (var i = 0; i < 100000; i++) temp.Foo(); "); Console.WriteLine("method call without args {0} ms", Environment.TickCount - ticks); ticks = Environment.TickCount; engine.Run(@" var temp = new Baz(); for (var i = 0; i < 100000; i++) temp.CurrentValue; "); Console.WriteLine("get property {0} ms", Environment.TickCount - ticks); ticks = Environment.TickCount; engine.Run(@" var temp = new Baz(); for (var i = 0; i < 100000; i++) temp.t; "); Console.WriteLine("get field {0} ms", Environment.TickCount - ticks); ticks = Environment.TickCount; engine.Run(@" for (var i = 0; i < 100000; i++) /**/1; "); Console.WriteLine("empty loop {0} ms", Environment.TickCount - ticks); //JsInstance inst = ctor.Construct(new JsInstance[0], null, visitor); Console.ReadKey(); return; }
public void LoadPlugins(Player p) { Hooks.ResetHooks(); this.ParsePlugin(); foreach (Plugin plugin in this.plugins) { try { this.interpreter.Run(plugin.Code); foreach (Statement current in JintEngine.Compile(plugin.Code, false).Statements) { if (current.GetType() == typeof(FunctionDeclarationStatement)) { FunctionDeclarationStatement functionDeclarationStatement = (FunctionDeclarationStatement)current; if (functionDeclarationStatement != null) { if (functionDeclarationStatement.Name == "On_ServerInit") { Hooks.OnServerInit += new Hooks.ServerInitDelegate(plugin.OnServerInit); } else if (functionDeclarationStatement.Name == "On_PluginInit") { Hooks.OnPluginInit += new Hooks.PluginInitHandlerDelegate(plugin.OnPluginInit); } else if (functionDeclarationStatement.Name == "On_ServerShutdown") { Hooks.OnServerShutdown += new Hooks.ServerShutdownDelegate(plugin.OnServerShutdown); } else if (functionDeclarationStatement.Name == "On_ItemsLoaded") { Hooks.OnItemsLoaded += new Hooks.ItemsDatablocksLoaded(plugin.OnItemsLoaded); } else if (functionDeclarationStatement.Name == "On_TablesLoaded") { Hooks.OnTablesLoaded += new Hooks.LootTablesLoaded(plugin.OnTablesLoaded); } else if (functionDeclarationStatement.Name == "On_Chat") { Hooks.OnChat += new Hooks.ChatHandlerDelegate(plugin.OnChat); } else if (functionDeclarationStatement.Name == "On_Console") { Hooks.OnConsoleReceived += new Hooks.ConsoleHandlerDelegate(plugin.OnConsole); } else if (functionDeclarationStatement.Name == "On_Command") { Hooks.OnCommand += new Hooks.CommandHandlerDelegate(plugin.OnCommand); } else if (functionDeclarationStatement.Name == "On_PlayerConnected") { Hooks.OnPlayerConnected += new Hooks.ConnectionHandlerDelegate(plugin.OnPlayerConnected); } else if (functionDeclarationStatement.Name == "On_PlayerDisconnected") { Hooks.OnPlayerDisconnected += new Hooks.DisconnectionHandlerDelegate(plugin.OnPlayerDisconnected); } else if (functionDeclarationStatement.Name == "On_PlayerKilled") { Hooks.OnPlayerKilled += new Hooks.KillHandlerDelegate(plugin.OnPlayerKilled); } else if (functionDeclarationStatement.Name == "On_PlayerHurt") { Hooks.OnPlayerHurt += new Hooks.HurtHandlerDelegate(plugin.OnPlayerHurt); } else if (functionDeclarationStatement.Name == "On_PlayerSpawning") { Hooks.OnPlayerSpawning += new Hooks.PlayerSpawnHandlerDelegate(plugin.OnPlayerSpawn); } else if (functionDeclarationStatement.Name == "On_PlayerSpawned") { Hooks.OnPlayerSpawned += new Hooks.PlayerSpawnHandlerDelegate(plugin.OnPlayerSpawned); } else if (functionDeclarationStatement.Name == "On_PlayerGathering") { Hooks.OnPlayerGathering += new Hooks.PlayerGatheringHandlerDelegate(plugin.OnPlayerGathering); } else if (functionDeclarationStatement.Name == "On_EntityHurt") { Hooks.OnEntityHurt += new Hooks.EntityHurtDelegate(plugin.OnEntityHurt); } else if (functionDeclarationStatement.Name == "On_EntityDecay") { Hooks.OnEntityDecay += new Hooks.EntityDecayDelegate(plugin.OnEntityDecay); } else if (functionDeclarationStatement.Name == "On_EntityDeployed") { Hooks.OnEntityDeployed += new Hooks.EntityDeployedDelegate(plugin.OnEntityDeployed); } else if (functionDeclarationStatement.Name == "On_NPCHurt") { Hooks.OnNPCHurt += new Hooks.HurtHandlerDelegate(plugin.OnNPCHurt); } else if (functionDeclarationStatement.Name == "On_NPCKilled") { Hooks.OnNPCKilled += new Hooks.KillHandlerDelegate(plugin.OnNPCKilled); } else if (functionDeclarationStatement.Name == "On_BlueprintUse") { Hooks.OnBlueprintUse += new Hooks.BlueprintUseHandlerDelagate(plugin.OnBlueprintUse); } else if (functionDeclarationStatement.Name == "On_DoorUse") { Hooks.OnDoorUse += new Hooks.DoorOpenHandlerDelegate(plugin.OnDoorUse); } } } } } catch (Exception) { string arg = "Can't load plugin : " + plugin.Path.Remove(0, plugin.Path.LastIndexOf("\\") + 1); if (p != null) { p.Message(arg); } else { Server.GetServer().Broadcast(arg); } } } }
void init() { PythonEngine.Inst.init(); jint = new JintEngine(); string absUserDir = Directory.GetCurrentDirectory() + "/Js"; jint.AddPermission(new FileIOPermission(FileIOPermissionAccess.AllAccess, absUserDir)); //set some simple funcitons. Func <object, int> alert = delegate(object s) { MessageBox.Show(s.ToString()); return(0); }; Func <string, double, string, double[]> ema = delegate(string label, double days, string outLabel) { if (arrays.ContainsKey(label)) { double[] inputs = arrays[label]; double[] outputs = MathUtil.calcEMA(inputs, days); addArray(outLabel, outputs); return(outputs); } return(null); }; Func <string, string, string, double[]> diff = delegate(string label0, string label1, string outLabel) { if (arrays.ContainsKey(label0) && arrays.ContainsKey(label1)) { double[] inputs0 = arrays[label0]; double[] inputs1 = arrays[label1]; double[] outputs = MathUtil.calcDiff(inputs0, inputs1); addArray(outLabel, outputs); return(outputs); } return(null); }; //tell canvas to line Func <string, double, double, double, double, double, double, int> line = delegate(string label, double part, double r, double g, double b, double a, double thickness) { if (!arrays.ContainsKey(label)) { return(1); } Color c = new Color() { R = (byte)r, G = (byte)g, B = (byte)b, A = (byte)a }; canvas.addDrawingObj(label, arrays[label], (int)part, c, thickness, DrawingObjectType.Line); return(0); }; Func <string, double, double, double, double, double, double, int> zeroBars = delegate(string label, double part, double r, double g, double b, double a, double thickness) { if (!arrays.ContainsKey(label)) { return(1); } Color c = new Color() { R = (byte)r, G = (byte)g, B = (byte)b, A = (byte)a }; canvas.addDrawingObj(label, arrays[label], (int)part, c, thickness, DrawingObjectType.zVLines); return(0); }; ////kdj('close','high','low',9,'k','d','j'); Func <string, string, string, double, string, string, string, int> kdj = delegate(string close, string high, string low, double days, string k, string d, string j) { if (arrays.ContainsKey(close) && arrays.ContainsKey(high) && arrays.ContainsKey(low)) { double[] inputs0 = arrays[close]; double[] inputs1 = arrays[high]; double[] inputs2 = arrays[low]; double[] kArray; double[] dArray; double[] jArray; MathUtil.calcKDJ((int)days, inputs0, inputs1, inputs2, out kArray, out dArray, out jArray); addArray(k, kArray); addArray(d, dArray); addArray(j, jArray); return(0); } return(1); }; //draw candle line. Func <string, double, string, string, string, string, int> candleLine = delegate(string id, double part, string open, string close, string high, string low) { if (!arrays.ContainsKey(open) || !arrays.ContainsKey(close) || !arrays.ContainsKey(high) || !arrays.ContainsKey(low)) { return(1); } canvas.addKLineObj(id, (int)part, arrays[open], arrays[close], arrays[high], arrays[low]); return(0); }; Func <string, object, int> addConfig = delegate(string id, object value) { addConfigVal(id, value); return(0); }; Func <string, int> runScript = delegate(string scriptName) { runJsScript(scriptName); return(0); }; Func <string, double, string, double, double, double, double, double, int> vLines = delegate(string id, double part, string label, double r, double g, double b, double a, double thickness) { if (!arrays.ContainsKey(label)) { return(1); } Color c = new Color() { R = (byte)r, G = (byte)g, B = (byte)b, A = (byte)a }; // canvas.addDrawingObj(id, arrays[label], (int)part, c, thickness, DrawingObjectType.vLines); return(0); }; // Func <string, string, int> setDrawItemEventHandler = delegate(string id, string handlerName) { canvas.setDrawItemEventHandler(id, handlerName); return(0); }; jint.SetFunction("addConfig", addConfig); jint.SetFunction("runScript", runScript); jint.SetFunction("setDrawItemEventHandler", setDrawItemEventHandler); jint.SetFunction("alert", alert); jint.SetFunction("ema", ema); jint.SetFunction("kdj", kdj); jint.SetFunction("diff", diff); jint.SetFunction("line", line); jint.SetFunction("zeroBars", zeroBars); jint.SetFunction("candleLine", candleLine); jint.SetFunction("vLines", vLines); }
/// <summary> /// Evaluate a code and return a value /// </summary> /// <param name="discardFromDebugView">true to discard from Debug View, in Debug mode (used to prevent pollution of executed modules in Visual Studio Code)</param> public object Evaluate(string script, bool discardFromDebugView = false) { if (script is null) { throw new ArgumentNullException(nameof(script)); } switch (Type) { case JsScriptRunnerType.Jint: { try { return(JintEngine.Execute(script) // from https://github.com/sebastienros/jint .GetCompletionValue() // get the latest statement completion value .ToObject()); // converts the value to .NET } catch (Esprima.ParserException ex) { throw new ApplicationException($"{ex.Error} (Line {ex.LineNumber}, Column {ex.Column}), -> {ReadLine(script, ex.LineNumber)}", ex); } catch (Jint.Runtime.JavaScriptException ex) // from https://github.com/sebastienros/jint/issues/112 { throw new ApplicationException($"{ex.Error} (Line {ex.LineNumber}, Column {ex.Column}), -> {ReadLine(script, ex.LineNumber)}", ex); } } case JsScriptRunnerType.ClearScriptDebugMode: { try { if (discardFromDebugView) { return(ClearScriptEngine.Evaluate(string.Empty, true, script)); } else { // see https://microsoft.github.io/ClearScript/Reference/html/M_Microsoft_ClearScript_ScriptEngine_Evaluate_2.htm return(ClearScriptEngine.Evaluate(ReadAndNormalizeFirstNonEmptyLineOfAScript(script), false, script)); } } catch (Microsoft.ClearScript.ScriptEngineException ex) // from https://github.com/microsoft/ClearScript/issues/16 { throw new ApplicationException($"{ex.ErrorDetails}", ex); } } case JsScriptRunnerType.ClearScript: { try { // see https://microsoft.github.io/ClearScript/Reference/html/M_Microsoft_ClearScript_ScriptEngine_Evaluate_2.htm return(ClearScriptEngine.Evaluate(script)); } catch (Microsoft.ClearScript.ScriptEngineException ex) // from https://github.com/microsoft/ClearScript/issues/16 { throw new ApplicationException($"{ex.ErrorDetails}", ex); } } } throw new InvalidOperationException("unexpected case"); }
public void Run(string script, bool discardFromDebugView = false) { if (script is null) { throw new ArgumentNullException(nameof(script)); } switch (Type) { case JsScriptRunnerType.Jint: { try { JintEngine.Execute(script); break; } catch (Esprima.ParserException ex) { throw new ApplicationException($"{ex.Error} (Line {ex.LineNumber}, Column {ex.Column}), -> {ReadLine(script, ex.LineNumber)}", ex); } catch (Jint.Runtime.JavaScriptException ex) // from https://github.com/sebastienros/jint/issues/112 { throw new ApplicationException($"{ex.Error} (Line {ex.LineNumber}, Column {ex.Column}), -> {ReadLine(script, ex.LineNumber)}", ex); } } case JsScriptRunnerType.ClearScriptDebugMode: { try { if (discardFromDebugView) { // see https://microsoft.github.io/ClearScript/Reference/html/M_Microsoft_ClearScript_ScriptEngine_Execute_2.htm ClearScriptEngine.Execute(string.Empty, true, script); } else { ClearScriptEngine.Execute(ReadAndNormalizeFirstNonEmptyLineOfAScript(script), false, script); } break; } catch (Microsoft.ClearScript.ScriptEngineException ex) // from https://github.com/microsoft/ClearScript/issues/16 { throw new ApplicationException($"{ex.ErrorDetails}", ex); } } case JsScriptRunnerType.ClearScript: { try { // see https://microsoft.github.io/ClearScript/Reference/html/M_Microsoft_ClearScript_ScriptEngine_Execute_2.htm ClearScriptEngine.Execute(script); break; } catch (Microsoft.ClearScript.ScriptEngineException ex) // from https://github.com/microsoft/ClearScript/issues/16 { throw new ApplicationException($"{ex.ErrorDetails}", ex); } } } }
protected override void RemoveEngineCustomizations(JintEngine jintEngine) { jintEngine.RemoveParameter("documentId"); jintEngine.RemoveParameter("sqlReplicate"); }
protected virtual void RemoveEngineCustomizations(JintEngine jintEngine) { }
void worker_DoWork(object sender, DoWorkEventArgs e) { string script = textEditor1.Text; IsInNetDelegate IsInNet = PacExtensions.IsInNetAction; localHostOrDomainIsDelegate localHostOrDomainIs = PacExtensions.localHostOrDomainIs; myIpAddressDelegate myIpAddress = PacExtensions.myIpAddress; isResolvableDelegate isResolvable = PacExtensions.isResolvable; dateRangeDelegate dateRange = PacExtensions.dateRange; weekdayRangeDelegate weekdayRange = PacExtensions.weekdayRange; timeRangeDelegate timeRange = PacExtensions.timeRange; isPlainHostNameDelegate isPlainHostName = PacExtensions.isPlainHostName; dnsDomainIsDelegate dnsDomainIs = PacExtensions.dnsDomainIs; dnsResolveDelegate dnsResolve = PacExtensions.dnsResolve; alertDelegate alert = PacExtensions.alert; dnsDomainLevelsDelegate dnsDomainLevels = PacExtensions.dnsDomainLevels; shExpMatchDelegate shExpMatch = PacExtensions.shExpMatch; JintEngine jint = new JintEngine() .SetDebugMode(true) .SetFunction("isInNet", IsInNet) .SetFunction("localHostOrDomainIs", localHostOrDomainIs) .SetFunction("myIpAddress", myIpAddress) .SetFunction("isResolvable", isResolvable) .SetFunction("dateRange", dateRange) .SetFunction("weekdayRange", weekdayRange) .SetFunction("timeRange", timeRange) .SetFunction("isPlainHostName", isPlainHostName) .SetFunction("dnsDomainIs", dnsDomainIs) .SetFunction("dnsResolve", dnsResolve) .SetFunction("alert", alert) .SetFunction("dnsDomainLevels", dnsDomainLevels) .SetFunction("shExpMatch", shExpMatch); try { jint.Step += jint_Step; textEditor1.Text = script; var result = jint.Run(script); executionHistory.Clear(); listBox1.Invoke(new Action(delegate { listBox1.Items.Clear(); })); Uri uri; if (!textBoxURL.Text.Contains("://")) { this.Invoke(new Action(delegate { textBoxURL.Text = "http://" + textBoxURL.Text; })); } if (!Uri.TryCreate(textBoxURL.Text, UriKind.Absolute, out uri)) { listView1.Invoke(new Action(delegate { listView1.Items.Add(string.Format("'{0}' is not a valid URL", textBoxURL.Text), 2); })); } else { PacExtensions.CounterReset(); result = jint.Run(string.Format("FindProxyForURL(\"{0}\",\"{1}\")", uri.ToString(), uri.Host)); Trace.WriteLine(result); textBoxProxy.Invoke(new Action(delegate { listView1.Items.Add(string.Format("IsInNet Count: {0} Total Duration: {1} ms", PacExtensions.IsInNetCount, PacExtensions.IsInNetDuration.Milliseconds)); listView1.Items.Add(string.Format("DnsDomainIs Count: {0} Total Duration: {1} ms", PacExtensions.DnsDomainIsCount, PacExtensions.DnsDomainIsDuration.Milliseconds)); textBoxProxy.Text = result.ToString(); foreach (string s in PacExtensions.EvaluationHistory) { listView1.Items.Add(s, 0); } })); } } catch (Jint.Native.JsException ex) { listBox1.Invoke(new Action(delegate { string msg = ex.Message.Replace("An unexpected error occurred while parsing the script. Jint.JintException: ", ""); listView1.Items.Add(msg, 2); })); } catch (System.NullReferenceException) { listBox1.Invoke(new Action(delegate { string msg = "Null reference. Probably variable/function not defined, remember functions and variables are case sensitive."; listView1.Items.Add(msg, 2); })); } catch (JintException ex) { listBox1.Invoke(new Action(delegate { int i = ex.InnerException.ToString().IndexOf(":"); string msg = ex.InnerException.ToString(); if (msg.Contains("line")) { int x = msg.IndexOf("line"); int y = msg.IndexOf(":", x); if (y > 0) { string lineNumber = msg.Substring(x + 5, y - x - 5); int line; if (Int32.TryParse(lineNumber, out line)) { textEditor1.HighlightActiveLine = true; textEditor1.GotoLine(line - 1); } } } if (i > 0) { msg = msg.Substring(i + 1); } msg = msg.Substring(0, msg.IndexOf(" at Jint.")); if (msg.Contains("Object reference not set to an instance of an object.")) { msg = "Variable/Function not defined. Remember variables/functions are case sensitive."; } //.Replace("An unexpected error occurred while parsing the script. Jint.JintException: ", ""); listView1.Items.Add(msg, 2); if (!msg.Contains("Variable/Function not defined.")) { listBox1.Items.Add(string.Format("Fatal Error: {0}. {1}", ex.Message, ex.InnerException)); } })); } catch (Exception ex) { listBox1.Invoke(new Action(delegate { listBox1.Items.Add(string.Format("Fatal Error: {0}", ex.Message)); })); } }
private static void AddScript(JintEngine jintEngine, string ravenDatabaseJsonMapJs) { jintEngine.Run(GetFromResources(ravenDatabaseJsonMapJs)); }
public void ShouldHandleCustomMethods() { Assert.AreEqual(9d, new JintEngine() .SetFunction("square", new Func<double, double>(a => a * a)) .Run("return square(3);")); new JintEngine() .SetFunction("print", new Action<string>(Console.Write)) .Run("print('hello');"); const string script = @" function square(x) { return multiply(x, x); }; return square(4); "; var result = new JintEngine() .SetFunction("multiply", new Func<double, double, double>((x, y) => x * y)) .Run(script); Assert.AreEqual(16d, result); }
protected virtual void CustomizeEngine(JintEngine jintEngine) { }
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);")); }
public void SetTimeout(string function, double millisecondsDelay) { Task.Delay((int)millisecondsDelay).Wait(); JintEngine.Execute(function); }
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); }
public Util(JintEngine engine) { this.engine = engine; }
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')); "); }
/// <summary> /// Loads a script file to the current execution context /// </summary> public static bool LoadScriptFile(string scriptFile) { bool loaded = false; try { //work out the full path of the script file to be loaded if (!Path.IsPathRooted(scriptFile)) { string basePath; if (scriptFile.StartsWith("~")) { //relative to scripts path basePath = ScriptsPath; scriptFile = scriptFile.Substring(1); } else { //relative to current script folder basePath = Path.GetDirectoryName(scriptFile); } while (scriptFile.StartsWith(@"\")) { scriptFile = scriptFile.Substring(1); } scriptFile = Path.GetFullPath(Path.Combine(basePath, scriptFile)); } //check that script file is not already loaded if (!loadedScripts.Contains(scriptFile, StringComparer.OrdinalIgnoreCase)) { //check that script exists if (File.Exists(scriptFile)) { //load file into the current ExecutionVisitor string script = File.ReadAllText(scriptFile); //load into current execution visitor Program program = JintEngine.Compile(script, false); foreach (var statement in program.ReorderStatements()) { statement.Accept(m_Instance.visitor); } //add to scripts collection to stop reloading loadedScripts.Add(scriptFile); loaded = true; } else { m_Logger.WarnFormat("The script file to append could not be found at {0}", scriptFile); } } else { //alread loaded loaded = true; } } catch (Exception exp) { m_Logger.WarnFormat("An error occurred appending the script {0} in the script engine: {1}", scriptFile, exp.Message); } return(loaded); }
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); } } }
public void Dispose() { this._engine = (JintEngine)null; }