/// <summary>
        /// Initializes a new instance of the <see cref="InteractiveExecution"/> class.
        /// </summary>
        public InteractiveExecution()
        {
            var scriptOptions = ScriptOptions.Default.WithImports(ScriptCompiler.DefaultUsings).WithReferences(ScriptCompiler.DefaultAssemblyReferences);

            scriptState = CSharpScript.RunAsync("", scriptOptions, scriptBase).Result;
            scriptBase.ObjectWriter = new DefaultObjectWriter();
            scriptBase._InternalObjectWriter_ = new ConsoleObjectWriter();
        }
 internal EvaluationState WithScriptState(ScriptState<object> state)
 {
     return new EvaluationState(
         state,
         ScriptOptions,
         SourceSearchPaths,
         ReferenceSearchPaths,
         WorkingDirectory);
 }
Exemplo n.º 3
0
		public ScriptResult(
			ScriptState state,
			string output,
			TimeSpan elapsed = default(TimeSpan))
		{
			this.State = state;
			this.Output = output;
			this.Elapsed = elapsed;
		}
 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;
 }
Exemplo n.º 5
0
		public LogPack(
			ulong tweetId,
			DateTimeOffset tweetTime,
			string scriptContent,
			string resultContent,
			ScriptState state)
		{
			this.TweetId = tweetId;
			this.TweetTime = tweetTime;
			this.ScriptContent = scriptContent;
			this.ResultContent = resultContent;
			this.State = state;
		}
Exemplo n.º 6
0
        public void ExecuteScript(Script script)
        {
            // wrap the script in our state
            ScriptState scriptState = new ScriptState(script);

            // the script may complete in one go
            scriptState.Execute(null);

            // if not, add it to our list
            if (!scriptState.IsComplete)
            {
                scripts.Add(scriptState);
            }
        }
Exemplo n.º 7
0
                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;
                }
Exemplo n.º 8
0
        private async void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            var tb = (TextBox)sender;
            var s = tb.Text;

            if (string.IsNullOrWhiteSpace(s))
                return;

            if (s[s.Length - 1] == '\n')
            {
                try
                {
                    if (_state == null)
                        _state = await CSharpScript.RunAsync(s, globals: ViewModel.Commander);
                    else
                        _state = await _state.ContinueWithAsync(s);
                }
                catch { }

                tb.Text = "";
            }
        }
Exemplo n.º 9
0
 public void InitNew()
 {
     Debug.WriteLine ("InitNew()");
     DotNet.Enable ();
     CLOS.Init ();
     this.currentScriptState = ScriptState.Disconnected;
     if (this.site != null)
         this.site.OnStateChange (this.currentScriptState);
     CL.Readtable.Case = ReadtableCase.Preserve;
 }
Exemplo n.º 10
0
        private void BuildAndRun(Script<object> newScript, InteractiveScriptGlobals globals, ref ScriptState<object> state, ref ScriptOptions options, bool displayResult, CancellationToken cancellationToken)
        {
            var diagnostics = newScript.Compile(cancellationToken);
            DisplayDiagnostics(diagnostics);
            if (diagnostics.HasAnyErrors())
            {
                return;
            }

            var task = (state == null) ?
                newScript.RunAsync(globals, catchException: e => true, cancellationToken: cancellationToken) :
                newScript.RunFromAsync(state, catchException: e => true, cancellationToken: cancellationToken);

            state = task.GetAwaiter().GetResult();
            if (state.Exception != null)
            {
                DisplayException(state.Exception);
            }
            else if (displayResult && newScript.HasReturnValue())
            {
                globals.Print(state.ReturnValue);
            }

            options = UpdateOptions(options, globals);
        }
Exemplo n.º 11
0
 private void SelectTegel1_Click(object sender, EventArgs e)
 {
     _ScriptState = ScriptState.selectTegel1;
     UpdateStatus();
 }
Exemplo n.º 12
0
 public abstract void GetScriptState(out ScriptState state);
            private async Task<ScriptState<object>> ExecuteOnUIThread(Script<object> script, ScriptState<object> stateOpt)
            {
                return await Task.Factory.StartNew(async () =>
                {
                    try
                    {
                        var task = (stateOpt == null) ?
                            script.RunAsync(_hostObject, CancellationToken.None) :
                            script.ContinueAsync(stateOpt, CancellationToken.None);

                        return await task.ConfigureAwait(false);
                    }
                    catch (Exception e)
                    {
                        // TODO (tomat): format exception
                        Console.Error.WriteLine(e);
                        return null;
                    }
                },
                CancellationToken.None,
                TaskCreationOptions.None,
                s_UIThreadScheduler).Unwrap().ConfigureAwait(false);
            }
