BadScript 2
Loading...
Searching...
No Matches
BadRuntime.cs
Go to the documentation of this file.
1using System.Globalization;
2
7using BadScript2.IO;
20
24namespace BadScript2;
25
29public class BadRuntime : IDisposable
30{
34 private readonly List<Action<BadExecutionContext>> m_ConfigureContext = new List<Action<BadExecutionContext>>();
35
36 private readonly List<Action<BadExecutionContext, string, BadModuleImporter>> m_ConfigureModuleImporter =
37 new List<Action<BadExecutionContext, string, BadModuleImporter>>();
38
42 private readonly List<Action<BadExecutionContextOptions>> m_ConfigureOptions =
43 new List<Action<BadExecutionContextOptions>>();
44
48 private readonly List<IDisposable> m_Disposables = new List<IDisposable>();
49
54
58 private Func<BadExecutionContext, IEnumerable<BadExpression>, BadObject> m_Executor = Executor;
59
65 {
66 m_Options = options;
67
69 {
71 }
72 }
73
77 public BadRuntime() : this(new BadExecutionContextOptions()) { }
78
79 public CultureInfo Culture { get; private set; } = CultureInfo.InvariantCulture;
80
81 private BadModuleStore ModuleStore { get; } = new BadModuleStore();
82
83 private BadModuleImporter? Importer { get; set; }
84
85#region IDisposable Members
86
87 //private BadModuleImporter? Importer { get; set; }
88
92 public void Dispose()
93 {
94 foreach (IDisposable disposable in m_Disposables)
95 {
96 disposable.Dispose();
97 }
98 }
99
100#endregion
101
107 {
110
111 //Copy the configurators that are not part of the options
114
115 return r;
116 }
117
123 public BadRuntime UseExecutor(Func<BadExecutionContext, IEnumerable<BadExpression>, BadObject> executor)
124 {
125 m_Executor = executor;
126
127 return this;
128 }
129
136 private static BadObject Executor(BadExecutionContext ctx, IEnumerable<BadExpression> exprs)
137 {
138 return ctx.ExecuteScript(exprs);
139 }
140
146 public BadRuntime UseLogMask(params BadLogMask[] mask)
147 {
148 BadLogWriterSettings.Instance.Mask = BadLogMask.GetMask(mask);
149
150 return this;
151 }
152
158 public BadRuntime UseLogMask(params string[] mask)
159 {
160 return UseLogMask(mask.Select(x => (BadLogMask)x)
161 .ToArray()
162 );
163 }
164
171 {
172 BadConsole.SetConsole(console);
173
174 return this;
175 }
176
183 {
184 writer.Register();
185 m_Disposables.Add(writer);
186
187 return this;
188 }
189
190
196 {
197 return UseLogWriter(new BadConsoleLogWriter());
198 }
199
205 public BadRuntime UseFileLogWriter(string path)
206 {
207 return UseLogWriter(new BadFileLogWriter(path));
208 }
209
215 public BadRuntime LoadSettings(string settingsFile, IFileSystem? fileSystem = null)
216 {
217 BadLogger.Log("Loading Settings...", "Settings");
218
220 fileSystem ?? BadFileSystem.Instance,
221 settingsFile
222 );
223
225 BadLogger.Log("Settings loaded!", "Settings");
226
227 return this;
228 }
229
235 {
237
238 return this;
239 }
240
247 {
249 {
251 }
252
253 BadDebugger.Attach(debugger);
254
255 return this;
256 }
257
263 {
265
266 foreach (Action<BadExecutionContextOptions> config in m_ConfigureOptions)
267 {
268 config(opts);
269 }
270
271 return opts;
272 }
273
278 public BadExecutionContext CreateContext(string workingDirectory)
279 {
281 .Build();
282
283 foreach (Action<BadExecutionContext> config in m_ConfigureContext)
284 {
285 config(ctx);
286 }
287
288 ctx.Scope.AddSingleton(this);
289 BadModuleImporter importer;
290
291 if (Importer == null)
292 {
293 importer = Importer = new BadModuleImporter(ModuleStore);
294 }
295 else
296 {
297 importer = Importer = Importer.Clone();
298 }
299
300 foreach (Action<BadExecutionContext, string, BadModuleImporter> action in m_ConfigureModuleImporter)
301 {
302 action(ctx, workingDirectory, importer);
303 }
304
305 ctx.Scope.AddSingleton(importer);
306
307 return ctx;
308 }
309
315 public BadRuntimeExecutionResult Execute(IEnumerable<BadExpression> expressions, string workingDirectory)
316 {
317 BadExecutionContext ctx = CreateContext(workingDirectory);
318
319 BadObject? result = m_Executor(ctx, expressions);
320 BadObject exports = ctx.Scope.GetExports();
321
322 return new BadRuntimeExecutionResult(result, exports);
323 }
324
325
331 public BadRuntimeExecutionResult Execute(string source)
332 {
334 }
335
342 public BadRuntimeExecutionResult Execute(string source, string file)
343 {
344 return Execute(Parse(source, file),
345 Path.GetDirectoryName(BadFileSystem.Instance.GetFullPath(file)) ??
347 );
348 }
349
356 public BadRuntimeExecutionResult ExecuteFile(string file, IFileSystem? fileSystem = null)
357 {
358 IFileSystem? fs = fileSystem ?? BadFileSystem.Instance;
359
360 return Execute(ParseFile(file, fs),
361 fs.GetFullPath(Path.GetDirectoryName(fs.GetFullPath(file)) ?? fs.GetCurrentDirectory())
362 );
363 }
364
370 public static IEnumerable<BadExpression> Parse(string source)
371 {
372 return Parse(source, "<memory>");
373 }
374
381 public static IEnumerable<BadExpression> Parse(string source, string file)
382 {
383 BadSourceParser parser = BadSourceParser.Create(file, source);
384
385 IEnumerable<BadExpression> result = parser.Parse();
386
387 if (BadNativeOptimizationSettings.Instance.UseConstantFoldingOptimization)
388 {
389 result = BadConstantFoldingOptimizer.Optimize(result);
390 }
391
392 if (BadNativeOptimizationSettings.Instance.UseConstantSubstitutionOptimization)
393 {
395 }
396
397 return result;
398 }
399
406 public static IEnumerable<BadExpression> ParseFile(string file, IFileSystem? fileSystem = null)
407 {
408 IFileSystem? fs = fileSystem ?? BadFileSystem.Instance;
409
410 return Parse(fs.ReadAllText(file), file);
411 }
412
413
419 {
420 return UseImportHandler((workingDir, _) =>
421 new BadLocalPathImportHandler(this, workingDir, fs ?? BadFileSystem.Instance)
422 );
423 }
424
430 public BadRuntime ConfigureContextOptions(params Action<BadExecutionContextOptions>[] action)
431 {
432 m_ConfigureOptions.AddRange(action);
433
434 return this;
435 }
436
443 public BadRuntime UseApi(BadInteropApi api, bool replace = false)
444 {
445 if (replace)
446 {
447 return ConfigureContextOptions(opt => opt.AddOrReplaceApi(api));
448 }
449
450 return ConfigureContextOptions(opt => opt.AddApi(api));
451 }
452
453
460 public BadRuntime UseApis(IEnumerable<BadInteropApi> apis, bool replace = false)
461 {
462 if (replace)
463 {
464 return ConfigureContextOptions(opt => opt.AddOrReplaceApis(apis));
465 }
466
467 return ConfigureContextOptions(opt => opt.AddApis(apis));
468 }
469
470
477 {
478 return ConfigureContextOptions(opts => opts.AddExtension<T>());
479 }
480
481
487 public BadRuntime UseImportHandler(Func<BadExecutionContext, string, BadModuleImporter, BadImportHandler> f)
488 {
489 return ConfigureModuleImporter((ctx, workingDir, importer) => importer.AddHandler(f(ctx, workingDir, importer))
490 );
491 }
492
498 public BadRuntime UseImportHandler(Func<BadExecutionContext, BadModuleImporter, BadImportHandler> f)
499 {
500 return ConfigureModuleImporter((ctx, importer) => importer.AddHandler(f(ctx, importer)));
501 }
502
508 public BadRuntime UseImportHandler(Func<BadModuleImporter, BadImportHandler> f)
509 {
510 return ConfigureModuleImporter(importer => importer.AddHandler(f(importer)));
511 }
512
518 public BadRuntime UseImportHandler(Func<string, BadModuleImporter, BadImportHandler> f)
519 {
520 return ConfigureModuleImporter((workingDir, importer) => importer.AddHandler(f(workingDir, importer)));
521 }
522
529 {
530 return ConfigureModuleImporter(importer => importer.AddHandler(handler));
531 }
532
533
539 public BadRuntime ConfigureModuleImporter(Action<BadExecutionContext, string, BadModuleImporter> action)
540 {
541 m_ConfigureModuleImporter.Add(action);
542
543 return this;
544 }
545
551 public BadRuntime ConfigureModuleImporter(Action<BadExecutionContext, BadModuleImporter> action)
552 {
553 return ConfigureModuleImporter((ctx, _, importer) => action(ctx, importer));
554 }
555
561 public BadRuntime ConfigureModuleImporter(Action<BadModuleImporter> action)
562 {
563 return ConfigureModuleImporter((_, _, importer) => action(importer));
564 }
565
571 public BadRuntime ConfigureModuleImporter(Action<string, BadModuleImporter> action)
572 {
573 return ConfigureModuleImporter((_, workingDir, importer) => action(workingDir, importer));
574 }
575
582 public BadRuntime UseSingleton<T>(T obj) where T : class
583 {
584 return ConfigureContext(ctx => ctx.Scope.AddSingleton(obj));
585 }
586
592 public BadRuntime ConfigureContext(params Action<BadExecutionContext>[] action)
593 {
594 m_ConfigureContext.AddRange(action);
595
596 return this;
597 }
598
599 public BadRuntime UseCulture(CultureInfo culture)
600 {
601 Culture = culture;
602
603 return this;
604 }
605
606 public BadRuntime UseCulture(string culture)
607 {
608 return UseCulture(new CultureInfo(culture));
609 }
610}
Exposes the BadScript Runtime Functionality to Consumers.
Definition BadRuntime.cs:30
BadModuleImporter? Importer
Definition BadRuntime.cs:83
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:81
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:42
readonly List< Action< BadExecutionContext, string, BadModuleImporter > > m_ConfigureModuleImporter
Definition BadRuntime.cs:36
Func< BadExecutionContext, IEnumerable< BadExpression >, BadObject > m_Executor
The Executor Function used to Execute a list of Expressions.
Definition BadRuntime.cs:58
BadRuntime Clone()
Clone this Runtime.
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:48
BadRuntime UseCulture(string culture)
BadRuntime UseLocalModules(IFileSystem? fs=null)
Registers the Local Path Handler to the Module Importer.
BadRuntime UseCulture(CultureInfo culture)
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:77
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:34
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:64
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.
CultureInfo Culture
Definition BadRuntime.cs:79
BadRuntime ConfigureContext(params Action< BadExecutionContext >[] action)
Adds the specified Context Configuration Actions.
void Dispose()
Disposes all Disposables.
Definition BadRuntime.cs:92
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:53
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:60
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:522
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.