public void Test1() { var code = "function print(msg){ console.log(msg) } print('teste');"; var context = new JsContext(); context.Set("console", new ConsoleTest()); var o = context.Run(code); }
public JsImportantComment(JsContext context, JsParser parser) : base(context, parser) { if (parser != null && parser.Settings.OutputMode == MinifierOutputMode.SingleLine) { // if we are in single-line mode, we want to replace all CRLF pairs // with just the LF to save output bytes. Comment = Context.Code.Replace("\r\n", "\n"); } else { // multi-line mode, just leave it as-is Comment = Context.Code; } }
public void ExternalObjects() { var context = new JsContext(); context.Set("console", new ConsoleTest()); context.Run("console.log('teste')"); //context.Set("$ERROR", ); context.Set("script", new EvalTest(context)); context.Run("function eval(code){ return script.eval(code); }"); var r = context.Run("eval('1+1')"); Assert.AreEqual(2, r); }
public void VarDeclarationAndBasicOperationsTest() { var code = "var s = 3, r = 6\n" + "/* */var t = 1;" + "var name = 'string';" + "var w = t + s;" + "var z = (w + (((s) + 6)) + (1 * 2));" ; var context = new JsContext(); context.Run(code); Assert.AreEqual(3, context.Get("s")); Assert.AreEqual(6, context.Get("r")); Assert.AreEqual(1, context.Get("t")); Assert.AreEqual("string", context.Get("name")); Assert.AreEqual(4, context.Get("w")); Assert.AreEqual(15, context.Get("z")); var res = (bool)context.Run("z > w"); Assert.IsTrue(res); }
static void Main() { //----------------------------------- //1. //after we build nodejs in dll version //we will get node.dll //then just copy it to another name 'libespr' string libEspr = @"C:\projects\node-v6.7.0\Release\libespr.dll"; if (File.Exists(libEspr)) { //delete the old one File.Delete(libEspr); } File.Copy( @"C:\projects\node-v6.7.0\Release\node.dll", //from libEspr); //----------------------------------- //2. load libespr.dll (node.dll) IntPtr intptr = LoadLibrary(libEspr); int errCode = GetLastError(); #if DEBUG JsBridge.dbugTestCallbacks(); #endif //------------ JsEngine.RunJsEngine((IntPtr nativeEngine, IntPtr nativeContext) => { JsEngine eng = new JsEngine(nativeEngine); JsContext ctx = eng.CreateContext(nativeContext); //------------- //this LibEspressoClass object is need, //so node can talk with us, //------------- JsTypeDefinition jstypedef = new JsTypeDefinition("LibEspressoClass"); jstypedef.AddMember(new JsMethodDefinition("LoadMainSrcFile", args => { string filedata = @"var http = require('http'); (function t(){ console.log('hello from EspressoCup'); var server = http.createServer(function(req, res) { res.writeHead(200); res.end('Hello! from EspressoCup'); }); server.listen(8080,'localhost'); })();"; args.SetResult(filedata); })); jstypedef.AddMember(new JsMethodDefinition("C", args => { args.SetResult(true); })); jstypedef.AddMember(new JsMethodDefinition("E", args => { args.SetResult(true); })); if (!jstypedef.IsRegisterd) { ctx.RegisterTypeDefinition(jstypedef); } //---------- //then register this as x*** //this object is just an instance for reference ctx.SetVariableFromAny("LibEspresso", ctx.CreateWrapper(new object(), jstypedef)); }); }
public void Setup() { jsEngine = new JsEngine(); js = jsEngine.CreateContext(); }
internal static extern JsErrorCode JsCreateContext(JsRuntime runtime, out JsContext newContext);
internal static extern JsErrorCode JsSetCurrentContext(JsContext context);
public TestProgram(Runtime runtime, JsContext context, ChakraCore.TypeMapper typeMapper) : base(runtime, context, typeMapper) { }
internal static extern JsErrorCode JsContextAddRef(JsContext reference, out uint count);
private void ProjectProperties(EmbeddedItem externalItem, EmbeddingObjectOptions options) { Type type = externalItem.HostType; object obj = externalItem.HostObject; JsValue typeValue = externalItem.ScriptValue; IList <JsNativeFunction> nativeFunctions = externalItem.NativeFunctions; bool instance = externalItem.IsInstance; string typeName = type.FullName; BindingFlags defaultBindingFlags = ReflectionHelpers.GetDefaultBindingFlags(instance); PropertyInfo[] properties = type.GetProperties(defaultBindingFlags).Where(options.IsMapped).ToArray(); foreach (PropertyInfo property in properties) { string propertyName = property.Name; JsValue descriptorValue = JsValue.CreateObject(); descriptorValue.SetProperty("enumerable", JsValue.True, true); if (property.GetGetMethod() != null) { JsValue nativeGetFunction(JsValue callee, bool isConstructCall, JsValue[] args, ushort argCount, IntPtr callbackData) { if (instance && obj == null) { CreateAndSetError($"Invalid context for '{propertyName}' property."); return(JsValue.Undefined); } object result; try { result = property.GetValue(obj, new object[0]); } catch (Exception e) { Exception exception = UnwrapException(e); var wrapperException = exception as JsException; JsValue errorValue; if (wrapperException != null) { errorValue = CreateErrorFromWrapperException(wrapperException); } else { string errorMessage = instance ? $"Property '{propertyName}' get operation failed: {exception.Message}" : $"Property '{propertyName}' of static type '{typeName}' get operation failed: {exception.Message}" ; errorValue = JsValue.CreateError(JsValue.FromString(errorMessage)); } JsContext.SetException(errorValue); return(JsValue.Undefined); } JsValue resultValue = MapToScriptType(result); return(resultValue); } nativeFunctions.Add(nativeGetFunction); JsValue getMethodValue = JsValue.CreateFunction(nativeGetFunction); descriptorValue.SetProperty("get", getMethodValue, true); } if (property.GetSetMethod() != null) { JsValue nativeSetFunction(JsValue callee, bool isConstructCall, JsValue[] args, ushort argCount, IntPtr callbackData) { JsValue undefinedValue = JsValue.Undefined; if (instance && obj == null) { CreateAndSetError($"Invalid context for '{propertyName}' property."); return(undefinedValue); } object value = MapToHostType(args[1]); ReflectionHelpers.FixPropertyValueType(ref value, property); try { property.SetValue(obj, value, new object[0]); } catch (Exception e) { Exception exception = UnwrapException(e); var wrapperException = exception as JsException; JsValue errorValue; if (wrapperException != null) { errorValue = CreateErrorFromWrapperException(wrapperException); } else { string errorMessage = instance ? $"Host object property '{propertyName}' setting failed: {exception.Message}" : $"Host type '{typeName}' property '{propertyName}' setting failed: {exception.Message}" ; errorValue = JsValue.CreateError(JsValue.FromString(errorMessage)); } JsContext.SetException(errorValue); return(undefinedValue); } return(undefinedValue); } nativeFunctions.Add(nativeSetFunction); JsValue setMethodValue = JsValue.CreateFunction(nativeSetFunction); descriptorValue.SetProperty("set", setMethodValue, true); } typeValue.DefineProperty(propertyName, descriptorValue); } }
/// <summary> /// vm.runInContext compiles code, then runs it in context and returns the result. A (V8) context comprises a global object, /// together with a set of built-in objects and functions. /// Running code does not have access to local scope and the global object held within context will be used as the global object for code. /// ///<example> /// Example: compile and execute code in a existing context. /// <code> /// var util = require('util'), /// vm = require('vm'), /// initSandbox = { /// animal: 'cat', /// count: 2 /// }, /// context = vm.createContext(initSandbox); /// /// vm.runInContext('count += 1; name = "CATT"', context, 'myfile.vm'); /// console.log(util.inspect(context)); /// /// // { animal: 'cat', count: 3, name: 'CATT' } ///</code> ///</example> ///<remarks> /// Note that createContext will perform a shallow clone of the supplied sandbox object in order to initialize the global object of the freshly constructed context. /// /// Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable leakage, vm.runInContext is quite useful, but safely running untrusted code requires a separate process. /// /// In case of syntax error in code, vm.runInContext emits the syntax error to stderr and throws an exception. /// </remarks> /// </summary> /// <param name="code"></param> /// <param name="context"></param> /// <returns></returns> public object runInContext(JsString code, JsContext context) { return null; }
protected override void InnerExecute(string code, string documentName) { string uniqueDocumentName = _documentNameManager.GetUniqueName(documentName); InvokeScript(() => JsContext.RunScript(code, _jsSourceContext++, uniqueDocumentName)); }
protected JsConditionalCompilationStatement(JsContext context, JsParser parser) : base(context, parser) { }
public static int ParseInt(string s) { var val = JsContext.parseInt(s); return(JsContext.isNaN(val) ? int.MinValue : (int)val); }
public static float ParseFloat(string s) { return(JsContext.parseFloat(s)); }
public static void FillFromJson(Settings settings, dynamic json) { if (!json) { return; } if (Std.JsonExists(json, "scale")) { settings.Scale = json.scale; } if (Std.JsonExists(json, "width")) { settings.Width = json.width; } if (Std.JsonExists(json, "height")) { settings.Height = json.height; } if (Std.JsonExists(json, "engine")) { settings.Engine = json.engine; } if (Std.JsonExists(json, "stretchForce")) { settings.StretchForce = json.stretchForce; } if (Std.JsonExists(json, "forcePianoFingering")) { settings.ForcePianoFingering = json.forcePianoFingering; } if (Std.JsonExists(json, "atRoot")) { settings.ScriptFile = json.atRoot; // append script name if (!settings.ScriptFile.EndsWith(".js")) { if (!settings.ScriptFile.EndsWith("/")) { settings.ScriptFile += "/"; } settings.ScriptFile += "AlphaTab.js"; } if (!settings.ScriptFile.StartsWith("http") && !settings.ScriptFile.StartsWith("https")) { var root = new StringBuilder(); root.Append(HtmlContext.window.location.protocol); root.Append("//"); root.Append(HtmlContext.window.location.hostname); if (HtmlContext.window.location.port.As <bool>()) { root.Append(":"); root.Append(HtmlContext.window.location.port); } root.Append(settings.ScriptFile); settings.ScriptFile = root.ToString(); } } else { settings.ScriptFile = Environment.ScriptFile; } if (Std.JsonExists(json, "layout")) { if (JsContext.@typeof(json.layout) == "string") { settings.Layout.Mode = json.layout; } else { if (json.layout.mode) { settings.Layout.Mode = json.layout.mode; } if (json.layout.additionalSettings) { string[] keys = Std.JsonKeys(json.layout.additionalSettings); foreach (var key in keys) { settings.Layout.AdditionalSettings[key] = json.layout.additionalSettings[key]; } } } } if (Std.JsonExists(json, "staves")) { settings.Staves = new FastList <StaveSettings>(); string[] keys = Std.JsonKeys(json.staves); foreach (var key in keys) { var val = json.staves[key]; if (JsContext.@typeof(val) == "string") { settings.Staves.Add(new StaveSettings(val)); } else { if (val.id) { var staveSettings = new StaveSettings(val.id); if (val.additionalSettings) { string[] keys2 = Std.JsonKeys(val.additionalSettings); foreach (var key2 in keys2) { staveSettings.AdditionalSettings[key2] = val.additionalSettings[key2]; } } settings.Staves.Add(staveSettings); } } } } }
public ComputerProgram(Runtime runtime, JsContext context, ChakraCore.TypeMapper typeMapper) : base(runtime, context, typeMapper) { terminal = new Terminal(this); }
public JsConditionalCompilationOn(JsContext context, JsParser parser) : base(context, parser) { }
internal JsToken GetKeyword(JsContext context, int wordLength) { return GetKeyword(context.Document.Source, context.StartPosition, wordLength); }
internal static extern JsErrorCode JsGetContextOfObject(JsValue obj, out JsContext context);
static void PlatformInit() { RenderEngines["svg"] = () => new CssFontSvgCanvas(); RenderEngines["default"] = () => new CssFontSvgCanvas(); RenderEngines["html5"] = () => new Platform.JavaScript.Html5Canvas(); // check whether webfont is loaded CheckFontLoad(); JsContext.JsCode("Math.log2 = Math.log2 || function(x) { return Math.log(x) * Math.LOG2E; };"); // try to build the find the alphaTab script url in case we are not in the webworker already if (HtmlContext.self.document.As <bool>()) { /** * VB Loader For IE * This code is based on the code of * http://nagoon97.com/reading-binary-files-using-ajax/ * Copyright (c) 2008 Andy G.P. Na <*****@*****.**> * The source code is freely distributable under the terms of an MIT-style license. */ var vbAjaxLoader = new StringBuilder(); vbAjaxLoader.AppendLine("<script type=\"text/vbscript\">"); vbAjaxLoader.AppendLine("Function VbAjaxLoader(method, fileName)"); vbAjaxLoader.AppendLine(" Dim xhr"); vbAjaxLoader.AppendLine(" Set xhr = CreateObject(\"Microsoft.XMLHTTP\")"); vbAjaxLoader.AppendLine(" xhr.Open method, fileName, False"); vbAjaxLoader.AppendLine(" xhr.setRequestHeader \"Accept-Charset\", \"x-user-defined\""); vbAjaxLoader.AppendLine(" xhr.send"); vbAjaxLoader.AppendLine(" Dim byteArray()"); vbAjaxLoader.AppendLine(" if xhr.Status = 200 Then"); vbAjaxLoader.AppendLine(" Dim byteString"); vbAjaxLoader.AppendLine(" Dim i"); vbAjaxLoader.AppendLine(" byteString=xhr.responseBody"); vbAjaxLoader.AppendLine(" ReDim byteArray(LenB(byteString))"); vbAjaxLoader.AppendLine(" For i = 1 To LenB(byteString)"); vbAjaxLoader.AppendLine(" byteArray(i-1) = AscB(MidB(byteString, i, 1))"); vbAjaxLoader.AppendLine(" Next"); vbAjaxLoader.AppendLine(" End If"); vbAjaxLoader.AppendLine(" VbAjaxLoader=byteArray"); vbAjaxLoader.AppendLine("End Function"); vbAjaxLoader.AppendLine("</script>"); HtmlContext.document.write(vbAjaxLoader.ToString()); var scriptElement = HtmlContext.document.Member("currentScript").As <HtmlScriptElement>(); if (!scriptElement.As <bool>()) { // try to get javascript from exception stack try { var error = new JsError(); var stack = error.Member("stack"); if (!stack.As <bool>()) { throw error; } ScriptFile = ScriptFileFromStack(stack.As <JsString>()); } catch (JsError e) { var stack = e.Member("stack"); if (!stack.As <bool>()) { scriptElement = HtmlContext.document.querySelector("script[data-alphatab]").As <HtmlScriptElement>(); } else { ScriptFile = ScriptFileFromStack(stack.As <JsString>()); } } } // failed to automatically resolve if (string.IsNullOrEmpty(ScriptFile)) { if (!scriptElement.As <bool>()) { HtmlContext.console.warn( "Could not automatically find alphaTab script file for worker, please add the data-alphatab attribute to the script tag that includes alphaTab or provide it when initializing alphaTab"); } else { ScriptFile = scriptElement.src; } } } }
void foo() { var ctor = JsContext.CtorOf <Constructors>(); var obj = JsContext.JsCode("new ctor()"); }
private void ProjectMethods(EmbeddedItem externalItem, EmbeddingObjectOptions options) { Type type = externalItem.HostType; object obj = externalItem.HostObject; JsValue typeValue = externalItem.ScriptValue; IList <JsNativeFunction> nativeFunctions = externalItem.NativeFunctions; bool instance = externalItem.IsInstance; string typeName = type.FullName; BindingFlags defaultBindingFlags = ReflectionHelpers.GetDefaultBindingFlags(instance); var methods = type.GetMethods(defaultBindingFlags).Select(options.ExtendInfo) .Where((m) => m.IsMapped); var methodGroups = methods.GroupBy(m => m.Name); foreach (var methodGroup in methodGroups) { string methodName = methodGroup.Key; MethodInfo[] methodCandidates = methodGroup.Select(m => m.Info).ToArray(); JsValue nativeFunction(JsValue callee, bool isConstructCall, JsValue[] args, ushort argCount, IntPtr callbackData) { if (instance && obj == null) { CreateAndSetError($"Invalid context while calling method '{methodName}'."); return(JsValue.Undefined); } if (!SelectAndProcessFunction(methodCandidates, args, argCount, out MethodInfo bestSelection, out object[] processedArgs)) { CreateAndSetError($"Suitable method '{methodName}' was not found."); return(JsValue.Undefined); } object result; try { result = bestSelection.Invoke(obj, processedArgs); } catch (Exception e) { Exception exception = UnwrapException(e); var wrapperException = exception as JsException; JsValue errorValue; if (wrapperException != null) { errorValue = CreateErrorFromWrapperException(wrapperException); } else { string errorMessage = instance ? $"Host method '{methodName}' invocation error: {exception.Message}" : $"Host static type '{typeName}' method '{methodName}' invocation error: {exception.Message}" ; errorValue = JsValue.CreateError(JsValue.FromString(errorMessage)); } JsContext.SetException(errorValue); return(JsValue.Undefined); } JsValue resultValue = MapToScriptType(result); return(resultValue); } nativeFunctions.Add(nativeFunction); JsValue methodValue = JsValue.CreateNamedFunction(methodName, nativeFunction); typeValue.SetProperty(methodName, methodValue, true); } }
public EvalTest(JsContext context) { _context = context; }
/// <summary> /// Constructs an instance of adapter for the ChakraCore JS engine /// </summary> /// <param name="settings">Settings of the ChakraCore JS engine</param> public ChakraCoreJsEngine(ChakraCoreSettings settings) { #if NETFULL Initialize(); #endif ChakraCoreSettings chakraCoreSettings = settings ?? new ChakraCoreSettings(); JsRuntimeAttributes attributes = JsRuntimeAttributes.AllowScriptInterrupt; if (chakraCoreSettings.DisableBackgroundWork) { attributes |= JsRuntimeAttributes.DisableBackgroundWork; } if (chakraCoreSettings.DisableEval) { attributes |= JsRuntimeAttributes.DisableEval; } if (chakraCoreSettings.DisableExecutablePageAllocation) { attributes |= JsRuntimeAttributes.DisableExecutablePageAllocation; } if (chakraCoreSettings.DisableFatalOnOOM) { attributes |= JsRuntimeAttributes.DisableFatalOnOOM; } if (chakraCoreSettings.DisableNativeCodeGeneration) { attributes |= JsRuntimeAttributes.DisableNativeCodeGeneration; } if (chakraCoreSettings.EnableExperimentalFeatures) { attributes |= JsRuntimeAttributes.EnableExperimentalFeatures; } #if NETSTANDARD1_3 _dispatcher = new ScriptDispatcher(); #else _dispatcher = new ScriptDispatcher(chakraCoreSettings.MaxStackSize); #endif _promiseContinuationCallback = PromiseContinuationCallback; try { _dispatcher.Invoke(() => { _jsRuntime = JsRuntime.Create(attributes, null); _jsRuntime.MemoryLimit = settings.MemoryLimit; _jsContext = _jsRuntime.CreateContext(); if (_jsContext.IsValid) { _jsContext.AddRef(); using (new JsScope(_jsContext)) { JsContext.SetPromiseContinuationCallback(_promiseContinuationCallback, IntPtr.Zero); } } }); } catch (DllNotFoundException e) { throw WrapDllNotFoundException(e); } catch (Exception e) { throw CoreErrorHelpers.WrapEngineLoadException(e, EngineName, EngineVersion, true); } finally { if (!_jsContext.IsValid) { Dispose(); } } }
private static JsType CompileType(JsType type) { var currentType = Types[type.fullname].As <JsType>() ?? type; if (currentType.ctors == null) { currentType.ctors = new JsObject(); } if (!type.isCompiled) { var baseTypeResolved = false; if (currentType.baseType == null && currentType.baseTypeName != null) { ResolveBaseType(type, currentType); if (currentType.baseType != null) { baseTypeResolved = true; } } ResolveInterfaces(type, currentType); foreach (var p in type.definition) { if (p.As <JsString>().search("ctor") == 0) //isCtor { currentType.As <JsObject>()[p] = type.definition[p]; JsContext.delete(type.definition[p]); if (JsContext.@typeof(currentType.commonPrototype) == "undefined") { currentType.commonPrototype = currentType.As <JsObject>()[p].As <JsFunction>().prototype.As <JsCompilerPrototype>(); } else { currentType.As <JsObject>()[p].As <JsFunction>().prototype = currentType.commonPrototype; } currentType.ctors[p] = currentType.As <JsObject>()[p]; } if (p == "cctor") { currentType.cctor = p.As <JsFunction>(); } } // if(currentType.ctor==null) // { // currentType.ctor = window[type.get_FullName()]; // } if (currentType.ctor == null) { if (currentType.ns == null || currentType.ns == "") { var jsCtor = window.As <JsObject>()[currentType.name].As <JsFunction>(); currentType.ctor = jsCtor; } // currentType.ctor = type.definition[type.name]; // if(type.definition[type.name]!=null) // delete type.definition[type.name]; // else if (currentType.ctor == null && currentType.ctors != null) { var createCtor = true; foreach (var p in currentType.ctors) { createCtor = false; break; } if (createCtor) { if (currentType.baseType != null) { currentType.ctor = CreateBaseCtor(); } else { currentType.ctor = CreateEmptyCtor(); } } } if (currentType.ctor != null) { currentType.ctors["ctor"] = currentType.ctor; if (JsContext.@typeof(currentType.commonPrototype) == "undefined") { currentType.commonPrototype = currentType.ctor.prototype.As <JsCompilerPrototype>(); } else { currentType.ctor.prototype = currentType.commonPrototype; } } } foreach (var p in currentType.ctors) { var ctor = currentType.ctors[p].As <JsCompilerFunction>(); if (ctor._type == null) { ctor._type = currentType; } } // if(currentType.ctor._type==null) // currentType.ctor._type = currentType; if (baseTypeResolved) { _CopyObject(currentType.baseType.commonPrototype, currentType.commonPrototype); } foreach (var p in type.definition) { var member = type.definition[p]; currentType.commonPrototype[p] = member; if (JsContext.@typeof(member) == "function") { member.As <JsCompilerFunction>()._name = p; member.As <JsCompilerFunction>()._type = currentType; } } if (type.definition.As <JsCompilerPrototype>().toString != JsCompilerObject.prototype.toString) { currentType.commonPrototype.toString = type.definition.As <JsCompilerPrototype>().toString; currentType.commonPrototype.toString.name = "toString"; currentType.commonPrototype.toString._type = currentType; } foreach (var p in type.staticDefinition) { var member = type.staticDefinition[p]; //TODO: if (JsContext.@typeof(currentType.As<JsObject>()[p]) != "undefined") //TODO: throw new JsError("Reserved static member name " + p).As<Exception>(); currentType.As <JsObject>()[p] = member; if (JsContext.@typeof(member) == "function") { member.As <JsCompilerFunction>()._name = p; member.As <JsCompilerFunction>()._type = currentType; } } type.isCompiled = true; } CompileEnum(currentType); if (currentType != type && type.customAttributes != null) { if (currentType.customAttributes != null) { for (var i = 0; i < type.customAttributes.length; i++) { currentType.customAttributes.push(type.customAttributes[i]); } } else { currentType.customAttributes = type.customAttributes; } } return(currentType); }
internal static extern JsErrorCode JsSetContextData(JsContext context, IntPtr data);
public static void Main(string[] args) { // string lodash = File.ReadAllText(@"c:\lodash.js"); using (JsEngine engine = new JsEngine()) { //Stopwatch watch = new Stopwatch(); // watch.Start(); JsScript script = engine.CompileScript("3+3"); using (JsContext ctx = engine.CreateContext()) { ctx.Execute(script); } } debugtest dbg = new debugtest(); // Delegate.CreateDelegate() //Dictionary<string, object> values = new Dictionary<string, object>(); //values["test"] = 333; while (true) { using (JsEngine js = new JsEngine(4, 32)) { using (JsContext context = js.CreateContext()) { //context.SetVariable("dbg", dbg); //object result = context.Execute("dbg.Write(dbg.valueOf());"); context.SetVariableFromAny("Debug", typeof(debugtest)); object result = context.Execute("Debug.BoolTest(3,4);"); } GC.Collect(); js.DumpHeapStats(); } } //context.SetVariable("values", values); //object result = context.Execute("dbg.runFunc(); values.test ? true : false;"); // object result = // context.Execute("var obj = { test: 0 }; obj.ft = function (v) { dbg.Write(v); return 'from JS'; }; dbg.runFunc(obj.ft); dbg.write(obj.test);"); //int a = 1; // context.SetFunction("runfunc", new Func<int, bool>(Activate)); //object result = context.Execute("runfunc(2);"); // } // } //} /*using (JsEngine js = new JsEngine()) { * using (JsContext context = js.CreateContext()) { * using (JsScript script = js.CompileScript("3 * 4")) { * object result = context.Execute(script, TimeSpan.FromHours(200)); * Console.WriteLine(result); * } * } * }*/ //return; /* * using (JsEngine js = new JsEngine()) { * using (JsContext context = js.CreateContext()) { * for (int i = 0; i < 10; i++) { * context.SetVariable("a", new Simple { N = i, S = (i * 10).ToString() }); * Console.WriteLine(context.Execute("a.N+' '+a.S")); * } * Console.WriteLine(context.Execute("a.N+' '+a.X")); * } * }*/ }
internal static extern JsErrorCode JsContextRelease(JsContext reference, out uint count);
public JsDebuggerNode(JsContext context, JsParser parser) : base(context, parser) { }
internal static extern JsErrorCode JsGetCurrentContext(out JsContext currentContext);
public bool ContainsKey(TKey key) { var hashKey = GetHashKey(key); return(JsContext.@typeof(this._table[hashKey]) != "undefined"); }
internal static extern JsErrorCode JsGetRuntime(JsContext context, out JsRuntime runtime);
private void button3_Click(object sender, EventArgs e) { #if DEBUG JsBridge.dbugTestCallbacks(); #endif JsTypeDefinition jstypedef = new JsTypeDefinition("AA"); jstypedef.AddMember(new JsMethodDefinition("B", args => { args.SetResult(100); })); jstypedef.AddMember(new JsMethodDefinition("C", args => { args.SetResult(true); })); jstypedef.AddMember(new JsPropertyDefinition("D", args => { //getter args.SetResult(true); }, args => { //setter })); jstypedef.AddMember(new JsPropertyDefinition("E", args => { //getter args.SetResult(250); }, args => { //setter })); //=============================================================== //create js engine and context using (JsEngine engine = new JsEngine()) using (JsContext ctx = engine.CreateContext()) { ctx.RegisterTypeDefinition(jstypedef); GC.Collect(); System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch(); stwatch.Reset(); stwatch.Start(); TestMe1 t1 = new TestMe1(); var proxy = ctx.CreateWrapper(t1, jstypedef); //for (int i = 2000; i >= 0; --i) //{ ctx.SetVariableFromAny("x", proxy); //object result = ctx.Execute("(function(){if(x.C()){return x.B();}else{return 0;}})()"); object result = ctx.Execute("(function(){if(x.D){ x.E=300; return x.B();}else{return 0;}})()"); //} stwatch.Stop(); Console.WriteLine("met1 template:" + stwatch.ElapsedMilliseconds.ToString()); //Assert.That(result, Is.EqualTo(100)); } }
public JsThisLiteral(JsContext context, JsParser parser) : base(context, parser) { }
private void button5_Click(object sender, EventArgs e) { #if DEBUG JsBridge.dbugTestCallbacks(); #endif JsTypeDefinition jstypedef = new JsTypeDefinition("AA"); jstypedef.AddMember(new JsMethodDefinition("B", args => { var argCount = args.ArgCount; var thisArg = args.GetThisArg(); var arg0 = args.GetArgAsObject(0); args.SetResult((bool)arg0); })); jstypedef.AddMember(new JsMethodDefinition("C", args => { args.SetResult(true); })); //----------------------------------------------------- jstypedef.AddMember(new JsPropertyDefinition("D", args => { var ab = new AboutMe(); args.SetResultAutoWrap(ab); }, args => { //setter })); jstypedef.AddMember(new JsPropertyDefinition("E", args => { //getter args.SetResult(250); }, args => { //setter })); //=============================================================== //create js engine and context using (JsEngine engine = new JsEngine()) using (JsContext ctx = engine.CreateContext()) { ctx.RegisterTypeDefinition(jstypedef); GC.Collect(); System.Diagnostics.Stopwatch stwatch = new System.Diagnostics.Stopwatch(); stwatch.Reset(); stwatch.Start(); TestMe1 t1 = new TestMe1(); INativeScriptable proxy = ctx.CreateWrapper(t1, jstypedef); ctx.SetVariable("x", proxy); string testsrc = "x.B(x.D.IsOK);"; object result = ctx.Execute(testsrc); stwatch.Stop(); Console.WriteLine("met1 template:" + stwatch.ElapsedMilliseconds.ToString()); } }
protected JsConditionalCompilationStatement(JsContext context, JsParser parser) : base(context, parser) { }
public JsDebuggerNode(JsContext context, JsParser parser) : base(context, parser) { }
public JsConditionalCompilationEnd(JsContext context, JsParser parser) : base(context, parser) { }
public static Settings FromJson(dynamic json) { if (Std.InstanceOf <Settings>(json)) { return((Settings)json); } var settings = Defaults; if (!json) { return(settings); } if (JsonExists(json, "scale")) { settings.Scale = json.scale; } if (JsonExists(json, "width")) { settings.Width = json.width; } if (JsonExists(json, "height")) { settings.Height = json.height; } if (JsonExists(json, "engine")) { settings.Engine = json.engine; } if (JsonExists(json, "layout")) { if (JsContext.@typeof(json.layout) == "string") { settings.Layout.Mode = json.layout; } else { if (json.layout.mode) { settings.Layout.Mode = json.layout.mode; } if (json.layout.additionalSettings) { string[] keys = JsonKeys(json.layout.additionalSettings); foreach (var key in keys) { settings.Layout.AdditionalSettings[key] = json.layout.additionalSettings[key]; } } } } if (JsonExists(json, "staves")) { settings.Staves = new FastList <StaveSettings>(); string[] keys = JsonKeys(json.staves); foreach (var key in keys) { var val = json.staves[key]; if (JsContext.@typeof(val) == "string") { settings.Staves.Add(new StaveSettings(val)); } else { if (val.id) { var staveSettings = new StaveSettings(val.id); if (val.additionalSettings) { string[] keys2 = JsonKeys(val.additionalSettings); foreach (var key2 in keys2) { staveSettings.AdditionalSettings[key2] = val.additionalSettings[key2]; } } settings.Staves.Add(staveSettings); } } } } return(settings); }
public void Setup() { Context = new JsContext(); Context.Set("___testUtil", new TestUtil()); Context.Run("function $ERROR(message){ return ___testUtil.ThrowError(message); }"); }
private void ProjectFields(EmbeddedItem externalItem, EmbeddingObjectOptions options) { Type type = externalItem.HostType; object obj = externalItem.HostObject; JsValue typeValue = externalItem.ScriptValue; bool instance = externalItem.IsInstance; IList <JsNativeFunction> nativeFunctions = externalItem.NativeFunctions; string typeName = type.FullName; BindingFlags defaultBindingFlags = ReflectionHelpers.GetDefaultBindingFlags(instance); FieldInfo[] fields = type.GetFields(defaultBindingFlags).Where(options.IsMapped).ToArray(); foreach (FieldInfo field in fields) { string fieldName = field.Name; JsValue descriptorValue = JsValue.CreateObject(); descriptorValue.SetProperty("enumerable", JsValue.True, true); JsValue nativeGetFunction(JsValue callee, bool isConstructCall, JsValue[] args, ushort argCount, IntPtr callbackData) { if (instance && obj == null) { CreateAndSetError($"Context error while invoking getter '{fieldName}'."); return(JsValue.Undefined);; } object result; try { result = field.GetValue(obj); } catch (Exception e) { Exception exception = UnwrapException(e); var wrapperException = exception as JsException; JsValue errorValue; if (wrapperException != null) { errorValue = CreateErrorFromWrapperException(wrapperException); } else { string errorMessage = instance ? $"Error ocured while reading field '{fieldName}': {exception.Message}" : $"Erorr ocured while reading static field '{fieldName}' from type '{typeName}': {exception.Message}" ; errorValue = JsValue.CreateError(JsValue.FromString(errorMessage)); } JsContext.SetException(errorValue); return(JsValue.Undefined); } JsValue resultValue = MapToScriptType(result); return(resultValue); } nativeFunctions.Add(nativeGetFunction); JsValue getMethodValue = JsValue.CreateFunction(nativeGetFunction); descriptorValue.SetProperty("get", getMethodValue, true); JsValue nativeSetFunction(JsValue callee, bool isConstructCall, JsValue[] args, ushort argCount, IntPtr callbackData) { if (instance && obj == null) { CreateAndSetError($"Invalid context got host object field {fieldName}."); return(JsValue.Undefined); } object value = MapToHostType(args[1]); ReflectionHelpers.FixFieldValueType(ref value, field); try { field.SetValue(obj, value); } catch (Exception e) { Exception exception = UnwrapException(e); var wrapperException = exception as JsException; JsValue errorValue; if (wrapperException != null) { errorValue = CreateErrorFromWrapperException(wrapperException); } else { string errorMessage = instance ? $"Failed to set value for hosts object field '{fieldName}': {exception.Message}" : $"Failed to set value for static type '{typeName}' field '{fieldName}': {exception.Message}" ; errorValue = JsValue.CreateError(JsValue.FromString(errorMessage)); } JsContext.SetException(errorValue); return(JsValue.Undefined); } return(JsValue.Undefined); } nativeFunctions.Add(nativeSetFunction); JsValue setMethodValue = JsValue.CreateFunction(nativeSetFunction); descriptorValue.SetProperty("set", setMethodValue, true); typeValue.DefineProperty(fieldName, descriptorValue); } }
/// <summary> /// vm.runInContext compiles code, then runs it in context and returns the result. A (V8) context comprises a global object, /// together with a set of built-in objects and functions. /// Running code does not have access to local scope and the global object held within context will be used as the global object for code. /// ///<example> /// Example: compile and execute code in a existing context. /// <code> /// var util = require('util'), /// vm = require('vm'), /// initSandbox = { /// animal: 'cat', /// count: 2 /// }, /// context = vm.createContext(initSandbox); /// /// vm.runInContext('count += 1; name = "CATT"', context, 'myfile.vm'); /// console.log(util.inspect(context)); /// /// // { animal: 'cat', count: 3, name: 'CATT' } ///</code> ///</example> ///<remarks> /// Note that createContext will perform a shallow clone of the supplied sandbox object in order to initialize the global object of the freshly constructed context. /// /// Note that running untrusted code is a tricky business requiring great care. To prevent accidental global variable leakage, vm.runInContext is quite useful, but safely running untrusted code requires a separate process. /// /// In case of syntax error in code, vm.runInContext emits the syntax error to stderr and throws an exception. /// </remarks> /// </summary> /// <param name="code"></param> /// <param name="context"></param> /// <param name="filename">filename is optional, it's used only in stack traces.</param> /// <returns></returns> public object runInContext(JsString code, JsContext context, JsString filename) { return null; }
public JsParameterDeclaration(JsContext context, JsParser parser) : base(context, parser) { }