Exemplo n.º 14
0
 private async Task<ScriptState<object>> ExecuteOnUIThread(Script<object> script, ScriptState<object> stateOpt)
 {
     return await ((Task<ScriptState<object>>)s_control.Invoke(
         (Func<Task<ScriptState<object>>>)(async () =>
         {
             try
             {
                 var task = (stateOpt == null) ?
                     script.RunAsync(_globals, CancellationToken.None) :
                     script.ContinueAsync(stateOpt, CancellationToken.None);
                 return await task.ConfigureAwait(false);
             }
             catch (FileLoadException e) when (e.InnerException is InteractiveAssemblyLoaderException)
             {
                 Console.Error.WriteLine(e.InnerException.Message);
                 return null;
             }
             catch (Exception e)
             {
                 // TODO (tomat): format exception
                 Console.Error.WriteLine(e);
                 return null;
             }
         }))).ConfigureAwait(false);
 }
Exemplo n.º 15
0
 private static void DisplaySubmissionResult(ScriptState<object> state)
 {
     // TODO
     //if (state.Script.GetCompilation().HasSubmissionResult())
     if (state.ReturnValue != null)
     {
         state.ReturnValue.Dump();
     }
 }
 public override async Task SubmitCode(string name, string code)
 {
     state = null;
     await Run(code, false /* throwException */, isAsync);
 }
Exemplo n.º 17
0
            private async Task <ScriptState <object> > ExecuteOnUIThread(Script <object> script, ScriptState <object> stateOpt, bool displayResult)
            {
                return(await((Task <ScriptState <object> >)s_control.Invoke(
                                 (Func <Task <ScriptState <object> > >)(async() =>
                {
                    var task = (stateOpt == null) ?
                               script.RunAsync(_globals, catchException: e => true, cancellationToken: CancellationToken.None) :
                               script.RunFromAsync(stateOpt, catchException: e => true, cancellationToken: CancellationToken.None);

                    var newState = await task.ConfigureAwait(false);

                    if (newState.Exception != null)
                    {
                        DisplayException(newState.Exception);
                    }
                    else if (displayResult && newState.Script.HasReturnValue())
                    {
                        _globals.Print(newState.ReturnValue);
                    }

                    return newState;
                }))).ConfigureAwait(false));
            }
Exemplo n.º 18
0
 void IActiveScriptSite.OnStateChange(ScriptState scriptState)
 {
 }
