protected CommonScriptEngine(IScriptHostFactory scriptHostFactory, ILogProvider logProvider) { Guard.AgainstNullArgument("logProvider", logProvider); ScriptOptions = new ScriptOptions().WithReferences(typeof(Object).Assembly); _scriptHostFactory = scriptHostFactory; _log = logProvider.ForCurrentType(); }
public IEnumerable<SyntaxTreeDiagnosticResult> Compile(string sourceCode, ScriptOptions options = null) { if (String.IsNullOrEmpty(sourceCode)) throw new ArgumentException(nameof(sourceCode)); _previousCompilations.Push(sourceCode); Script prev = _scriptQueue.Any() ? _scriptQueue.Pop() : null; var script = CSharpScript.Create(sourceCode, options ?? DefaultOptions).WithPrevious(prev); ScriptState endState = null; try { endState = script.RunAsync(); } catch (CompilationErrorException ex) { var compilationError = new SyntaxTreeDiagnosticResult(ex.Message); _diagnosticMessages.Add(compilationError); } _scriptQueue.Push(endState.Script); if (endState.Variables != null) { var res = endState.Variables .Select(v => new SyntaxTreeDiagnosticResult(-1, -1, v.Name + v.Value) { Name = v.Name, Value = v.Value.ToString() }) .ToList(); _variables.AddRange(res); } return _diagnosticMessages.Any() ? _diagnosticMessages : _variables; }
private ScriptOptions(ScriptOptions other) : this(filePath: other.FilePath, references: other.MetadataReferences, namespaces: other.Imports, metadataResolver: other.MetadataResolver, sourceResolver: other.SourceResolver) { }
internal EvaluationState WithOptions(ScriptOptions options) { return new EvaluationState( ScriptStateOpt, options, SourceSearchPaths, ReferenceSearchPaths, WorkingDirectory); }
static ScriptOptions() { var paths = ImmutableArray.Create(RuntimeEnvironment.GetRuntimeDirectory()); Default = new ScriptOptions() .WithReferences(typeof(int).Assembly) .WithNamespaces("System") .WithSearchPaths(paths); }
internal EvaluationState( ScriptState<object> scriptState, ScriptOptions scriptOptions, ImmutableArray<string> sourceSearchPaths, ImmutableArray<string> referenceSearchPaths, string workingDirectory) { ScriptStateOpt = scriptState; ScriptOptions = scriptOptions; SourceSearchPaths = sourceSearchPaths; ReferenceSearchPaths = referenceSearchPaths; WorkingDirectory = workingDirectory; }
static VSScriptRunner() { var VsDir = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]); //TODO: find location of Visual Studio installation //location of package var path = System.IO.Path.GetDirectoryName(typeof(CSharpScript).Assembly.Location); var options = ScriptOptions.Default.WithBaseDirectory(path) .WithSearchPaths( Path.Combine(VsDir, "PublicAssemblies"), Path.Combine(VsDir, "PrivateAssemblies")); options = options.AddReferences(typeof(CSharpScript).Assembly, typeof(EnvDTE.TextSelection).Assembly, typeof(EnvDTE.DTE).Assembly); defaultOptions = options; }
internal Script(string code, string path, ScriptOptions options, Type globalsType, ScriptBuilder builder, Script previous) { _code = code ?? ""; _path = path ?? ""; _options = options ?? ScriptOptions.Default; _globalsType = globalsType; _previous = previous; if (_previous != null && builder != null && _previous._lazyBuilder != builder) { throw new ArgumentException("Incompatible script builder."); } _lazyBuilder = builder; }
Scripting() { if (Engine.EditorHint) { return; } Self = this; ScriptOptions = Sc.ScriptOptions.Default.WithReferences(AppDomain.CurrentDomain.GetAssemblies()) .AddReferences(Assembly.GetAssembly(typeof(System.Dynamic.DynamicObject)), // System.Code Assembly.GetAssembly(typeof(Microsoft.CSharp.RuntimeBinder.CSharpArgumentInfo)), // Microsoft.CSharp Assembly.GetAssembly(typeof(System.Dynamic.ExpandoObject))); // System.Dynamic Sc.Script CEngine = Cs.Create("", ScriptOptions); ConsoleState = CEngine.ContinueWith("using System; using System.Dynamic; using Godot; using static API; using static Items.ID;") .RunAsync().Result; }
internal EvaluationState( ScriptState<object> scriptStateOpt, ScriptOptions scriptOptions, ImmutableArray<string> sourceSearchPaths, ImmutableArray<string> referenceSearchPaths, string workingDirectory) { Debug.Assert(scriptOptions != null); Debug.Assert(!sourceSearchPaths.IsDefault); Debug.Assert(!referenceSearchPaths.IsDefault); Debug.Assert(workingDirectory != null); ScriptStateOpt = scriptStateOpt; ScriptOptions = scriptOptions; SourceSearchPaths = sourceSearchPaths; ReferenceSearchPaths = referenceSearchPaths; WorkingDirectory = workingDirectory; }
public static void UpdateDefaultOptions(ReplAssembliesReferencesOptionsModel userOptions) { var VsDir = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]); //TODO: find location of Visual Studio installation //location of package var path = System.IO.Path.GetDirectoryName(typeof(CSharpScript).Assembly.Location); var options = ScriptOptions.Default.WithBaseDirectory(path) .WithSearchPaths( Path.Combine(VsDir, "PublicAssemblies"), Path.Combine(VsDir, "PrivateAssemblies")) .WithReferences("System", "system.core", "mscorlib", "Microsoft.CSharp","Microsoft.VisualStudio.ComponentModelHost","System.ComponentModel.Composition"); if (userOptions != null) { options = options.AddSearchPaths(userOptions.SearchPaths); options = options.WithReferences(userOptions.References); options = options.WithNamespaces(userOptions.Namespaces); defaultOptions = options; } }
void IModule.Install(ModuleManager manager) { _client = manager.Client; _scriptOptions = _scriptOptions.AddReferences( typeof (object).Assembly, typeof (Enumerable).Assembly, _client.GetType().Assembly) .AddImports("System", "System.Linq", "System.Collections.Generic", "Discord"); manager.CreateCommands("exec", group => { group.MinPermissions((int) PermissionLevel.BotOwner); group.CreateCommand("") .Description("Compiles and runs a C# script.") .Parameter("query", ParameterType.Unparsed) .Do(async e => { if (e.User.Name != "SSStormy" || e.User.Id != Constants.UserOwner) return; // really have to make sure that it's me calling this tbh. try { object output = await CSharpScript.EvaluateAsync(e.GetArg("query"), _scriptOptions, new Globals(e, _client)); if (output == null || (output as Task) != null || (output as string) == string.Empty) await e.Channel.SafeSendMessage("Output was empty or null."); else await e.Channel.SafeSendMessage(output.ToString()); } catch (CompilationErrorException ex) { await e.Channel.SafeSendMessage($"Compilation failed: {Format.Code(ex.Message)}"); } GC.Collect(); }); }); }
private static void CreateOptions() { _options = ScriptOptions.Default; _options = _options.WithReferences(new[] { typeof (DateTime).Assembly, typeof (IEnumerable<>).Assembly, typeof (Enumerable).Assembly, typeof (IObjectQuerySerie).Assembly, typeof (IDb).Assembly, typeof (ScriptingEngine).Assembly, typeof (CSharpArgumentInfo).Assembly, typeof (DynamicObject).Assembly, typeof (ExpandoObject).Assembly, typeof (DbExtensions).Assembly }.Distinct()); _options = _options.WithImports("System", "System.Collections.Generic", "System.Diagnostics", "System.Linq", "DbInterfaces.Interfaces", "Timeenator.Interfaces", "FileDb.Interfaces", "FileDb", "Timeenator.Impl", "Timeenator.Impl.Grouping", "Timeenator.Extensions.Grouping", "Timeenator.Extensions.Scientific", "Timeenator.Extensions.Converting", "Microsoft.CSharp", "System.Dynamic", "DbInterfaces.Interfaces", "CustomDbExtensions"); }
public Service() { // TODO (tomat): we should share the copied files with the host _metadataFileProvider = new MetadataShadowCopyProvider( Path.Combine(Path.GetTempPath(), "InteractiveHostShadow"), noShadowCopyDirectories: s_systemNoShadowCopyDirectories); _options = ScriptOptions.Default.WithSearchPaths(DefaultReferenceSearchPaths); _assemblyLoader = new InteractiveAssemblyLoader(_metadataFileProvider); _sourceSearchPaths = DefaultSourceSearchPaths; _formattingOptions = new ObjectFormattingOptions( memberFormat: MemberDisplayFormat.Inline, quoteStrings: true, useHexadecimalNumbers: false, maxOutputLength: 200, memberIndentation: " "); // We want to be sure to delete the shadow-copied files when the process goes away. Frankly // there's nothing we can do if the process is forcefully quit or goes down in a completely // uncontrolled manner (like a stack overflow). When the process goes down in a controlled // manned, we should generally expect this event to be called. AppDomain.CurrentDomain.ProcessExit += HandleProcessExit; }
private void CompleteExecution(RemoteAsyncOperation<RemoteExecutionResult> operation, bool success, string resolvedPath = null) { // TODO (tomat): we should be resetting this info just before the execution to ensure that the services see the same // as the next execution. // send any updates to the host object and current directory back to the client: var newSourcePaths = _hostObject.SourcePaths.List.GetNewContent(); var newReferencePaths = _hostObject.ReferencePaths.List.GetNewContent(); var currentDirectory = Directory.GetCurrentDirectory(); var oldWorkingDirectory = _options.BaseDirectory; var newWorkingDirectory = (oldWorkingDirectory != currentDirectory) ? currentDirectory : null; // update local search paths, the client updates theirs on operation completion: if (newSourcePaths != null) { _sourceSearchPaths = newSourcePaths.AsImmutable(); } if (newReferencePaths != null) { _options = _options.WithSearchPaths(newReferencePaths); } _options = _options.WithBaseDirectory(currentDirectory); operation.Completed(new RemoteExecutionResult(success, newSourcePaths, newReferencePaths, newWorkingDirectory, resolvedPath)); }
static ScriptOptions() { Default = new ScriptOptions() .WithReferences(typeof(int).GetTypeInfo().Assembly) .WithNamespaces("System"); }
public void Initialize(IList<string> references, IList<string> imports, INuGetProvider nuGetProvider, string workingDirectory, Action<ResultObject> dumped, Action<int> completed) { var scriptOptions = _scriptOptions .WithReferences(references) .WithImports(imports); if (nuGetProvider != null) { var resolver = new NuGetScriptMetadataResolver(nuGetProvider, workingDirectory); scriptOptions = scriptOptions.WithMetadataResolver(resolver); } _scriptOptions = scriptOptions; _dumped = dumped; _completed = completed; }
public void Initialize(Type replType) { Contract.ThrowIfNull(replType); _repl = (IRepl)Activator.CreateInstance(replType); _objectFormatter = _repl.CreateObjectFormatter(); _hostObject = new InteractiveHostObject(); _options = _options .WithBaseDirectory(Directory.GetCurrentDirectory()) .AddReferences(_hostObject.GetType().Assembly); _hostObject.ReferencePaths.AddRange(_options.SearchPaths); _hostObject.SourcePaths.AddRange(_sourceSearchPaths); Console.OutputEncoding = Encoding.UTF8; }
internal void SetNamespaces(IEnumerable <string> namespaces) { _options = _options.WithNamespaces(namespaces); }
public void SetReferenceSearchPaths(ImmutableArray <string> paths) { _options = _options.WithSearchPaths(paths); }
protected CommonScriptEngine(IScriptHostFactory scriptHostFactory, ILog logger) { ScriptOptions = new ScriptOptions().WithReferences(typeof(ScriptExecutor).Assembly, typeof(Object).Assembly); _scriptHostFactory = scriptHostFactory; Logger = logger; }
internal void SetReferences(IEnumerable <MetadataReference> references) { _options = _options.WithReferences(references); }
/// <summary> /// Creates a new version of this script with the specified options. /// </summary> public Script WithOptions(ScriptOptions options) { return this.With(options: options); }
internal TaskResult With(ScriptOptions options) { return new TaskResult(options, State); }
internal abstract Script <T> Create <T>(string code, ScriptOptions options, Type globalsType);
static ScriptOptions() { Default = new ScriptOptions() .WithReferences(typeof(int).GetTypeInfo().Assembly); }
internal Script(ScriptCompiler compiler, ScriptBuilder builder, SourceText sourceText, ScriptOptions options, Type globalsTypeOpt, Script previousOpt) { Debug.Assert(sourceText != null); Debug.Assert(options != null); Debug.Assert(compiler != null); Debug.Assert(builder != null); Compiler = compiler; Builder = builder; Previous = previousOpt; SourceText = sourceText; Options = options; GlobalsType = globalsTypeOpt; }
/// <summary> /// Continues the script with given code snippet. /// </summary> public Script <TResult> ContinueWith <TResult>(string code, ScriptOptions options = null) { options = options ?? InheritOptions(Options); return(new Script <TResult>(Compiler, Builder, SourceText.From(code ?? "", options.FileEncoding), options, GlobalsType, this)); }
protected override ScriptState ExecuteScript(string text, ScriptOptions options) { return VisualBasicScript.Run(text, options, new FiddlerScriptGlobals()); }
/// <summary> /// Continues the script with given code snippet. /// </summary> public Script <object> ContinueWith(string code, ScriptOptions options = null) => ContinueWith <object>(code, options);
/// <summary> /// Continues the script with given code snippet. /// </summary> public Script <TResult> ContinueWith <TResult>(string code, ScriptOptions options = null) => new Script <TResult>(Compiler, Builder, code ?? "", options ?? Options, GlobalsType, this);
protected abstract ScriptState ExecuteScript(string text, ScriptOptions options);
internal static Script <T> CreateInitialScript <T>(ScriptCompiler compiler, string codeOpt, ScriptOptions optionsOpt, Type globalsTypeOpt, InteractiveAssemblyLoader assemblyLoaderOpt) { return(new Script <T>(compiler, new ScriptBuilder(assemblyLoaderOpt ?? new InteractiveAssemblyLoader()), codeOpt ?? "", optionsOpt ?? ScriptOptions.Default, globalsTypeOpt, previousOpt: null)); }
public void ImportNamespace(string @namespace) { ScriptEngine.ValidateNamespace(@namespace); _options = _options.AddNamespaces(@namespace); }
/// <summary> /// Creates a new version of this script with the specified options. /// </summary> public Script WithOptions(ScriptOptions options) => WithOptionsInternal(options);
public void SetReferenceSearchPaths(params string[] paths) { _options = _options.WithSearchPaths(paths); }
internal abstract Script WithOptionsInternal(ScriptOptions options);
public Service() { _lastTaskGuard = new object(); _lastTask = Task.CompletedTask; _scriptOptions = ScriptOptions.Default; ObjectExtensions.Dumped += OnDumped; }
public void SetReferenceSearchPaths(ImmutableArray <string> paths) { MetadataFileReferenceResolver.ValidateSearchPaths(paths, "paths"); _options = _options.WithSearchPaths(paths); }
private static Script<object> TryCompile(string code, ScriptOptions options) { var script = CSharpScript.Create<object>(code, options); var diagnostics = script.Compile(); if (diagnostics.Any(diagnostic => diagnostic.Severity == DiagnosticSeverity.Error)) { DisplayErrors(diagnostics); return null; } return script; }
/// <summary> /// Creates a new version of this script with the specified options. /// </summary> public Script WithOptions(ScriptOptions options) { return(this.WithOptionsInternal(options)); }
public void SetPathsAsync( RemoteAsyncOperation<object> operation, string[] referenceSearchPaths, string[] sourceSearchPaths, string baseDirectory) { Debug.Assert(operation != null); Debug.Assert(referenceSearchPaths != null); Debug.Assert(sourceSearchPaths != null); Debug.Assert(baseDirectory != null); lock (_sessionGuard) { _hostObject.ReferencePaths.Clear(); _hostObject.ReferencePaths.AddRange(referenceSearchPaths); _options = _options.WithSearchPaths(referenceSearchPaths).WithBaseDirectory(baseDirectory); _hostObject.SourcePaths.Clear(); _hostObject.SourcePaths.AddRange(sourceSearchPaths); _sourceSearchPaths = sourceSearchPaths.AsImmutable(); Directory.SetCurrentDirectory(baseDirectory); } operation.Completed(null); }
/// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables and return value.</returns> public Task <ScriptState <TResult> > ContinueWithAsync <TResult>(string code, ScriptOptions options, CancellationToken cancellationToken) => ContinueWithAsync <TResult>(code, options, null, cancellationToken);
private AssemblyLoadResult LoadFromPathThrowing(string fullOriginalPath, bool addReference) { var result = _assemblyLoader.LoadFromPath(fullOriginalPath); if (addReference && result.IsSuccessful) { var reference = _metadataFileProvider.GetReference(fullOriginalPath); _options = _options.AddReferences(reference); } return result; }
private Script<object> TryCompile(Script previousScript, string code, string path, ScriptOptions options) { Script script; var scriptOptions = options.WithPath(path).WithIsInteractive(path == null); if (previousScript != null) { script = previousScript.ContinueWith(code, scriptOptions); } else { script = _replServiceProvider.CreateScript<object>(code, scriptOptions, _hostObject.GetType(), _assemblyLoader); } // force build so exception is thrown now if errors are found. try { script.Build(); } catch (CompilationErrorException e) { DisplayInteractiveErrors(e.Diagnostics, Console.Error); return null; } // TODO: Do we want to do this? // Pros: immediate feedback for assemblies that can't be loaded. // Cons: maybe we won't need them //foreach (PortableExecutableReference reference in script.GetCompilation().DirectiveReferences) //{ // LoadReference(reference, suppressWarnings: false); //} return (Script<object>)script; }
private Script<object> Compile(ScriptState<object> previous, string text, string path, ref ScriptOptions options) { Script script = _repl.CreateScript(text).WithOptions(options); if (previous != null) { script = script.WithPrevious(previous.Script); } else { script = script.WithGlobalsType(_hostObject.GetType()); } if (path != null) { script = script.WithPath(path).WithOptions(script.Options.WithIsInteractive(false)); } // force build so exception is thrown now if errors are found. script.Build(); // load all references specified in #r's -- they will all be PE references (may be shadow copied): foreach (PortableExecutableReference reference in script.GetCompilation().DirectiveReferences) { // FullPath refers to the original reference path, not the copy: LoadReference(reference.FilePath, suppressWarnings: false, addReference: false, options: ref options); } return (Script<object>)script; }
private Script<object> TryCompile(Script previousScript, string code, string path, ScriptOptions options) { Script script; var scriptOptions = options.WithFilePath(path); if (previousScript != null) { script = previousScript.ContinueWith(code, scriptOptions); } else { script = _replServiceProvider.CreateScript<object>(code, scriptOptions, _globals.GetType(), _assemblyLoader); } var diagnostics = script.Compile(); if (diagnostics.HasAnyErrors()) { DisplayInteractiveErrors(diagnostics, Console.Error); return null; } return (Script<object>)script; }
public ScriptResult Execute(string code, string[] scriptArgs, AssemblyReferences references, IEnumerable<string> namespaces, ScriptPackSession scriptPackSession) { if (scriptPackSession == null) { throw new ArgumentNullException("scriptPackSession"); } if (references == null) { throw new ArgumentNullException("references"); } _log.Debug("Starting to create execution components"); _log.Debug("Creating script host"); var executionReferences = new AssemblyReferences(references.Assemblies, references.Paths); executionReferences.Union(scriptPackSession.References); ScriptResult scriptResult; SessionState<ScriptState> sessionState; var isFirstExecution = !scriptPackSession.State.ContainsKey(SessionKey); if (isFirstExecution) { var host = _scriptHostFactory.CreateScriptHost( new ScriptPackManager(scriptPackSession.Contexts), scriptArgs); ScriptLibraryWrapper.SetHost(host); _log.Debug("Creating session"); var hostType = host.GetType(); ScriptOptions = ScriptOptions.AddReferences(hostType.Assembly); var allNamespaces = namespaces.Union(scriptPackSession.Namespaces).Distinct(); foreach (var reference in executionReferences.Paths) { _log.DebugFormat("Adding reference to {0}", reference); ScriptOptions = ScriptOptions.AddReferences(reference); } foreach (var assembly in executionReferences.Assemblies) { _log.DebugFormat("Adding reference to {0}", assembly.FullName); ScriptOptions = ScriptOptions.AddReferences(assembly); } foreach (var @namespace in allNamespaces) { _log.DebugFormat("Importing namespace {0}", @namespace); ScriptOptions = ScriptOptions.AddNamespaces(@namespace); } sessionState = new SessionState<ScriptState> { References = executionReferences, Namespaces = new HashSet<string>(allNamespaces) }; scriptPackSession.State[SessionKey] = sessionState; scriptResult = Execute(code, host, sessionState); } else { _log.Debug("Reusing existing session"); sessionState = (SessionState<ScriptState>)scriptPackSession.State[SessionKey]; if (sessionState.References == null) { sessionState.References = new AssemblyReferences(); } if (sessionState.Namespaces == null) { sessionState.Namespaces = new HashSet<string>(); } var newReferences = executionReferences.Except(sessionState.References); foreach (var reference in newReferences.Paths) { _log.DebugFormat("Adding reference to {0}", reference); ScriptOptions = ScriptOptions.AddReferences(reference); sessionState.References = sessionState.References.Union(new[] { reference }); } foreach (var assembly in newReferences.Assemblies) { _log.DebugFormat("Adding reference to {0}", assembly.FullName); ScriptOptions = ScriptOptions.AddReferences(assembly); sessionState.References = sessionState.References.Union(new[] { assembly }); } var newNamespaces = namespaces.Except(sessionState.Namespaces); foreach (var @namespace in newNamespaces) { _log.DebugFormat("Importing namespace {0}", @namespace); ScriptOptions = ScriptOptions.AddNamespaces(@namespace); sessionState.Namespaces.Add(@namespace); } if (string.IsNullOrWhiteSpace(code)) { return ScriptResult.Empty; } scriptResult = Execute(code, sessionState.Session, sessionState); } return scriptResult; //todo handle namespace failures //https://github.com/dotnet/roslyn/issues/1012 }
/// <summary> /// Creates a new instance of a script of this type. /// </summary> internal abstract Script Make(string code, string path, ScriptOptions options, Type globalsType, Type returnType, ScriptBuilder builder, Script previous);
/// <summary> /// Continues script execution from the state represented by this instance by running the specified code snippet. /// </summary> /// <param name="code">The code to be executed.</param> /// <param name="options">Options.</param> /// <param name="catchException"> /// If specified, any exception thrown by the script top-level code is passed to <paramref name="catchException"/>. /// If it returns true the exception is caught and stored on the resulting <see cref="ScriptState"/>, otherwise the exception is propagated to the caller. /// </param> /// <param name="cancellationToken">Cancellation token.</param> /// <returns>A <see cref="ScriptState"/> that represents the state after running <paramref name="code"/>, including all declared variables, return value and caught exception (if applicable).</returns> public Task <ScriptState <TResult> > ContinueWithAsync <TResult>(string code, ScriptOptions options = null, Func <Exception, bool> catchException = null, CancellationToken cancellationToken = default(CancellationToken)) => Script.ContinueWith <TResult>(code, options).RunFromAsync(this, catchException, cancellationToken);
public Task <ScriptState <object> > ContinueWithAsync(string code, ScriptOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return(ContinueWithAsync <object>(code, options, cancellationToken)); }
public Task <ScriptState <TResult> > ContinueWithAsync <TResult>(string code, ScriptOptions options = null, CancellationToken cancellationToken = default(CancellationToken)) { return(Script.ContinueWith <TResult>(code, options).ContinueAsync(this, cancellationToken)); }
internal abstract Script Create(string code, ScriptOptions options, Type globalsType, Type returnType);
/// <summary> /// Creates a new version of this script with the specified options. /// </summary> public Script WithOptions(ScriptOptions options) { return(this.With(options: options)); }