BadScript 2
Loading...
Searching...
No Matches
BadRuntime.cs
Go to the documentation of this file.
5using BadScript2.IO;
18
22namespace BadScript2;
23
27public class BadRuntime : IDisposable
28{
32 private readonly List<Action<BadExecutionContext>> m_ConfigureContext = new List<Action<BadExecutionContext>>();
33
34 private readonly List<Action<BadExecutionContext, string, BadModuleImporter>> m_ConfigureModuleImporter = new List<Action<BadExecutionContext, string, BadModuleImporter>>();
35
39 private readonly List<Action<BadExecutionContextOptions>> m_ConfigureOptions =
40 new List<Action<BadExecutionContextOptions>>();
41
45 private readonly List<IDisposable> m_Disposables = new List<IDisposable>();
46
51
55 private Func<BadExecutionContext, IEnumerable<BadExpression>, BadObject> m_Executor = Executor;
56
62 {
63 m_Options = options;
64
66 {
68 }
69 }
70
74 public BadRuntime() : this(new BadExecutionContextOptions()) { }
75
76 private BadModuleStore ModuleStore { get; } = new BadModuleStore();
77 private BadModuleImporter? Importer { get; set; }
78
79 //private BadModuleImporter? Importer { get; set; }
80
84 public void Dispose()
85 {
86 foreach (IDisposable disposable in m_Disposables)
87 {
88 disposable.Dispose();
89 }
90 }
91
97 {
100
101 //Copy the configurators that are not part of the options
104
105 return r;
106 }
107
113 public BadRuntime UseExecutor(Func<BadExecutionContext, IEnumerable<BadExpression>, BadObject> executor)
114 {
115 m_Executor = executor;
116
117 return this;
118 }
119
126 private static BadObject Executor(BadExecutionContext ctx, IEnumerable<BadExpression> exprs)
127 {
128 return ctx.ExecuteScript(exprs);
129 }
130
136 public BadRuntime UseLogMask(params BadLogMask[] mask)
137 {
138 BadLogWriterSettings.Instance.Mask = BadLogMask.GetMask(mask);
139
140 return this;
141 }
142
148 public BadRuntime UseLogMask(params string[] mask)
149 {
150 return UseLogMask(mask.Select(x => (BadLogMask)x).ToArray());
151 }
152
159 {
160 BadConsole.SetConsole(console);
161
162 return this;
163 }
164
171 {
172 writer.Register();
173 m_Disposables.Add(writer);
174
175 return this;
176 }
177
178
184 {
185 return UseLogWriter(new BadConsoleLogWriter());
186 }
187
193 public BadRuntime UseFileLogWriter(string path)
194 {
195 return UseLogWriter(new BadFileLogWriter(path));
196 }
197
203 public BadRuntime LoadSettings(string settingsFile, IFileSystem? fileSystem = null)
204 {
205 BadLogger.Log("Loading Settings...", "Settings");
206 BadSettingsReader settingsReader = new BadSettingsReader(
208 fileSystem ?? BadFileSystem.Instance,
209 settingsFile
210 );
211
213 BadLogger.Log("Settings loaded!", "Settings");
214
215 return this;
216 }
217
223 {
225
226 return this;
227 }
228
235 {
237 {
239 }
240
241 BadDebugger.Attach(debugger);
242
243 return this;
244 }
245
251 {
253
254 foreach (Action<BadExecutionContextOptions> config in m_ConfigureOptions)
255 {
256 config(opts);
257 }
258
259 return opts;
260 }
261
266 public BadExecutionContext CreateContext(string workingDirectory)
267 {
269
270 foreach (Action<BadExecutionContext> config in m_ConfigureContext)
271 {
272 config(ctx);
273 }
274
275 ctx.Scope.AddSingleton(this);
276 BadModuleImporter importer;
277 if (Importer == null)
278 {
279 importer = Importer = new BadModuleImporter(ModuleStore);
280 }
281 else
282 {
283 importer = Importer = Importer.Clone();
284 }
285
286 foreach (Action<BadExecutionContext, string, BadModuleImporter> action in m_ConfigureModuleImporter)
287 {
288 action(ctx, workingDirectory, importer);
289 }
290
291 ctx.Scope.AddSingleton(importer);
292
293 return ctx;
294 }
295
301 public BadRuntimeExecutionResult Execute(IEnumerable<BadExpression> expressions, string workingDirectory)
302 {
303 BadExecutionContext ctx = CreateContext(workingDirectory);
304
305 BadObject? result = m_Executor(ctx, expressions);
306 BadObject exports = ctx.Scope.GetExports();
307
308 return new BadRuntimeExecutionResult(result, exports);
309 }
310
311
317 public BadRuntimeExecutionResult Execute(string source)
318 {
320 }
321
328 public BadRuntimeExecutionResult Execute(string source, string file)
329 {
330 return Execute(Parse(source, file), Path.GetDirectoryName(BadFileSystem.Instance.GetFullPath(file)) ?? BadFileSystem.Instance.GetCurrentDirectory());
331 }
332
339 public BadRuntimeExecutionResult ExecuteFile(string file, IFileSystem? fileSystem = null)
340 {
341 var fs = fileSystem ?? BadFileSystem.Instance;
342 return Execute(ParseFile(file, fs), fs.GetFullPath(Path.GetDirectoryName(fs.GetFullPath(file)) ?? fs.GetCurrentDirectory()));
343 }
344
350 public static IEnumerable<BadExpression> Parse(string source)
351 {
352 return Parse(source, "<memory>");
353 }
354
361 public static IEnumerable<BadExpression> Parse(string source, string file)
362 {
363 BadSourceParser parser = BadSourceParser.Create(file, source);
364
365 IEnumerable<BadExpression> result = parser.Parse();
366
367 if (BadNativeOptimizationSettings.Instance.UseConstantFoldingOptimization)
368 {
369 result = BadConstantFoldingOptimizer.Optimize(result);
370 }
371
372 if (BadNativeOptimizationSettings.Instance.UseConstantSubstitutionOptimization)
373 {
375 }
376
377 return result;
378 }
379
386 public static IEnumerable<BadExpression> ParseFile(string file, IFileSystem? fileSystem = null)
387 {
388 var fs = fileSystem ?? BadFileSystem.Instance;
389 return Parse(fs.ReadAllText(file), file);
390 }
391
392
398 {
399 return UseImportHandler((workingDir, _) => new BadLocalPathImportHandler(this, workingDir, fs ?? BadFileSystem.Instance));
400 }
401
407 public BadRuntime ConfigureContextOptions(params Action<BadExecutionContextOptions>[] action)
408 {
409 m_ConfigureOptions.AddRange(action);
410
411 return this;
412 }
413
420 public BadRuntime UseApi(BadInteropApi api, bool replace = false)
421 {
422 if (replace)
423 {
424 return ConfigureContextOptions(opt => opt.AddOrReplaceApi(api));
425 }
426
427 return ConfigureContextOptions(opt => opt.AddApi(api));
428 }
429
430
437 public BadRuntime UseApis(IEnumerable<BadInteropApi> apis, bool replace = false)
438 {
439 if (replace)
440 {
441 return ConfigureContextOptions(opt => opt.AddOrReplaceApis(apis));
442 }
443
444 return ConfigureContextOptions(opt => opt.AddApis(apis));
445 }
446
447
454 {
455 return ConfigureContextOptions(opts => opts.AddExtension<T>());
456 }
457
458
464 public BadRuntime UseImportHandler(Func<BadExecutionContext, string, BadModuleImporter, BadImportHandler> f)
465 {
466 return ConfigureModuleImporter((ctx, workingDir, importer) => importer.AddHandler(f(ctx, workingDir, importer)));
467 }
468
474 public BadRuntime UseImportHandler(Func<BadExecutionContext, BadModuleImporter, BadImportHandler> f)
475 {
476 return ConfigureModuleImporter((ctx, importer) => importer.AddHandler(f(ctx, importer)));
477 }
478
484 public BadRuntime UseImportHandler(Func<BadModuleImporter, BadImportHandler> f)
485 {
486 return ConfigureModuleImporter(importer => importer.AddHandler(f(importer)));
487 }
488
494 public BadRuntime UseImportHandler(Func<string, BadModuleImporter, BadImportHandler> f)
495 {
496 return ConfigureModuleImporter((workingDir, importer) => importer.AddHandler(f(workingDir, importer)));
497 }
498
505 {
506 return ConfigureModuleImporter(importer => importer.AddHandler(handler));
507 }
508
509
515 public BadRuntime ConfigureModuleImporter(Action<BadExecutionContext, string, BadModuleImporter> action)
516 {
517 m_ConfigureModuleImporter.Add(action);
518
519 return this;
520 }
521
527 public BadRuntime ConfigureModuleImporter(Action<BadExecutionContext, BadModuleImporter> action)
528 {
529 return ConfigureModuleImporter((ctx, _, importer) => action(ctx, importer));
530 }
531
537 public BadRuntime ConfigureModuleImporter(Action<BadModuleImporter> action)
538 {
539 return ConfigureModuleImporter((_, _, importer) => action(importer));
540 }
541
547 public BadRuntime ConfigureModuleImporter(Action<string, BadModuleImporter> action)
548 {
549 return ConfigureModuleImporter((_, workingDir, importer) => action(workingDir, importer));
550 }
551
558 public BadRuntime UseSingleton<T>(T obj) where T : class
559 {
560 return ConfigureContext(ctx => ctx.Scope.AddSingleton(obj));
561 }
562
568 public BadRuntime ConfigureContext(params Action<BadExecutionContext>[] action)
569 {
570 m_ConfigureContext.AddRange(action);
571
572 return this;
573 }
574}
Exposes the BadScript Runtime Functionality to Consumers.
Definition BadRuntime.cs:28
BadModuleImporter? Importer
Definition BadRuntime.cs:77
BadRuntime UseDebugger(IBadDebugger debugger)
Configures the Runtime to use the specified Debugger.
BadRuntime UseFileLogWriter(string path)
Configures the Runtime to use the file log writer implementation.
BadExecutionContextOptions CreateOptions()
Creates and configures the Options for the Context.
BadRuntime UseLogWriter(BadLogWriter writer)
Configures the Runtime to use the specified logwriter implementation.
BadRuntime UseExtension< T >()
Uses a specified Extension.
BadRuntime ConfigureModuleImporter(Action< string, BadModuleImporter > action)
Configures the Module Importer.
BadModuleStore ModuleStore
Definition BadRuntime.cs:76
BadRuntime UseLogMask(params BadLogMask[] mask)
Configures the Runtime to use the specified log masks.
readonly List< Action< BadExecutionContextOptions > > m_ConfigureOptions
Configuration Actions for the Options.
Definition BadRuntime.cs:39
readonly List< Action< BadExecutionContext, string, BadModuleImporter > > m_ConfigureModuleImporter
Definition BadRuntime.cs:34
Func< BadExecutionContext, IEnumerable< BadExpression >, BadObject > m_Executor
The Executor Function used to Execute a list of Expressions.
Definition BadRuntime.cs:55
BadRuntime Clone()
Clone this Runtime.
Definition BadRuntime.cs:96
BadRuntimeExecutionResult Execute(IEnumerable< BadExpression > expressions, string workingDirectory)
Executes the specified expressions.
BadRuntime UseLogMask(params string[] mask)
Configures the Runtime to use the specified log masks.
BadRuntime UseConsoleLogWriter()
Configures the Runtime to use the default log writer implementation(log to console)
BadRuntime ConfigureModuleImporter(Action< BadModuleImporter > action)
Configures the Module Importer.
static BadObject Executor(BadExecutionContext ctx, IEnumerable< BadExpression > exprs)
The Default Executor Function.
readonly List< IDisposable > m_Disposables
List of Disposables.
Definition BadRuntime.cs:45
BadRuntime UseLocalModules(IFileSystem? fs=null)
Registers the Local Path Handler to the Module Importer.
BadRuntime UseImportHandler(Func< string, BadModuleImporter, BadImportHandler > f)
Configures a Module Importer to use the specified Import Handler.
BadRuntime()
Creates a new BadScript Runtime with the default options.
Definition BadRuntime.cs:74
BadRuntime UseSingleton< T >(T obj)
Uses the specified Singleton Object.
BadRuntime UseCompilerApi()
Configures the Runtime to expose the CompilerAPI to the Scripts.
BadRuntime UseImportHandler(BadImportHandler handler)
Configures a Module Importer to use the specified Import Handler.
BadRuntime UseImportHandler(Func< BadExecutionContext, BadModuleImporter, BadImportHandler > f)
Configures a Module Importer to use the specified Import Handler.
readonly List< Action< BadExecutionContext > > m_ConfigureContext
Configuration Actions for the Context.
Definition BadRuntime.cs:32
BadRuntime UseApi(BadInteropApi api, bool replace=false)
Adds or Replaces a specified API.
BadRuntime(BadExecutionContextOptions options)
Creates a new BadScript Runtime with the specified options.
Definition BadRuntime.cs:61
BadRuntime UseImportHandler(Func< BadExecutionContext, string, BadModuleImporter, BadImportHandler > f)
Configures a Module Importer to use the specified Import Handler.
BadRuntime ConfigureModuleImporter(Action< BadExecutionContext, BadModuleImporter > action)
Configures the Module Importer.
BadRuntime LoadSettings(string settingsFile, IFileSystem? fileSystem=null)
Loads the specified settings file.
BadRuntime UseImportHandler(Func< BadModuleImporter, BadImportHandler > f)
Configures a Module Importer to use the specified Import Handler.
BadRuntime UseApis(IEnumerable< BadInteropApi > apis, bool replace=false)
Adds or Replaces a specified APIs.
BadRuntimeExecutionResult Execute(string source)
Executes the specified script.
BadRuntime ConfigureContext(params Action< BadExecutionContext >[] action)
Adds the specified Context Configuration Actions.
void Dispose()
Disposes all Disposables.
Definition BadRuntime.cs:84
BadRuntime ConfigureContextOptions(params Action< BadExecutionContextOptions >[] action)
Adds the specified Option Configuration Actions.
BadRuntime UseExecutor(Func< BadExecutionContext, IEnumerable< BadExpression >, BadObject > executor)
Configures the Runtime to use the specified Executor.
BadExecutionContext CreateContext(string workingDirectory)
Creates a new Context with the configured Options.
BadRuntime UseConsole(IBadConsole console)
Configures the Runtime to use the specified console implementation.
BadRuntime ConfigureModuleImporter(Action< BadExecutionContext, string, BadModuleImporter > action)
Configures the Module Importer.
static IEnumerable< BadExpression > Parse(string source)
Parses the specified source.
BadRuntimeExecutionResult ExecuteFile(string file, IFileSystem? fileSystem=null)
Executes the specified script file.
static IEnumerable< BadExpression > ParseFile(string file, IFileSystem? fileSystem=null)
Parses the specified script file.
readonly BadExecutionContextOptions m_Options
The Options for the Context.
Definition BadRuntime.cs:50
BadRuntimeExecutionResult Execute(string source, string file)
Executes the specified script.
static IEnumerable< BadExpression > Parse(string source, string file)
Parses the specified source.
Implements a Mask for Log Messages.
Definition BadLogMask.cs:7
static BadLogMask GetMask(params BadLogMask[] masks)
Returns a combined mask of all masks provided.
Public facing interface for a logger.
Definition BadLogger.cs:7
static void Log(string message)
Writes a Log to the Message Handler.
Definition BadLogger.cs:26
Implements a simple file writer for the log system.
void Register()
Registers the Log Writer to the Log System.
Wrapper class for the console abstraction.
Definition BadConsole.cs:12
static void SetConsole(IBadConsole console)
Sets the Current Console Implementation.
Definition BadConsole.cs:58
Public Debugger Interface.
static bool IsAttached
True if a debugger is attached.
static void Attach(IBadDebugger debugger)
Attaches a debugger to the system.
static void Detach()
Detaches the debugger from the system.
Public interface for the filesystem abstraction of the BadScript Engine.
static IFileSystem Instance
File System implementation.
static BadExpression Optimize(BadExpression expr)
Optimizes the given expression.
Contains the Implementation of the Constant Substitution Optimization This optimization replaces expr...
static IEnumerable< BadExpression > Optimize(BadConstantSubstitutionOptimizerScope scope, IEnumerable< BadExpression > expressions)
Substitutes all variables in the expressions with their constant value.
The Parser of the Language. It turns Source Code into an Expression Tree.
static BadSourceParser Create(string fileName, string source)
Creates a BadSourceParser Instance based on the source and filename provided.
static IEnumerable< BadExpression > Parse(string fileName, string source)
Parses a BadExpression from the Source Reader.
The Execution Context. Every execution of a script needs a context the script is running in....
BadObject ExecuteScript(IEnumerable< BadExpression > expressions)
Executes an enumeration of expressions and returns the last value.
BadScope Scope
The Root Scope of the Context.
Provides settings for creating a new BadExecutionContext
BadExecutionContext Build()
Builds a new BadExecutionContext with the options provided in this Options Instance.
void AddApi(BadInteropApi api)
Adds a new Api to the context.
BadExecutionContextOptions Clone()
Clones this BadExecutionContextOptions instance.
BadObject GetExports()
Returns the exported key value pairs of the scope.
Definition BadScope.cs:717
Implements an Interop API for the BS2 Language.
Public Extension API for the BS2 Runtime.
Defines the shape of the import handler for the module importer.
The Class that manages the importing of modules.
BadModuleImporter Clone(bool onlyTransient=true)
Is the store for all loaded modules.
The Base Class for all BadScript Objects.
Definition BadObject.cs:14
Public Api for the Settings System.
Helper class that can be used to automatically load a settings object from a file.
static void SetRootSettings(BadSettings settings)
Sets the Root Settings Object.
static T Instance
Returns the Instance of the Settings Provider.
static bool HasRootSettings
Returns true if the root setting has been set.
static BadSettings RootSettings
Returns the Root Settings Object.
Reads a JSON file and returns the resulting BadSettings Object.
BadSettings ReadSettings()
Returns a new Instance of BadSettings with all source files loaded.
Interface that abstracts the console.
Defines the Debugging Interface.
Defines the interface for a file system.
Definition IFileSystem.cs:7
string GetCurrentDirectory()
Returns the Current Directory.
string GetFullPath(string path)
Returns the full path of the given path.
Contains Writer Implementations for the BadScript Logging System.
Contains Logging system for the BadScript Runtime.
Definition BadLog.cs:6
Contains a Console Abstraction Layer to be able to Simulate Console Input/Output over the Network.
Definition BadConsole.cs:6
Contains the debugging abstractions for the BadScript2 Runtime.
Definition BadDebugger.cs:7
Contains IO Implementation for the BadScript2 Runtime.
Contains the BadScript2 Constant Folding Optimizations.
Contains the BadScript2 Constant Substitution Optimizations.
Contains the Expressions for the BadScript2 Language.
Contains the Parser for the BadScript2 Language.
Contains the Interop Abstractions and Implementations for the BadScript2 Language.
Contains the Runtime Objects.
Definition BadArray.cs:10
Contains Runtime Settings Objects.
Contains the Compiler for the BadVirtualMachine.
Contains the Runtime Implementation.
Contains the Settings Implementation.
The main namespace for the BadScript2 Language.
Definition BadConsole.cs:6
Gets returned by the bad runtime when an execution is finished.