Exemplo n.º 19
0
        static async Task Main(string[] args)
        {
            ReadLine.AutoCompletionHandler = new AutoCompletionHandler((text, index) =>
            {
                var service     = CompletionService.GetService(Current);
                var completions = service.GetCompletionsAsync(Current, text.Length - 1).Result;

                var wordToComplete = GetWordToComplete(text);

                var result = completions.Items
                             .OrderByDescending(c => c.DisplayText.IsValidCompletionStartsWithExactCase(wordToComplete))
                             .ThenByDescending(c => c.DisplayText.IsValidCompletionStartsWithIgnoreCase(wordToComplete))
                             .ThenByDescending(c => c.DisplayText.IsCamelCaseMatch(wordToComplete))
                             .ThenByDescending(c => c.DisplayText.IsSubsequenceMatch(wordToComplete))
                             .ThenBy(c => c.DisplayText, StringComparer.OrdinalIgnoreCase)
                             .ThenBy(c => c.FilterText, StringComparer.OrdinalIgnoreCase).Select(x =>
                {
                    var displayText = x.DisplayText;
                    //if (x.Tags.Any())
                    //{
                    //    displayText = displayText + " #[" + string.Join(",", x.Tags.Select(t => t.ToLowerInvariant())) + "]";
                    //}

                    return(displayText);
                }).ToArray();

                return(result);
            });

            var assemblies = new[]
            {
                Assembly.Load("Microsoft.CodeAnalysis"),
                Assembly.Load("Microsoft.CodeAnalysis.CSharp"),
                Assembly.Load("Microsoft.CodeAnalysis.Features"),
                Assembly.Load("Microsoft.CodeAnalysis.CSharp.Features"),
            };

            var partTypes = MefHostServices.DefaultAssemblies.Concat(assemblies)
                            .Distinct()
                            .SelectMany(x => x.GetTypes())
                            .ToArray();

            var compositionContext = new ContainerConfiguration()
                                     .WithParts(partTypes)
                                     .CreateContainer();

            var host = MefHostServices.Create(compositionContext);

            Workspace = new AdhocWorkspace(host);

            var firstProj = Workspace.AddProject(CreateProject());

            Current = Workspace.AddDocument(CreateDocument(firstProj.Id, ""));

            ScriptState <object> scriptState = null;

            while (true)
            {
                var project = Workspace.AddProject(CreateProject(Current.Project));
                Current = Workspace.AddDocument(CreateDocument(project.Id, ""));

                Console.Write("> ");
                var input = ReadLine.Read();

                var solution = Current.Project.Solution;
                solution = solution.WithDocumentText(Current.Id, SourceText.From(input));
                Workspace.TryApplyChanges(solution);

                Current = solution.GetDocument(Current.Id);

                scriptState = scriptState == null ?
                              await CSharpScript.RunAsync(input) :
                              await scriptState.ContinueWithAsync(input);
            }


            //            var code = @"
            //namespace IntellisenseTest
            //{
            //    public class Class1
            //    {
            //        public static void Bar() { }

            //        public static void Foo(int n)
            //        {
            //            Ba
            //        }
            //    }
            //}";
            //var sourceText = SourceText.From(code);



            //string projName = "NewProject";
            //var projectId = ProjectId.CreateNewId();
            //var versionStamp = VersionStamp.Create();
            //var projectInfo = ProjectInfo.Create(projectId, versionStamp, projName, projName, LanguageNames.CSharp);
            //var newProject = workspace.AddProject(projectInfo);
            //var newDocument = workspace.AddDocument(newProject.Id, "NewFile.cs", sourceText);

            //var service = CompletionService.GetService(newDocument);
            //var results = service.GetCompletionsAsync(newDocument, 169).Result;

            //var symbols = Recommender.GetRecommendedSymbolsAtPositionAsync(
            //    newDocument.GetSemanticModelAsync().Result,
            //    position,
            //    workspace).Result;

            //foreach(var i in results.Items.Where(x => !x.Tags.Contains("Keyword")))
            //{
            //    Console.WriteLine(i);
            //}

            //Console.ReadLine();
        }
Exemplo n.º 20
0
 private async Task <ScriptState <object> > ExecuteOnUIThread(Script <object> script, ScriptState <object> stateOpt)
 {
     return(await((Task <ScriptState <object> >)s_control.Invoke(
                      (Func <Task <ScriptState <object> > >)(async() =>
     {
         try
         {
             var task = (stateOpt == null) ?
                        script.RunAsync(_globals, CancellationToken.None) :
                        script.ContinueAsync(stateOpt, CancellationToken.None);
             return await task.ConfigureAwait(false);
         }
         catch (FileLoadException e) when(e.InnerException is InteractiveAssemblyLoaderException)
         {
             Console.Error.WriteLine(e.InnerException.Message);
             return null;
         }
         catch (Exception e)
         {
             // TODO (tomat): format exception
             Console.Error.WriteLine(e);
             return null;
         }
     }))).ConfigureAwait(false));
 }
Exemplo n.º 21
0
 public async Task Init()
 {
     state = await InitStateAsync();
 }
Exemplo n.º 22
0
        /// <summary>
        /// Executes the specified code.
        /// </summary>
        /// <param name="code">The code.</param>
        private void Execute(string code)
        {
            try
            {
                InteractiveScriptBase.Current = scriptBase;
                scriptBase._ScriptState_ = scriptState;
                scriptState = scriptState.ContinueWithAsync(code).Result;
                importedCode = ExtractImportedCode(scriptState.Script, importedCode);
                UpdateUsings(scriptState.Script, usings);
                UpdateReferences(scriptState.Script, references);
                scriptBase.Dump(scriptState.ReturnValue);

                if (scriptBase._InteractiveScriptBaseType_ != null && scriptBase._InteractiveScriptBaseType_ != scriptBase.GetType())
                {
                    var oldScriptBase = scriptBase;

                    scriptBase = (InteractiveScriptBase)Activator.CreateInstance(scriptBase._InteractiveScriptBaseType_);
                    scriptBase.ObjectWriter = oldScriptBase.ObjectWriter;
                    scriptBase._InternalObjectWriter_ = oldScriptBase._InternalObjectWriter_;

                    // TODO: Changing globals, but we need to store previous variables
                    scriptState = CSharpScript.RunAsync("", scriptState.Script.Options, scriptBase).Result;
                }
            }
            finally
            {
                InteractiveScriptBase.Current = null;
            }
        }
 public void OnStateChange(ScriptState scriptState)
 {
     GlobalLog.Print("AutoWebProxyScriptWrapper.ScriptHost#" + ValidationHelper.HashString(this) + "::OnStateChange() state:" + ValidationHelper.ToString(scriptState));
     if (scriptState == ScriptState.Closed)
     {
         helper = null;
     }
 }
