public static void LoadLibrary(WrenVM vm) { vm.Interpret("timer", "timer", _timerSource); ObjClass timer = (ObjClass)vm.FindVariable("timer", "Timer"); vm.Primitive(timer.ClassObj, "startTimer_(_,_)", StartTimer); }
static void RunRepl() { WrenVM vm = new WrenVM(); LibraryLoader.LoadLibraries(vm); Console.WriteLine("-- wren v0.0.0"); string line = ""; for (; ;) { Console.Write("> "); line += Console.ReadLine() + "\n"; if (OpenBrackets(line) > 0) { continue; } // TODO: Handle failure. vm.Interpret("Prompt", "Prompt", line); line = ""; } }
public static void LoadLibrary(WrenVM vm, string libraryName, string typeName) { Type wrenLibrary = Type.GetType("Wren.Core.Library.LoadLibrary"); var path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var di = new DirectoryInfo(path); foreach (var file in di.GetFiles(libraryName)) { try { var nextAssembly = Assembly.LoadFrom(file.FullName); foreach (var type in nextAssembly.GetTypes()) { if (type.GetCustomAttributes(wrenLibrary, false).Length > 0) { // This class implements the interface var m = type.GetMethod("LoadLibrary"); m.Invoke(null, new object[] { vm }); } } } catch (BadImageFormatException) { // Not a .net assembly - ignore } } }
public static void LoadLibrary(WrenVM vm) { vm.Interpret("scheduler", "scheduler", _schedulerSource); ObjClass scheduler = (ObjClass)vm.FindVariable("scheduler", "Scheduler"); vm.Primitive(scheduler.ClassObj, "captureMethods_()", CaptureMethods); vm.Interpret("scheduler", "scheduler", "Scheduler.captureMethods_()"); }
static string LoadModule(WrenVM VM, string Module) { if (File.Exists(Module)) { return(File.ReadAllText(Module)); } return(""); }
public static void LoadLibrary(WrenVM vm) { vm.Interpret("", "", MetaLibSource); ObjClass meta = (ObjClass)vm.FindVariable("Meta"); vm.Primitive(meta.ClassObj, "eval(_)", Eval); }
static WrenForeignMethodFn BindForeignMethod(WrenVM VM, string Module, string ClassName, bool Static, string Sig) { if (ClassName == "DotNet" && Static) { if (Sig == "SomeFunction()") { return(SomeFunction); } } return(null); }
private static string loadAutoMapperModule(WrenVM vm, string name) { Dictionary <string, ForeignModule> modules; if (generatedModules.TryGetValue(vm, out modules)) { return(modules?[name]?.GetSource()); } return(null); }
static void Main(string[] args) { Console.Title = "Wren.NET Test"; WrenConfig Cfg = new WrenConfig(BindForeignMethod, LoadModule); WrenVM WVM = Cfg.NewVM(); string Test = File.ReadAllText("test.wren"); Console.WriteLine("{0}\n\n----------", Test); WVM.Interpret("Test", Test); Console.ReadLine(); }
public static void LoadLibrary(WrenVM vm) { vm.Interpret("io", "io", IoSource); ObjClass file = (ObjClass)vm.FindVariable("io", "File"); vm.Primitive(file.ClassObj, "open_(_,_)", Open); vm.Primitive(file.ClassObj, "sizePath_(_,_)", SizePath); vm.Primitive(file, "close_(_)", Close); vm.Primitive(file, "descriptor", Descriptor); vm.Primitive(file, "readBytes_(_,_)", ReadBytes); vm.Primitive(file, "size_(_)", Size); }
static void RunRepl() { WrenVM vm = new WrenVM(null, null); LibraryLoader.LoadLibraries(vm); WrenScript.LoadLibrary <ScriptTest>(vm); Console.WriteLine("-- wren v0.0.0"); string line = ""; for (; ;) { Console.Write("> "); line += Console.ReadLine() + "\n"; if (OpenBrackets(line) > 0) { continue; } // TODO: Handle failure. var result = new WrenVM.ResultRef(); var coroutine = vm.InterpretCoroutines("Prompt", "Prompt", line, result); // quick and dirty sim of unity's coroutines Stack <IEnumerator> stack = new Stack <IEnumerator>(); stack.Push(coroutine); while (stack.Count > 0) { if (!stack.Peek().MoveNext()) { stack.Pop(); } else { if (stack.Peek().Current is IEnumerator) { stack.Push(stack.Peek().Current as IEnumerator); } else { Console.WriteLine("yielded " + stack.Peek().Current); } } } line = ""; } }
static int RunFile(string path) { if (!File.Exists(path)) { return(66); // File Not Found } _loadedFile = path; string source = File.ReadAllText(path); WrenVM vm = new WrenVM { LoadModuleFn = LoadModule }; LibraryLoader.LoadLibraries(vm); return((int)vm.Interpret("main", path, source)); }
public void WithAutoMapper() { var vm = new WrenVM(); vm.AutoMap <Test>(); var wrVM = new WeakReference <WrenVM>(vm); vm = null; GC.Collect(); WrenVM _; Assert.IsFalse(wrVM.TryGetTarget(out _)); }
private static void checkInitialization(WrenVM vm) { Dictionary <string, ForeignModule> module; if (generatedModules.TryGetValue(vm, out module)) { return; } vm.Config.LoadModule += loadAutoMapperModule; vm.Config.BindForeignMethod += bindAutoMapperMethod; vm.Config.BindForeignClass += bindAutoMapperClass; generatedModules.Add(vm, new Dictionary <string, ForeignModule>()); mainModuleClasses.Add(vm, new Dictionary <string, ForeignClass>()); }
private static WrenForeignClassMethods bindAutoMapperClass(WrenVM vm, string module, string className) { Dictionary <string, ForeignClass> classes; if (module == WrenVM.InterpetModule && mainModuleClasses.TryGetValue(vm, out classes)) { return(classes?[className]?.Bind()); } Dictionary <string, ForeignModule> modules; if (generatedModules.TryGetValue(vm, out modules)) { return(modules?[module]?.Classes?[className]?.Bind()); } return(null); }
private static WrenForeignMethod bindAutoMapperMethod(WrenVM vm, string module, string className, bool isStatic, string signature) { Dictionary <string, ForeignClass> classes; if (module == WrenVM.InterpetModule && mainModuleClasses.TryGetValue(vm, out classes)) { return(classes?[className]?.Functions?[signature]); } Dictionary <string, ForeignModule> modules; if (generatedModules.TryGetValue(vm, out modules)) { return(modules?[module]?.Classes?[className]?.Functions?[signature]); } return(null); }
/// <summary> /// Automatically maps the given types to make their marked interfaces accessible from Wren. /// If the module name is the <see cref="WrenVM.InterpetModule"/>, the code will be interpreted immediately. /// </summary> /// <param name="vm">The <see cref="WrenVM"/> to make the types available to.</param> /// <param name="moduleName">The name of the module to place the types into.</param> /// <param name="targets">The types to map.</param> public static void AutoMap(this WrenVM vm, string moduleName, params Type[] targets) { checkInitialization(vm); if (moduleName == WrenVM.InterpetModule) { var classes = mainModuleClasses.GetValue(vm, _ => null); foreach (var target in targets) { var foreignClass = new ForeignClass(target); classes.Add(foreignClass.Name, foreignClass); vm.Interpret(foreignClass.Source); } return; } var modules = generatedModules.GetValue(vm, _ => null); ForeignModule module; if (modules.ContainsKey(moduleName)) { module = modules[moduleName]; if (module.Used && TreatModificationAfterLoadAsError) { throw new LoadedModuleModifiedException(moduleName); } } else { module = new ForeignModule(); modules.Add(moduleName, module); } foreach (var target in targets) { module.Add(target); } }
static bool Eval(WrenVM vm, Obj[] args, int stackStart) { if (args[stackStart + 1] is ObjString) { // Eval the code in the module where the calling function was defined. Obj callingFn = vm.Fiber.GetFrame().Fn; ObjModule module = (callingFn is ObjFn) ? ((ObjFn)callingFn).Module : ((ObjClosure)callingFn).Function.Module; // Compile it. ObjFn fn = Compiler.Compile(vm, module, "", args[stackStart + 1].ToString(), false); if (fn == null) { vm.Fiber.Error = Obj.MakeString("Could not compile source code."); return(false); } // TODO: Include the compile errors in the runtime error message. // Create a fiber to run the code in. ObjFiber evalFiber = new ObjFiber(fn) { Caller = vm.Fiber }; // Switch to the fiber. args[stackStart] = evalFiber; return(false); } vm.Fiber.Error = Obj.MakeString("Source code must be a string."); return(false); }
/// <summary> /// Automatically maps the given types to make their marked interfaces accessible from Wren. /// Places them into the <see cref="WrenVM.InterpetModule"/> as the generated code will be interpreted immediately. /// </summary> /// <param name="vm">The <see cref="WrenVM"/> to make the types available to.</param> /// <param name="targets">The types to map.</param> public static void AutoMap(this WrenVM vm, params Type[] targets) { vm.AutoMap(WrenVM.InterpetModule, targets); }
private static bool SizePath(WrenVM vm, Obj[] args, int stackStart) { return(true); }
private static bool Open(WrenVM vm, Obj[] args, int stackStart) { return(true); }
static void SomeFunction(WrenVM VM) { VM.ReturnString("Hello Wren World #" + Rand.Next(1, 100) + "!"); }
private static bool ReadBytes(WrenVM vm, Obj[] args, int stackStart) { return(true); }
private static bool Descriptor(WrenVM vm, Obj[] args, int stackStart) { return(true); }
public static void LoadLibrary(WrenVM vm) { Scheduler.LoadLibrary(vm); Io.LoadLibrary(vm); Timer.LoadLibrary(vm); }
/// <summary> /// Automatically maps the given type to make its marked interface accessible from Wren. /// Optionally places it into a module other than the <see cref="WrenVM.InterpetModule"/>. /// <para/> /// If no other module is specified, the generated code will be interpreted immediately. /// </summary> /// <typeparam name="TTarget">The type to map.</typeparam> /// <param name="vm">The <see cref="WrenVM"/> to make the type available to.</param> /// <param name="moduleName">The name of the module to place the type into.</param> public static void AutoMap <TTarget>(this WrenVM vm, string moduleName = WrenVM.InterpetModule) { vm.AutoMap(moduleName, typeof(TTarget)); }
private static void Main(string[] args) { var config = new WrenConfig(); config.Write += (vm, text) => Console.Write(text); config.Error += (type, module, line, message) => Console.WriteLine($"Error [{type}] in module [{module}] at line {line}:{Environment.NewLine}{message}"); config.LoadModule += (vm, module) => $"System.print(\"Module [{module}] loaded!\")"; config.BindForeignMethod += (vm, module, className, isStatic, signature) => { Console.WriteLine($"BindForeignMethod called: It's called {signature}, is part of {className} and is {(isStatic ? "static" : "not static")}."); return(signature == "sayHi(_)" ? sayHi : (WrenForeignMethod)null); }; config.BindForeignClass += (vm, module, className) => className == "Test" ? new WrenForeignClassMethods { Allocate = alloc } : null; using (var vm = new WrenVM(config)) { var result = vm.Interpret("System.print(\"Hi from Wren!\")"); result = vm.Interpret("var helloTo = Fn.new { |name|\n" + "System.print(\"Hello, %(name)!\")\n" + "}"); result = vm.Interpret("helloTo.call(\"IronWren\")"); var someFnHandle = vm.MakeCallHandle("call(_)"); vm.EnsureSlots(2); vm.GetVariable(WrenVM.InterpetModule, "helloTo", 0); vm.SetSlotString(1, "foreign method"); result = vm.Call(someFnHandle); result = vm.Interpret("foreign class Test {\n" + "construct new() { }\n" + "isForeign { true }\n" + "foreign sayHi(to)\n" + "}\n" + "var test = Test.new()\n" + "test.sayHi(\"wren\")\n" + "\n" + "import \"TestModule\"\n"); vm.EnsureSlots(1); vm.GetVariable(WrenVM.InterpetModule, "test", 0); result = vm.Call(vm.MakeCallHandle("isForeign")); var isTestClassForeign = vm.GetSlotBool(0); Console.WriteLine("Test class is foreign: " + isTestClassForeign); vm.AutoMap(typeof(WrenMath)); vm.Interpret("System.print(\"The sine of pi is: %(Math.sin(Math.pi))!\")"); Console.WriteLine($"And C# says it's: {Math.Sin(Math.PI)}"); Console.WriteLine(); var sw = new Stopwatch(); for (var i = 0; i < 3; ++i) { sw.Restart(); vm.Interpret("for (i in 1..1000000) Math.sin(Math.pi)"); sw.Stop(); Console.WriteLine("1000000 iterations took " + sw.ElapsedMilliseconds + "ms."); } var results = new double[1000000]; sw.Restart(); for (var i = 0; i < 1000000; ++i) { results[i] = Math.Sin(Math.PI); } sw.Stop(); Console.WriteLine("1000000 iterations in C# took " + sw.ElapsedMilliseconds + "ms."); vm.AutoMap <WrenVector>(); vm.Interpret("var vec = Vector.new(1, 2)"); vm.Interpret("vec.print()"); vm.Interpret("System.print(\"Vector's X is: %(vec.x)\")"); vm.Interpret("System.print(\"Vector's Y is: %(vec.y)\")"); Console.ReadLine(); Console.Clear(); Console.WriteLine("You may now write Wren code that will be interpreted!"); Console.WriteLine("Use file:[path] to interpret a file!"); Console.WriteLine(); while (true) { var input = Console.ReadLine(); if (input.StartsWith("file:")) { vm.Interpret(File.ReadAllText(input.Substring(5))); } else { vm.Interpret(input); } } } }
private static void sayHi(WrenVM vm) { var to = vm.GetSlotString(1); Console.WriteLine("Foreign method says hi to " + to + "!"); }
private static void alloc(WrenVM vm) { Console.WriteLine("Allocator called!"); vm.SetSlotNewForeign(0, 1); }
private void test(WrenVM vm) { }