public static void Initialize() { // Atomic Modules CoreModule.Initialize(); MathModule.Initialize(); EngineModule.Initialize(); InputModule.Initialize(); IOModule.Initialize(); ResourceModule.Initialize(); AudioModule.Initialize(); GraphicsModule.Initialize(); SceneModule.Initialize(); Atomic2DModule.Initialize(); NavigationModule.Initialize(); NetworkModule.Initialize(); PhysicsModule.Initialize(); EnvironmentModule.Initialize(); UIModule.Initialize(); #if ATOMIC_DESKTOP IPCModule.Initialize(); #endif AtomicAppModule.Initialize(); ScriptModule.Initialize(); AtomicNETScriptModule.Initialize(); AtomicNETNativeModule.Initialize(); PlayerModule.Initialize(); IntPtr coreptr = csi_Atomic_NETCore_Initialize(eventDispatchDelegate, updateDispatchDelegate); NETCore core = (coreptr == IntPtr.Zero ? null : NativeCore.WrapNative <NETCore>(coreptr)); if (core != null) { AtomicNET.RegisterSubsystem("NETCore", core); } context = core.Context; NativeCore.Initialize(); CSComponentCore.Initialize(); #if ATOMIC_DESKTOP string[] arguments = Environment.GetCommandLineArgs(); foreach (string arg in arguments) { AppBase.AddArgument(arg); } #endif }
/// <summary> /// Loads new bytecode into a script module. /// </summary> public async Task <bool> HotloadAsync(ScriptModule module, byte[] IL) { // TODO: Serialise the current state of the loaded assembly // TODO: Restore the old state into the new assembly var state = module.RuntimeState; state.Unload(); var result = state.Load(IL); return(result); }
public static object CompileBootfile(object libs) { AssemblyGenAttributes aga = ScriptDomainManager.Options.AssemblyGenAttributes; ScriptDomainManager.Options.AssemblyGenAttributes &= ~AssemblyGenAttributes.EmitDebugInfo; ScriptDomainManager.Options.AssemblyGenAttributes &= ~AssemblyGenAttributes.GenerateDebugAssemblies; ScriptDomainManager.Options.AssemblyGenAttributes &= ~AssemblyGenAttributes.DisableOptimizations; if (ScriptDomainManager.Options.DebugMode) { ScriptDomainManager.Options.AssemblyGenAttributes |= AssemblyGenAttributes.EmitDebugInfo; ScriptDomainManager.Options.AssemblyGenAttributes |= AssemblyGenAttributes.GenerateDebugAssemblies; //ScriptDomainManager.Options.AssemblyGenAttributes |= AssemblyGenAttributes.DisableOptimizations; ScriptDomainManager.Options.DebugCodeGeneration = false; } else { ScriptDomainManager.Options.DebugCodeGeneration = false; } ScriptDomainManager.Options.AssemblyGenAttributes |= AssemblyGenAttributes.SaveAndReloadAssemblies; ScriptDomainManager.CurrentManager.Snippets.CurrentAssembly = Compiler.Generator.CurrentAssemblyGen = AssemblyGen.CreateModuleAssembly("ironscheme.boot.new.dll"); //Console.WriteLine(new Cons(libs).PrettyPrint); CodeBlock cb = IronSchemeLanguageContext.CompileExpr(libs as Cons); cb.ExplicitCodeContextExpression = null; cb.Name = "ironscheme.boot.new"; ScriptCode sc = cc.LanguageContext.CompileSourceCode(cb); sc.LibraryGlobals = Compiler.SimpleGenerator.libraryglobals; sc.LibraryGlobalsN = Compiler.SimpleGenerator.libraryglobalsN; sc.LibraryGlobalsX = Compiler.SimpleGenerator.libraryglobalsX; sc.SourceUnit.IsVisibleToDebugger = true; ScriptModule sm = ScriptDomainManager.CurrentManager.CreateModule("ironscheme.boot.new", sc); ScriptDomainManager.Options.AssemblyGenAttributes = aga; sc.ClearCache(); Compiler.SimpleGenerator.ClearGlobals(); return(TRUE); }
public void AttachScript(string path, string type_name) { ScriptModule module = new ScriptModule(type_name, type_name, ModuleTypeEnum.OBJECT, false, path); ScriptInterpreter.Interpreter.Programm.AttachScript(module); InternalScriptType type = new InternalScriptType() { Name = type_name, Alias = type_name, Module = module, }; ScriptInterpreter.Interpreter.Programm.InternalTypes.Add(type); }
static ScriptModule GetModule(string name) { if (Modules.ContainsKey(name)) { return(Modules[name]); } var module = new ScriptModule { Name = name }; Modules[name] = module; return(module); }
public DynamicFunction GetFunction(string name) { if (ScriptModule == null) { return(null); } object val; if (!ScriptModule.TryGetVariable(name, out val)) { return(null); } return(new DynamicFunction(val)); }
public static void Initialize() { // Atomic Modules CoreModule.Initialize(); MathModule.Initialize(); EngineModule.Initialize(); InputModule.Initialize(); IOModule.Initialize(); ResourceModule.Initialize(); AudioModule.Initialize(); GraphicsModule.Initialize(); SceneModule.Initialize(); Atomic2DModule.Initialize(); Atomic3DModule.Initialize(); NavigationModule.Initialize(); NetworkModule.Initialize(); PhysicsModule.Initialize(); EnvironmentModule.Initialize(); UIModule.Initialize(); IPCModule.Initialize(); AtomicAppModule.Initialize(); ScriptModule.Initialize(); AtomicNETScriptModule.Initialize(); AtomicNETNativeModule.Initialize(); PlayerModule.Initialize(); coreDelegates = new CoreDelegates(); coreDelegates.eventDispatch = NativeCore.EventDispatch; coreDelegates.updateDispatch = NativeCore.UpdateDispatch; IntPtr coreptr = csb_Atomic_NETCore_Initialize(ref coreDelegates); NETCore core = (coreptr == IntPtr.Zero ? null : NativeCore.WrapNative <NETCore>(coreptr)); if (core != null) { AtomicNET.RegisterSubsystem("NETCore", core); } context = core.Context; NativeCore.Initialize(); CSComponentCore.Initialize(); }
internal static void Initialize(IronSchemeLanguageProvider ironSchemeLanguageProvider) { lp = ironSchemeLanguageProvider; se = lp.GetEngine() as IronSchemeScriptEngine; scriptmodule = ScriptDomainManager.CurrentManager.Host.DefaultModule as ScriptModule; ModuleContext mc = new ModuleContext(scriptmodule); mc.CompilerContext = new CompilerContext(SourceUnit.CreateSnippet(se, "")); cc = new CodeContext(scriptmodule.Scope, se.GetLanguageContext(), mc); binder = new IronScheme.Actions.IronSchemeActionBinder(cc); Generator.initme = true; }
public override void OnInspectorGUI() { base.OnInspectorGUI(); GUILayout.BeginVertical(); module = target as ScriptModule; string text = EditorGUILayout.TextArea(module.initCodes, GUI.skin.textArea, GUILayout.Height(100f)); if (module.initCodes != text) { RegisterUndo(); module.initCodes = text; } string text2 = EditorGUILayout.TextArea(module.fixedUpdateCodes, GUI.skin.textArea, GUILayout.Height(400f)); if (module.fixedUpdateCodes != text2) { RegisterUndo(); module.fixedUpdateCodes = text2; } GUILayout.EndVertical(); }
protected int RunInteractiveLoop() { if (_module == null) { _module = ScriptDomainManager.CurrentManager.Host.DefaultModule as ScriptModule; } OnInteractiveLoopStart(); int?res = null; do { if (Options.HandleExceptions) { try { res = TryInteractiveAction(); #if SILVERLIGHT } catch (ExitProcessException e) { res = e.ExitCode; #endif } catch (Exception e) { // There should be no unhandled exceptions in the interactive session // We catch all exceptions here, and just display it, // and keep on going _console.WriteLine(_engine.FormatException(e), Style.Error); } } else { res = TryInteractiveAction(); } } while (res == null); return(res.Value); }
private void SetupCommands(CommandDispatcher dispatcher) { dispatcher.RegisterCommand("quit", "Stops the node and exits", (args) => Terminate()); if (gui != null) { dispatcher.RegisterCommand("gui.log", "Switches the gui to log view", (args) => gui.ShowLog(args)); dispatcher.RegisterCommand("gui.graph", "Switches the gui to graph view", (args) => gui.ShowGraph(args)); } dispatcher.RegisterCommand("help", "Lists available commands", (args) => dispatcher.Commands.ToList().ForEach(x => logger.Message($"{x.Name}\t{x.Description}"))); foreach (var method in api.Methods) { dispatcher.RegisterCommand("api." + method.Name, "API CALL", (args) => ExecuteAPI(method.Name, args)); } dispatcher.RegisterCommand("script.assemble", "Assembles a .asm file into Phantasma VM script format", (args) => ScriptModule.AssembleFile(args)); dispatcher.RegisterCommand("script.disassemble", $"Disassembles a {ScriptFormat.Extension} file into readable Phantasma assembly", (args) => ScriptModule.DisassembleFile(args)); dispatcher.RegisterCommand("script.compile", "Compiles a .sol file into Phantasma VM script format", (args) => ScriptModule.CompileFile(args)); dispatcher.RegisterCommand("wallet.balance", "Shows the current wallet balance", (args) => WalletModule.Balance(node.Address, api, logger, args)); dispatcher.RegisterCommand("wallet.transfer", "Generates a new transfer transaction", (args) => WalletModule.Transfer(node.Keys, api, logger, args)); dispatcher.RegisterCommand("wallet.stake", $"Stakes {Nexus.StakingTokenSymbol}", (args) => WalletModule.Stake(node.Keys, api, logger, args)); dispatcher.RegisterCommand("file.upload", "Uploads a file into Phantasma", (args) => FileModule.Upload(node.Keys, api, logger, args)); }
public ErrorInfo(Exception exception) { if (exception.Data.Count == 0) { ModuleName = ScriptEngine.EngineBase.Interpreter.ScriptInterpreter.Interpreter.CurrentModule.Name; LineNumber = ScriptEngine.EngineBase.Interpreter.ScriptInterpreter.Interpreter.CurrentLine; SourceLine = ScriptEngine.EngineBase.Interpreter.ScriptInterpreter.Interpreter.CurrentModule.GetCodeLine(LineNumber); Description = exception.Message; Cause = null; } else { ModuleName = Convert.ToString(exception.Data["module"]); LineNumber = Convert.ToInt32(exception.Data["line"]); ScriptModule module = ScriptEngine.EngineBase.Interpreter.ScriptInterpreter.Interpreter.Programm.Modules.Get(ModuleName); if (module != null) { SourceLine = module.GetCodeLine(LineNumber); } Description = Convert.ToString(exception.Data["message"]);; Cause = null; } }
private void SetupCommands(CommandDispatcher dispatcher) { ModuleLogger.Init(logger, gui); var minimumFee = this.mempool != null ? mempool.MinimumFee : 1; dispatcher.RegisterCommand("quit", "Stops the node and exits", (args) => Terminate()); if (gui != null) { dispatcher.RegisterCommand("gui.log", "Switches the gui to log view", (args) => gui.ShowLog(args)); dispatcher.RegisterCommand("gui.graph", "Switches the gui to graph view", (args) => gui.ShowGraph(args)); } dispatcher.RegisterCommand("help", "Lists available commands", (args) => dispatcher.Commands.ToList().ForEach(x => logger.Message($"{x.Name}\t{x.Description}"))); foreach (var method in nexusApi.Methods) { dispatcher.RegisterCommand("api." + method.Name, "API CALL", (args) => ExecuteAPI(method.Name, args)); } dispatcher.RegisterCommand("script.assemble", "Assembles a .asm file into Phantasma VM script format", (args) => ScriptModule.AssembleFile(args)); dispatcher.RegisterCommand("script.disassemble", $"Disassembles a {ScriptFormat.Extension} file into readable Phantasma assembly", (args) => ScriptModule.DisassembleFile(args)); dispatcher.RegisterCommand("script.compile", "Compiles a .sol file into Phantasma VM script format", (args) => ScriptModule.CompileFile(args)); dispatcher.RegisterCommand("wallet.open", "Opens a wallet from a WIF key", (args) => WalletModule.Open(args)); dispatcher.RegisterCommand("wallet.create", "Creates new a wallet", (args) => WalletModule.Create(args)); dispatcher.RegisterCommand("wallet.balance", "Shows the current wallet balance", (args) => WalletModule.Balance(nexusApi, restPort, neoScanAPI, args)); dispatcher.RegisterCommand("wallet.transfer", "Generates a new transfer transaction", (args) => WalletModule.Transfer(nexusApi, minimumFee, neoAPI, args)); dispatcher.RegisterCommand("wallet.stake", $"Stakes {DomainSettings.StakingTokenSymbol}", (args) => WalletModule.Stake(nexusApi, args)); dispatcher.RegisterCommand("wallet.airdrop", "Does a batch transfer from a .csv", (args) => WalletModule.Airdrop(args, nexusApi, minimumFee)); dispatcher.RegisterCommand("wallet.migrate", "Migrates a validator to another address ", (args) => { WalletModule.Migrate(args, nexusApi, minimumFee); if (mempool != null) { mempool.SetKeys(WalletModule.Keys); } }); dispatcher.RegisterCommand("file.upload", "Uploads a file into Phantasma", (args) => FileModule.Upload(WalletModule.Keys, nexusApi, args)); dispatcher.RegisterCommand("oracle.read", "Read transaction from oracle", (args) => { var hash = Hash.Parse(args[0]); var reader = nexus.CreateOracleReader(); var tx = reader.ReadTransaction("neo", "neo", hash); logger.Message(tx.Transfers[0].interopAddress.Text); }); if (mempool != null) { dispatcher.RegisterCommand("mempool.list", "Shows mempool pending transaction list", (args) => { var txs = mempool.GetTransactions(); foreach (var tx in txs) { logger.Message(tx.ToString()); } }); } dispatcher.RegisterCommand("neo.deploy", "Deploys a contract into NEO", (args) => { if (args.Length != 2) { throw new CommandException("Expected: WIF avm_path"); } var avmPath = args[1]; if (!File.Exists(avmPath)) { throw new CommandException("path for avm not found"); } var keys = Neo.Core.NeoKeys.FromWIF(args[0]); var script = File.ReadAllBytes(avmPath); var scriptHash = Neo.Utils.CryptoUtils.ToScriptHash(script); logger.Message("Deploying contract " + scriptHash); try { var tx = neoAPI.DeployContract(keys, script, Base16.Decode("0710"), 0x05, Neo.Core.ContractProperties.HasStorage | Neo.Core.ContractProperties.Payable, "Contract", "1.0", "Author", "*****@*****.**", "Description"); logger.Success("Deployed contract via transaction: " + tx.Hash); } catch (Exception e) { logger.Error("Failed to deploy contract: " + e.Message); } }); dispatcher.RegisterCommand("exit", "Terminates the node", (args) => { this.Terminate(); }); if (useSimulator) { dispatcher.RegisterCommand("simulator.timeskip", $"Skips minutse in simulator", (args) => { if (args.Length != 1) { throw new CommandException("Expected: minutes"); } var minutes = int.Parse(args[0]); simulator.CurrentTime += TimeSpan.FromMinutes(minutes); logger.Success($"Simulator time advanced by {minutes}"); }); } }
static void Parse(string value) { var json = JsonConvert.DeserializeObject <JToken>(value); var comments = json.FindTokens("comment"); ScriptModule module = null; foreach (var comment in comments) { var attributes = comment["attributes"] as JObject; if (attributes == null) { continue; } var brief = (comment["brief"] ?? "").ToString(); var full = (comment["full"] ?? "").ToString(); if (attributes.ContainsKey("scriptModule")) { var scriptModule = attributes["scriptModule"]; var name = scriptModule.ToString(); if (!name.Contains('/')) { name = "FuseJS/" + name; } module = GetModule(name); module.Documentation = full; } if (attributes.ContainsKey("scriptMethod")) { var scriptMethod = attributes["scriptMethod"]; var result = new ScriptMethod { Name = scriptMethod["name"].ToString(), Documentation = full }; module.Methods.Add(result); foreach (var parameter in scriptMethod["parameters"]) { result.Parameters.Add(parameter.ToString()); } } if (attributes.ContainsKey("scriptProperty")) { var scriptProperty = attributes["scriptProperty"]; var result = new ScriptProperty { Name = scriptProperty.ToString(), Documentation = full }; // Extract type and docs if (result.Name.StartsWith("(")) { var i = result.Name.IndexOf(')', 1); result.Type = result.Name.Substring(1, i - 1); var parts = result.Name.Substring(i + 1).Trim().Split(' '); result.Name = parts[0]; result.Documentation = string.Join(" ", parts.Skip(1)); } // Skip duplicates if (module.Properties.Any(p => p.Name == result.Name)) { continue; } module.Properties.Add(result); } if (attributes.ContainsKey("scriptEvent")) { var scriptEvent = attributes["scriptEvent"]; var result = new ScriptEvent { Name = scriptEvent.ToString(), Documentation = brief }; module.Events.Add(result); } } }
internal static object Load(object filename, bool loadinmemory) { CodeContext cc = IronScheme.Compiler.BaseHelper.cc; // sneaky.... string path = GetPath(filename as string); switch (Path.GetExtension(path)) { case ".exe": case ".dll": const string newbf = "build/ironscheme.boot.dll"; if (File.Exists(newbf) && File.GetLastWriteTime(newbf) > File.GetLastWriteTime(path)) { File.Delete("ironscheme.boot.old.dll"); File.Delete("ironscheme.boot.pdb"); File.Move("ironscheme.boot.dll", "ironscheme.boot.old.dll"); File.Move(newbf, "ironscheme.boot.dll"); const string newpdb = "build/ironscheme.boot.pdb"; if (File.Exists(newpdb)) { File.Move(newpdb, "ironscheme.boot.pdb"); } } // just reference.? MethodInfo entry = null; Type ilmergefixup = typeof(Builtins).Assembly.GetType("#", false); if (ilmergefixup != null && BootfileAssembly == null) { entry = ilmergefixup.GetMethod("Initialize"); BootfileAssembly = typeof(Builtins).Assembly; } else { Assembly ext = AssemblyLoad(path, loadinmemory); // now that it is loaded, make sure we remove compiletime types IronScheme.Compiler.ClrGenerator.ClearTypesFrom(ext); foreach (Type t in ext.GetExportedTypes()) { if (t.BaseType == typeof(CustomSymbolDictionary)) { List <Type> ii = new List <Type>(t.GetInterfaces()); if (ii.Contains(typeof(IModuleDictionaryInitialization))) { entry = t.GetMethod("Initialize"); if (entry != null) { break; } } } } } if (entry == null) { // what now? throw new ArgumentException("No entry point"); } else { IModuleDictionaryInitialization init = Activator.CreateInstance(entry.DeclaringType) as IModuleDictionaryInitialization; CodeContext ccc = new CodeContext(cc, init as IAttributesCollection); init.InitializeModuleDictionary(ccc); var t = Delegate.CreateDelegate(typeof(CallTarget0), ccc, entry) as CallTarget0; return(t()); } default: { // check for already compiled version string cfn = Path.ChangeExtension(path, ".dll"); if (File.Exists(cfn)) { DateTime ct = File.GetLastWriteTime(cfn); if (!File.Exists(path) || ct >= File.GetLastWriteTime(path)) { if (File.GetLastWriteTime(Path.Combine(ApplicationDirectory, "IronScheme.dll")) <= ct || cfn.EndsWith("ironscheme.boot.dll")) { path = cfn; goto case ".dll"; } } } cfn = Path.ChangeExtension(path, ".new.dll"); if (File.Exists(cfn)) { DateTime ct = File.GetLastWriteTime(cfn); if (!File.Exists(path) || ct >= File.GetLastWriteTime(path)) { if (File.GetLastWriteTime(Path.Combine(ApplicationDirectory, "IronScheme.dll")) <= ct || cfn.EndsWith("ironscheme.boot.dll")) { path = cfn; goto case ".dll"; } } } if (!File.Exists(path)) { throw new FileNotFoundException("Not found", path); } SourceUnit su = ScriptDomainManager.CurrentManager.Host.TryGetSourceFileUnit(cc.LanguageContext.Engine, path, Encoding.Default); #if DEBUG Stopwatch sw = Stopwatch.StartNew(); #endif ScriptModule sm = ScriptDomainManager.CurrentManager.CompileModule(Path.GetFileNameWithoutExtension(path), su); Compiler.SimpleGenerator.ClearGlobals(); #if DEBUG Trace.WriteLine(sw.ElapsedMilliseconds, "Compile module: " + sm.FileName); sw = Stopwatch.StartNew(); #endif object result = sm.GetScripts()[0].Run(sm); #if DEBUG Trace.WriteLine(sw.ElapsedMilliseconds, "Run script: " + sm.GetScripts()[0].SourceUnit); #endif return(result); } } }
public T EvaluateAs <T>(string expression, ScriptModule module) { return(ConvertObject <T>(Evaluate(expression, module))); }
/// <summary> /// Gets a full qualified name of a script type given a sub-namespace. /// </summary> /// <param name="sourceFile">Source file.</param> /// <returns>The qualified name.</returns> public string GetQualifiedScriptTypeName(PhpSourceFile /*!*/ sourceFile) { Debug.Assert(sourceFile != null); return(GetQualifiedScriptTypeName(ScriptModule.GetSubnamespace(sourceFile))); }
public ScriptProcedure(ScriptModule module, string name) { _module = module; _name = name; _arguments = new object[0]; }
public ScriptProcedure(ScriptModule module, string name, object[] args) { _module = module; _name = name; _arguments = args; }
/// <summary> /// Invoked when the script assembly is being loaded from CLR assembly. /// </summary> protected override void LoadedFromAssembly(Assembly/*!*/ assembly) { script = new ScriptModule(this, ""); }
public static object CompileCore(object expr) { // fast path for really simple stuff if (expr is SymbolId) { CallTarget0 n = delegate { return(SymbolValue(expr)); }; return(Closure.Create(n)); } AssemblyGenAttributes aga = ScriptDomainManager.Options.AssemblyGenAttributes; ScriptDomainManager.Options.AssemblyGenAttributes &= ~AssemblyGenAttributes.EmitDebugInfo; ScriptDomainManager.Options.AssemblyGenAttributes &= ~AssemblyGenAttributes.GenerateDebugAssemblies; ScriptDomainManager.Options.AssemblyGenAttributes &= ~AssemblyGenAttributes.DisableOptimizations; if (ScriptDomainManager.Options.DebugMode) { ScriptDomainManager.Options.AssemblyGenAttributes |= AssemblyGenAttributes.EmitDebugInfo; ScriptDomainManager.Options.AssemblyGenAttributes |= AssemblyGenAttributes.GenerateDebugAssemblies; ScriptDomainManager.Options.AssemblyGenAttributes |= AssemblyGenAttributes.DisableOptimizations; ScriptDomainManager.Options.DebugCodeGeneration = true; } else { ScriptDomainManager.Options.DebugCodeGeneration = false; } ScriptDomainManager.Options.AssemblyGenAttributes |= AssemblyGenAttributes.SaveAndReloadAssemblies; // if you ever want to inspect the emitted dll's comment the following out (or skip in the debugger), use with care ScriptDomainManager.Options.AssemblyGenAttributes &= ~AssemblyGenAttributes.SaveAndReloadAssemblies; var prevt = IronScheme.Compiler.Generator.AllowTransientBinding; var prevag = Compiler.Generator.CurrentAssemblyGen; if ((ScriptDomainManager.Options.AssemblyGenAttributes & AssemblyGenAttributes.SaveAndReloadAssemblies) != 0) { IronScheme.Compiler.Generator.AllowTransientBinding = false; ScriptDomainManager.CurrentManager.Snippets.CurrentAssembly = Compiler.Generator.CurrentAssemblyGen = AssemblyGen.CreateModuleAssembly(null); } else { Compiler.Generator.CurrentAssemblyGen = ScriptDomainManager.Options.DebugMode ? ScriptDomainManager.CurrentManager.Snippets.DebugAssembly : ScriptDomainManager.CurrentManager.Snippets.Assembly; } int c = Interlocked.Increment(ref evalcounter); #if DEBUG Stopwatch sw = Stopwatch.StartNew(); #endif //Console.WriteLine(new Cons(expr).PrettyPrint); try { CodeBlock cb = IronSchemeLanguageContext.CompileExpr(new Cons(expr)); cb.ExplicitCodeContextExpression = null; ScriptCode sc = Context.LanguageContext.CompileSourceCode(cb); //wrap #if DEBUG sw.Stop(); Trace.WriteLine(sw.Elapsed.TotalMilliseconds, string.Format("compile - eval-core({0:D3})", c)); sw = Stopwatch.StartNew(); #endif try { sc.LibraryGlobals = Compiler.SimpleGenerator.libraryglobals; sc.LibraryGlobalsN = Compiler.SimpleGenerator.libraryglobalsN; sc.LibraryGlobalsX = Compiler.SimpleGenerator.libraryglobalsX; ScriptModule sm = ScriptDomainManager.CurrentManager.CreateModule(string.Format("eval-core({0:D3})", c), sc); sc = sm.GetScripts()[0]; #if DEBUG sw.Stop(); Trace.WriteLine(sw.Elapsed.TotalMilliseconds, string.Format("compile*- eval-core({0:D3})", c)); #endif CallTarget0 compiled = delegate { #if DEBUG try { sw = Stopwatch.StartNew(); #endif return(sc.Run(Context.ModuleContext.Module)); #if DEBUG } finally { sw.Stop(); Trace.WriteLine(sw.Elapsed.TotalMilliseconds, string.Format("run - eval-core({0:D3})", c)); } #endif }; return(Closure.Create(compiled)); } catch (Variable.UnInitializedUsageException ex) { CallTarget0 err = delegate { return(AssertionViolation(ex.Variable.Block.Name, ex.Message, UnGenSym(ex.Variable.Name))); }; return(Closure.Create(err)); } finally { BoundExpression.Fixups.Clear(); BoundExpression.FixupTypes.Clear(); Compiler.Generator.CurrentAssemblyGen = prevag; ScriptDomainManager.Options.AssemblyGenAttributes = aga; IronScheme.Compiler.Generator.AllowTransientBinding = prevt; sc.ClearCache(); Compiler.SimpleGenerator.ClearGlobals(); Compiler.ClrGenerator.compiletimetypes.Clear(); } } catch (Continuation) { throw; } catch (Exception ex) { var who = ex.Data["Who"]; return(SyntaxError(who ?? FALSE, ex.Message, FALSE, FALSE)); } }
protected int RunInteractiveLoop() { if (_module == null) { _module = ScriptDomainManager.CurrentManager.Host.DefaultModule as ScriptModule; } OnInteractiveLoopStart(); int? res = null; do { if (Options.HandleExceptions) { try { res = TryInteractiveAction(); #if SILVERLIGHT } catch (ExitProcessException e) { res = e.ExitCode; #endif } catch (Exception e) { // There should be no unhandled exceptions in the interactive session // We catch all exceptions here, and just display it, // and keep on going _console.WriteLine(_engine.FormatException(e), Style.Error); } } else { res = TryInteractiveAction(); } } while (res == null); return res.Value; }
internal protected virtual LanguageContext GetLanguageContext(ScriptModule module) { Contract.RequiresNotNull(module, "module"); return(GetLanguageContext(module.GetCompilerOptions(this))); }
/// <summary> /// Creates compiler options initialized by the options associated with the module. /// </summary> public virtual CompilerOptions GetModuleCompilerOptions(ScriptModule module) // TODO: internal protected { return(GetDefaultCompilerOptions()); }
/// <summary> /// Добавить в программу обьект используя его тип. /// </summary> /// <param name="type"></param> /// <param name="as_global"></param> public void AddObjectOfType(Type type, LibraryClassAttribute attribute = null) { if (attribute == null) { attribute = (LibraryClassAttribute)Attribute.GetCustomAttribute(type, typeof(LibraryClassAttribute), false); } ScriptModule module = new ScriptModule(attribute.Name, attribute.Alias, ModuleTypeEnum.OBJECT, attribute.AsGlobal) { InstanceType = type }; foreach (PropertyInfo property in type.GetTypeInfo().GetProperties().Where(m => m.GetCustomAttributes(typeof(LibraryClassPropertyAttribute), false).Length > 0)) { LibraryClassPropertyAttribute property_attr = property.GetCustomAttribute <LibraryClassPropertyAttribute>(false); IVariableReference reference = ReferenceFactory.Create(type, property); IVariable var = new Variable() { Name = property_attr.Name, Alias = property_attr.Alias, Public = true, Reference = reference }; module.Variables.Add(property_attr.Name, var); if (attribute.AsGlobal) { _programm.GlobalVariables.Add(var); } } foreach (MethodInfo method in type.GetTypeInfo().DeclaredMethods.Where(m => m.GetCustomAttributes(typeof(LibraryClassMethodAttribute), false).Length > 0)) { LibraryClassMethodAttribute method_attr = method.GetCustomAttribute <LibraryClassMethodAttribute>(false); IFunction function = module.Functions.Create(method_attr.Name, true); if (function == null) { throw new Exception($"Функция с именем {method_attr.Name} уже существует."); } function.Alias = method_attr.Alias; function.Type = method.ReturnType == typeof(void) ? FunctionTypeEnum.PROCEDURE : FunctionTypeEnum.FUNCTION; GetFunctionParameters(function, method); function.Method = LibraryMethodFactory.Create(type, method); if (attribute.AsGlobal) { _programm.GlobalFunctions.Add(function); } } if (module.Variables.Get("ЭтотОбъект") == null && !attribute.AsGlobal) { module.Variables.Create("ЭтотОбъект", true, module.ModuleScope); } _programm.Modules.Add(module); if (attribute.RegisterType) { _programm.InternalTypes.Add(new InternalScriptType() { Name = attribute.Name, Alias = attribute.Alias, Description = attribute.Alias, Module = module, Type = type }); } if (attribute.AsGlobal) { _programm.GlobalVariables.Add(new Variable() { Name = attribute.Name, Alias = attribute.Alias, Reference = new SimpleReference() }); } }
public Entry(FullPath path, ScriptModule scriptModule, ScriptAssembly containingAssembly) { ScriptModule = scriptModule; ContainingAssembly = containingAssembly; Path = path; }
/// <summary> /// Invoked when the script assembly is being loaded from CLR assembly. /// </summary> protected override void LoadedFromAssembly(Assembly /*!*/ assembly) { script = new ScriptModule(this, ""); }
public ScriptHost(IScriptEnvironment environment) { Contract.RequiresNotNull(environment, "environment"); _environment = environment; _defaultModule = null; }
public virtual void ModuleCreated(ScriptModule module) { // nop }
public CompilerOptions GetModuleCompilerOptions(ScriptModule module) { throw new NotSupportedException(); }
public static object CompileLibrary(object filename, object content) { IronScheme.Compiler.Generator.LocationHint = null; AssemblyGenAttributes aga = ScriptDomainManager.Options.AssemblyGenAttributes; ScriptDomainManager.Options.AssemblyGenAttributes &= ~AssemblyGenAttributes.EmitDebugInfo; ScriptDomainManager.Options.AssemblyGenAttributes &= ~AssemblyGenAttributes.GenerateDebugAssemblies; ScriptDomainManager.Options.AssemblyGenAttributes &= ~AssemblyGenAttributes.DisableOptimizations; if (ScriptDomainManager.Options.DebugMode) { ScriptDomainManager.Options.AssemblyGenAttributes |= AssemblyGenAttributes.EmitDebugInfo; ScriptDomainManager.Options.AssemblyGenAttributes |= AssemblyGenAttributes.GenerateDebugAssemblies; ScriptDomainManager.Options.AssemblyGenAttributes |= AssemblyGenAttributes.DisableOptimizations; ScriptDomainManager.Options.DebugCodeGeneration = true; } else { ScriptDomainManager.Options.DebugCodeGeneration = false; } ScriptDomainManager.Options.AssemblyGenAttributes |= AssemblyGenAttributes.SaveAndReloadAssemblies; //object[] arr = ListToVector(content as Cons); //0: id //1: name //2: version //3: imp* //4: vis* //5: inv* //6: subst //7: env //8: visit code //9: invoke code //10: guard code //11: guard req? //12: visible? Compiler.Generator.AllowTransientBinding = false; ScriptDomainManager.CurrentManager.Snippets.CurrentAssembly = Compiler.Generator.CurrentAssemblyGen = AssemblyGen.CreateModuleAssembly(filename as string); try { CodeBlock cb = IronSchemeLanguageContext.CompileExpr(new Cons(content)); cb.ExplicitCodeContextExpression = null; cb.Name = ""; ScriptCode sc = cc.LanguageContext.CompileSourceCode(cb, filename as string); sc.LibraryGlobals = Compiler.SimpleGenerator.libraryglobals; sc.LibraryGlobalsN = Compiler.SimpleGenerator.libraryglobalsN; sc.LibraryGlobalsX = Compiler.SimpleGenerator.libraryglobalsX; sc.SourceUnit.IsVisibleToDebugger = true; ScriptModule sm = ScriptDomainManager.CurrentManager.CreateModule(Path.GetFileNameWithoutExtension(filename as string), sc); // clean up transient non-generative types, could maybe also have used AllowTransientBinding to check? IronScheme.Runtime.R6RS.Records.ClearTypesFrom(Compiler.Generator.CurrentAssemblyGen); ScriptDomainManager.Options.AssemblyGenAttributes = aga; Compiler.SimpleGenerator.ClearGlobals(); return(TRUE); } finally { Compiler.Generator.AllowTransientBinding = true; } }
internal static void CreateDefaultModule(ref ScriptModule defaultModule) { // create a module and throw it away if there is already one: ScriptModule module = ScriptDomainManager.CurrentManager.CreateModule("<default>", null, ScriptCode.EmptyArray); Utilities.MemoryBarrier(); Interlocked.CompareExchange<ScriptModule>(ref defaultModule, module, null); }
public ScriptModuleAssemblyLoadContext(ScriptModule module) : base(isCollectible: true) { _module = module; }