Exemplo n.º 24
0
 private static Task <ScriptState <object> > EvaluateStringWithStateAsync(string text, ScriptState <object> state, ScriptOptions scriptOptions)
 {
     return(state == null
         ? CSharpScript.Create(text, scriptOptions).RunAsync()
         : state.ContinueWithAsync(text, scriptOptions));
 }
 public void OnStateChange(ScriptState state)
 {
 }
Exemplo n.º 26
0
 public async Task AddReferences(params MetadataReference[] assemblies)
 {
     this.scriptOptions = scriptOptions.AddReferences(assemblies);
     this.state         = await EvaluateStringWithStateAsync(string.Empty, this.state, this.scriptOptions);
 }
Exemplo n.º 27
0
        private async Task <IEnumerable <CompletionItem> > GetCompletionList(string code, int cursorPosition, ScriptState scriptState)
        {
            var metadataReferences = ImmutableArray <MetadataReference> .Empty;

            var forcedState = false;

            if (scriptState == null)
            {
                scriptState = await CSharpScript.RunAsync(string.Empty, ScriptOptions);

                forcedState = true;
            }

            var compilation = scriptState.Script.GetCompilation();

            metadataReferences = metadataReferences.AddRange(compilation.References);
            var originalCode = forcedState ? string.Empty : scriptState.Script.Code ?? string.Empty;

            var buffer = new StringBuilder(originalCode);

            if (!string.IsNullOrWhiteSpace(originalCode) && !originalCode.EndsWith(Environment.NewLine))
            {
                buffer.AppendLine();
            }

            buffer.AppendLine(code);
            var fullScriptCode   = buffer.ToString();
            var offset           = fullScriptCode.LastIndexOf(code, StringComparison.InvariantCulture);
            var absolutePosition = Math.Max(offset, 0) + cursorPosition;

            if (_fixture == null || _metadataReferences != metadataReferences)
            {
                _fixture            = new WorkspaceFixture(compilation.Options, metadataReferences);
                _metadataReferences = metadataReferences;
            }

            var document = _fixture.ForkDocument(fullScriptCode);
            var service  = CompletionService.GetService(document);

            var completionList = await service.GetCompletionsAsync(document, absolutePosition);

            var semanticModel = await document.GetSemanticModelAsync();

            var symbols = await Recommender.GetRecommendedSymbolsAtPositionAsync(semanticModel, absolutePosition, document.Project.Solution.Workspace);

            var symbolToSymbolKey = new Dictionary <(string, int), ISymbol>();

            foreach (var symbol in symbols)
            {
                var key = (symbol.Name, (int)symbol.Kind);
                if (!symbolToSymbolKey.ContainsKey(key))
                {
                    symbolToSymbolKey[key] = symbol;
                }
            }
            var items = completionList.Items.Select(item => item.ToModel(symbolToSymbolKey, document).ToDomainObject()).ToArray();

            return(items);
        }
 public virtual void Reset()
 {
     _scriptState   = null;
     _scriptOptions = null;
 }
Exemplo n.º 29
0
 public override void GetScriptState(out ScriptState state)
 {
     activeScript.GetScriptState(out state);
 }
Exemplo n.º 30
0
 public void OnStateChange(ScriptState scriptState)
 {
 }
 void IActiveScriptSite.OnStateChange(ScriptState scriptState)
 {
     //Trace.WriteLine("OnStateChange scriptState=" + scriptState);
 }
Exemplo n.º 32
0
 public MathLib(ScriptState state) : base(state)
 {
     this.name = "Math";
     this.rnd  = new Random();
 }
Exemplo n.º 33
0
 public ScriptResultObject(ScriptState <object> state) => FromState(state);
Exemplo n.º 34
0
        private bool TryBuildAndRun(Script <object> newScript, InteractiveScriptGlobals globals, ref ScriptState <object> state, ref ScriptOptions options, CancellationToken cancellationToken)
        {
            var diagnostics = newScript.Compile(cancellationToken);

            DisplayDiagnostics(diagnostics);
            if (diagnostics.HasAnyErrors())
            {
                return(false);
            }

            try
            {
                var task = (state == null) ?
                           newScript.RunAsync(globals, cancellationToken) :
                           newScript.ContinueAsync(state, cancellationToken);

                state = task.GetAwaiter().GetResult();
            }
            catch (FileLoadException e) when(e.InnerException is InteractiveAssemblyLoaderException)
            {
                _console.ForegroundColor = ConsoleColor.Red;
                _console.Out.WriteLine(e.InnerException.Message);
                _console.ResetColor();

                return(false);
            }
            catch (Exception e)
            {
                DisplayException(e);
                return(false);
            }

            options = UpdateOptions(options, globals);

            return(true);
        }
Exemplo n.º 35
0
 public void GetScriptState(out ScriptState scriptState)
 {
     Debug.WriteLine ("GetScriptState()");
     scriptState = this.currentScriptState;
 }
Exemplo n.º 36
0
 public ObjectHandler(ScriptState luaState)
     : base(luaState)
 {
 }
Exemplo n.º 37
0
 public void SetScriptState(ScriptState state)
 {
     Debug.WriteLine ("SetScriptState(" + state.ToString() + ")");
     this.currentScriptState =  state;
     // site.OnStateChange (this.currentScriptState);
 }
Exemplo n.º 38
0
 internal TaskResult(ScriptOptions options, ScriptState <object> state)
 {
     Debug.Assert(options != null);
     this.Options = options;
     this.State   = state;
 }
Exemplo n.º 39
0
            private Task <ScriptState <object> > ExecuteOnUIThreadAsync(Script <object> script, ScriptState <object>?state, bool displayResult)
            {
                return((Task <ScriptState <object> >)_invokeOnMainThread((Func <Task <ScriptState <object> > >)(async() =>
                {
                    var serviceState = GetServiceState();

                    var task = (state == null) ?
                               script.RunAsync(serviceState.Globals, catchException: e => true, cancellationToken: CancellationToken.None) :
                               script.RunFromAsync(state, catchException: e => true, cancellationToken: CancellationToken.None);

                    var newState = await task.ConfigureAwait(false);

                    if (newState.Exception != null)
                    {
                        DisplayException(newState.Exception);
                    }
                    else if (displayResult && newState.Script.HasReturnValue())
                    {
                        serviceState.Globals.Print(newState.ReturnValue);
                    }

                    return newState;
                })));
            }
Exemplo n.º 40
0
 internal TaskResult With(ScriptState <object> state)
 {
     return(new TaskResult(Options, state));
 }
Exemplo n.º 41
0
        private bool TryBuildAndRun(Script<object> newScript, object globals, ref ScriptState<object> state, CancellationToken cancellationToken)
        {
            var diagnostics = newScript.Build(cancellationToken);
            DisplayDiagnostics(diagnostics);
            if (diagnostics.HasAnyErrors())
            {
                return false;
            }

            try
            {
                var task = (state == null) ?
                    newScript.RunAsync(globals, cancellationToken) :
                    newScript.ContinueAsync(state, cancellationToken);

                state = task.GetAwaiter().GetResult();
            }
            catch (Exception e)
            {
                DisplayException(e);
                return false;
            }

            return true;
        }
Exemplo n.º 42
0
            private async Task <ScriptState <object> > ExecuteOnUIThread(Script <object> script, ScriptState <object> stateOpt)
            {
                return(await Task.Factory.StartNew(async() =>
                {
                    try
                    {
                        var task = (stateOpt == null) ?
                                   script.RunAsync(_hostObject, CancellationToken.None) :
                                   script.ContinueAsync(stateOpt, CancellationToken.None);

                        return await task.ConfigureAwait(false);
                    }
                    catch (Exception e)
                    {
                        // TODO (tomat): format exception
                        Console.Error.WriteLine(e);
                        return null;
                    }
                },
                                                   CancellationToken.None,
                                                   TaskCreationOptions.None,
                                                   s_UIThreadScheduler).Unwrap().ConfigureAwait(false));
            }
Exemplo n.º 43
0
 private object ExecuteInner(Script script)
 {
     var globals = _lastResult != null ? (object)_lastResult : (object)_hostObject;
     var result = script.Run(globals);
     _lastResult = result;
     return result.ReturnValue;
 }
Exemplo n.º 44
0
 public abstract void SetScriptState(ScriptState state);
Exemplo n.º 45
0
 private void DisplaySubmissionResult(ScriptState<object> state)
 {
     if (state.Script.HasReturnValue())
     {
         _globals.Print(state.ReturnValue);
     }
 }
Exemplo n.º 46
0
 public abstract void GetScriptState(out ScriptState state);
 private void DisplaySubmissionResult(ScriptState<object> state)
 {
     bool hasValue;
     var resultType = state.Script.GetCompilation().GetSubmissionResultType(out hasValue);
     if (hasValue)
     {
         if (resultType != null && resultType.SpecialType == SpecialType.System_Void)
         {
             Console.Out.WriteLine(_replServiceProvider.ObjectFormatter.VoidDisplayString);
         }
         else
         {
             Console.Out.WriteLine(_replServiceProvider.ObjectFormatter.FormatObject(state.ReturnValue, _formattingOptions));
         }
     }
 }
Exemplo n.º 48
0
 public override void SetScriptState(ScriptState state)
 {
     activeScript.SetScriptState(state);
 }
Exemplo n.º 49
0
        private async Task HandleSubmitCode(
            SubmitCode submitCode,
            KernelInvocationContext context)
        {
            CancellationTokenSource cancellationSource;

            lock (_cancellationSourceLock)
            {
                cancellationSource = _cancellationSource;
            }
            var codeSubmissionReceived = new CodeSubmissionReceived(
                submitCode.Code,
                submitCode);

            context.Publish(codeSubmissionReceived);

            var code       = submitCode.Code;
            var isComplete = await IsCompleteSubmissionAsync(submitCode.Code);

            if (isComplete)
            {
                context.Publish(new CompleteCodeSubmissionReceived(submitCode));
            }
            else
            {
                context.Publish(new IncompleteCodeSubmissionReceived(submitCode));
            }

            if (submitCode.SubmissionType == SubmissionType.Diagnose)
            {
                return;
            }

            Exception exception = null;

            using var console = await ConsoleOutput.Capture();

            using var _ = console.SubscribeToStandardOutput(std => PublishOutput(std, context, submitCode));
            var scriptState = _scriptState;

            if (!cancellationSource.IsCancellationRequested)
            {
                try
                {
                    if (scriptState == null)
                    {
                        scriptState = await CSharpScript.RunAsync(
                            code,
                            ScriptOptions,
                            cancellationToken : cancellationSource.Token)
                                      .UntilCancelled(cancellationSource.Token);
                    }
                    else
                    {
                        scriptState = await _scriptState.ContinueWithAsync(
                            code,
                            ScriptOptions,
                            e =>
                        {
                            exception = e;
                            return(true);
                        },
                            cancellationToken : cancellationSource.Token)
                                      .UntilCancelled(cancellationSource.Token);
                    }
                }
                catch (Exception e)
                {
                    exception = e;
                }
            }

            if (!cancellationSource.IsCancellationRequested)
            {
                _scriptState = scriptState;
                if (exception != null)
                {
                    string message = null;

                    if (exception is CompilationErrorException compilationError)
                    {
                        message =
                            string.Join(Environment.NewLine,
                                        compilationError.Diagnostics.Select(d => d.ToString()));
                    }

                    context.Publish(new CommandFailed(exception, submitCode, message));
                }
                else
                {
                    if (_scriptState != null && HasReturnValue)
                    {
                        var formattedValues = FormattedValue.FromObject(_scriptState.ReturnValue);
                        context.Publish(
                            new ReturnValueProduced(
                                _scriptState.ReturnValue,
                                submitCode,
                                formattedValues));
                    }

                    context.Publish(new CodeSubmissionEvaluated(submitCode));
                }
            }
            else
            {
                context.Publish(new CommandFailed(null, submitCode, "Command cancelled"));
            }

            context.Complete();
        }
Exemplo n.º 50
0
            private async Task<ScriptState<object>> ExecuteOnUIThread(Script<object> script, ScriptState<object> stateOpt, bool displayResult)
            {
                return await ((Task<ScriptState<object>>)s_control.Invoke(
                    (Func<Task<ScriptState<object>>>)(async () =>
                    {
                        var task = (stateOpt == null) ?
                            script.RunAsync(_globals, catchException: e => true, cancellationToken: CancellationToken.None) :
                            script.RunFromAsync(stateOpt, catchException: e => true, cancellationToken: CancellationToken.None);

                        var newState = await task.ConfigureAwait(false);

                        if (newState.Exception != null)
                        {
                            DisplayException(newState.Exception);
                        }
                        else if (displayResult && newState.Script.HasReturnValue())
                        {
                            _globals.Print(newState.ReturnValue);
                        }

                        return newState;

                    }))).ConfigureAwait(false);
            }
Exemplo n.º 51
0
 public override void SetScriptState(ScriptState state)
 {
     activeScript.SetScriptState(state);
 }
Exemplo n.º 52
0
        private void SelectHendel_Click(object sender, EventArgs e)
        {
            _ScriptState = ScriptState.selectSwitch;

            UpdateStatus();
        }
Exemplo n.º 53
0
 public abstract void SetScriptState(ScriptState state);
Exemplo n.º 54
0
        private void BuildAndRun(Script <object> newScript, InteractiveScriptGlobals globals, ref ScriptState <object> state, ref ScriptOptions options, bool displayResult, CancellationToken cancellationToken)
        {
            var diagnostics = newScript.Compile(cancellationToken);

            DisplayDiagnostics(diagnostics);
            if (diagnostics.HasAnyErrors())
            {
                return;
            }

            var task = (state == null) ?
                       newScript.RunAsync(globals, catchException: e => true, cancellationToken: cancellationToken) :
                       newScript.RunFromAsync(state, catchException: e => true, cancellationToken: cancellationToken);

            state = task.GetAwaiter().GetResult();
            if (state.Exception != null)
            {
                DisplayException(state.Exception);
            }
            else if (displayResult && newScript.HasReturnValue())
            {
                globals.Print(state.ReturnValue);
            }

            options = UpdateOptions(options, globals);
        }
Exemplo n.º 55
0
        private bool TryBuildAndRun(Script<object> newScript, InteractiveScriptGlobals globals, ref ScriptState<object> state, ref ScriptOptions options, CancellationToken cancellationToken)
        {
            var diagnostics = newScript.Compile(cancellationToken);
            DisplayDiagnostics(diagnostics);
            if (diagnostics.HasAnyErrors())
            {
                return false;
            }

            try
            {
                var task = (state == null) ?
                    newScript.RunAsync(globals, cancellationToken) :
                    newScript.ContinueAsync(state, cancellationToken);

                state = task.GetAwaiter().GetResult();
            }
            catch (FileLoadException e) when (e.InnerException is InteractiveAssemblyLoaderException)
            {
                var oldColor = _console.ForegroundColor;
                try
                {
                    _console.ForegroundColor = ConsoleColor.Red;
                    _console.Out.WriteLine(e.InnerException.Message);
                }
                finally
                {
                    _console.ForegroundColor = oldColor;
                }

                return false;
            }
            catch (Exception e)
            {
                DisplayException(e);
                return false;
            }

            options = UpdateOptions(options, globals);

            return true;
        }
Exemplo n.º 56
0
        public async Task <ReplFiddleExecuteResponse> ExecuteFiddleAsync(ReplFiddleExecuteRequest request)
        {
            var response = new ReplFiddleExecuteResponse();

            _scriptState = null;

            List <string> codeBlocks = new List <string>();

            codeBlocks.AddRange(request.PreviousCodeBlocks);
            codeBlocks.Add(request.CodeBlock);


            for (int i = 0; i < codeBlocks.Count; i++)
            {
                bool       isLastCodeEntry  = i == codeBlocks.Count - 1;
                TextWriter oldConsoleOutput = null;
                TextWriter newConsoleOutput = null;

                if (isLastCodeEntry)
                {
                    lock (_lockLastEntryExecution)
                    {
                        oldConsoleOutput = Console.Out;
                        newConsoleOutput = new StringWriter();
                        Console.SetOut(newConsoleOutput);

                        try
                        {
                            try
                            {
                                response.ReturnValue = RunCodeEntry(codeBlocks[i]).Result;
                            }
                            catch (Exception ex)
                            {
                                //User inner exception because async method throws AggregateException
                                response.ExceptionErrorMessage = ex.InnerException.Message;
                            }


                            string consoleOutputText = newConsoleOutput.ToString();

                            if (!String.IsNullOrEmpty(consoleOutputText))
                            {
                                response.ConsoleOutput = consoleOutputText.Trim();
                            }
                        }
                        finally
                        {
                            Console.SetOut(oldConsoleOutput);
                        }
                    }
                }
                else
                {
                    try
                    {
                        //The return values for all but last code entry are not used
                        string someReturnValue = await RunCodeEntry(codeBlocks[i]);
                    }
                    catch (Exception e)
                    {
                        Debug.WriteLine(e.Message);
                    }
                }
            }

            if (request.IsDebugEnabled)
            {
                response.DebugInfo = "Input: " + request.CodeBlock
                                     + Environment.NewLine + Environment.NewLine
                                     + "Output: "
                                     + Environment.NewLine + Environment.NewLine
                                     + JsonConvert.SerializeObject(response);
            }

            return(response);
        }
Exemplo n.º 57
0
 public override void GetScriptState(out ScriptState state)
 {
     activeScript.GetScriptState(out state);
 }
Exemplo n.º 58
0
 private void SelectHoek_Click(object sender, EventArgs e)
 {
     _ScriptState = ScriptState.SelectCorner;
     UpdateStatus();
 }
Exemplo n.º 59
0
        private bool TryBuildAndRun(Script<object> newScript, object globals, ref ScriptState<object> state, out Compilation newCompilation, CancellationToken cancellationToken)
        {
            newCompilation = newScript.GetCompilation();

            try
            {
                newScript.Build(cancellationToken);

                // display warnings:
                DisplayDiagnostics(newCompilation.GetDiagnostics(cancellationToken).Where(d => d.Severity == DiagnosticSeverity.Warning));
            }
            catch (CompilationErrorException e)
            {
                DisplayDiagnostics(e.Diagnostics.Where(d => d.Severity == DiagnosticSeverity.Error || d.Severity == DiagnosticSeverity.Warning));
                return false;
            }

            try
            {
                var task = (state == null) ?
                    newScript.RunAsync(globals, cancellationToken) :
                    newScript.ContinueAsync(state, cancellationToken);

                state = task.GetAwaiter().GetResult();
            }
            catch (Exception e)
            {
                DisplayException(e);
                return false;
            }

            return true;
        }
Exemplo n.º 60
0
        private void RunInteractiveLoop(ScriptOptions options, string initialScriptCodeOpt, CancellationToken cancellationToken)
        {
            var globals = new InteractiveScriptGlobals(_console.Out, _objectFormatter);

            globals.Args.AddRange(_compiler.Arguments.ScriptArguments);

            ScriptState <object> state = null;

            if (initialScriptCodeOpt != null)
            {
                var script = Script.CreateInitialScript <object>(_scriptCompiler, SourceText.From(initialScriptCodeOpt), options, globals.GetType(), assemblyLoaderOpt: null);
                BuildAndRun(script, globals, ref state, ref options, displayResult: false, cancellationToken: cancellationToken);
            }

            while (true)
            {
                _console.Out.Write("> ");
                var    input = new StringBuilder();
                string line;
                bool   cancelSubmission = false;

                while (true)
                {
                    line = _console.In.ReadLine();
                    if (line == null)
                    {
                        if (input.Length == 0)
                        {
                            return;
                        }

                        cancelSubmission = true;
                        break;
                    }

                    input.AppendLine(line);

                    var tree = _scriptCompiler.ParseSubmission(SourceText.From(input.ToString()), cancellationToken);
                    if (_scriptCompiler.IsCompleteSubmission(tree))
                    {
                        break;
                    }

                    _console.Out.Write(". ");
                }

                if (cancelSubmission)
                {
                    continue;
                }

                string code = input.ToString();

                if (IsHelpCommand(code))
                {
                    DisplayHelpText();
                    continue;
                }

                Script <object> newScript;
                if (state == null)
                {
                    newScript = Script.CreateInitialScript <object>(_scriptCompiler, SourceText.From(code ?? string.Empty), options, globals.GetType(), assemblyLoaderOpt: null);
                }
                else
                {
                    newScript = state.Script.ContinueWith(code, options);
                }

                BuildAndRun(newScript, globals, ref state, ref options, displayResult: true, cancellationToken: cancellationToken);
            }
        }