Exemplo n.º 1
0
 public RedirectedPackage(Workspace workspace, Package parentPackage, DirectoryInfo directory)
     : base(parentPackage.Name, parentPackage.Initializer, directory)
 {
     _parentPackage       = parentPackage;
     _redirectedDirectory = directory;
     _workspace           = workspace;
 }
Exemplo n.º 2
0
        public async Task The_Compile_contract_for_compiling_code_has_not_been_broken()
        {
            var package = await Package.Copy(await Default.ConsoleWorkspace());

            var viewport = ViewportCode();

            var requestJson = new WorkspaceRequest(
                new Workspace(
                    workspaceType: package.Name,
                    buffers: new[]
            {
                EntrypointCode(),
                viewport
            }),
                activeBufferId: viewport.Id,
                requestId: "TestRun");

            var response = await CallCompile(requestJson.ToJson());

            var result = await response.Content.ReadAsStringAsync();

            var compileResult = result.FromJsonTo <CompileResult>();

            compileResult.Base64Assembly.Should().NotBeNullOrWhiteSpace();
            compileResult = new CompileResult(
                compileResult.Succeeded,
                "",
                compileResult.GetFeature <Diagnostics>(),
                compileResult.RequestId);

            result = compileResult.ToJson().FormatJson();

            this.Assent(result, configuration);
        }
Exemplo n.º 3
0
        public async Task The_Run_contract_for_noncompiling_code_has_not_been_broken()
        {
            var package = await Package.Copy(await Default.ConsoleWorkspace());

            var viewport = ViewportCode("doesn't compile");

            var request = new WorkspaceRequest(
                new Workspace(
                    workspaceType: package.Name,
                    buffers: new[]
            {
                EntrypointCode(),
                viewport
            }),
                activeBufferId: viewport.Id,
                requestId: "TestRun");

            var requestBody = request.ToJson();

            var response = await CallRun(requestBody);

            var result = await response.Content.ReadAsStringAsync();

            this.Assent(RemoveMachineSpecificPaths(result).FormatJson(), configuration);
        }
Exemplo n.º 4
0
 protected override Workspace CreateWorkspaceWithMainContaining(string text, Package package)
 {
     return(Workspace.FromSource(
                $@"using System; using System.Linq; using System.Collections.Generic; class Program {{ static void Main() {{ {text}
             }}
         }}
     ",
                workspaceType: package.Name));
 }
Exemplo n.º 5
0
        public static async Task <(Compilation compilation, IReadOnlyCollection <Document> documents)> GetCompilation(
            this Package package,
            IReadOnlyCollection <SourceFile> sources,
            SourceCodeKind sourceCodeKind,
            IEnumerable <string> defaultUsings,
            Func <Task <Microsoft.CodeAnalysis.Workspace> > workspaceFactory,
            Budget budget)
        {
            var workspace = await workspaceFactory();

            var currentSolution = workspace.CurrentSolution;
            var project         = currentSolution.Projects.First();
            var projectId       = project.Id;

            foreach (var source in sources)
            {
                if (currentSolution.Projects
                    .SelectMany(p => p.Documents)
                    .FirstOrDefault(d => d.IsMatch(source)) is Document document)
                {
                    // there's a pre-existing document, so overwrite its contents
                    document        = document.WithText(source.Text);
                    document        = document.WithSourceCodeKind(sourceCodeKind);
                    currentSolution = document.Project.Solution;
                }
                else
                {
                    var docId = DocumentId.CreateNewId(projectId, $"{package.Name}.Document");

                    currentSolution = currentSolution.AddDocument(docId, source.Name, source.Text);
                    currentSolution = currentSolution.WithDocumentSourceCodeKind(docId, sourceCodeKind);
                }
            }


            project = currentSolution.GetProject(projectId);
            var usings = defaultUsings?.ToArray() ?? Array.Empty <string>();

            if (usings.Length > 0)
            {
                var options = (CSharpCompilationOptions)project.CompilationOptions;
                project = project.WithCompilationOptions(options.WithUsings(usings));
            }

            var compilation = await project.GetCompilationAsync().CancelIfExceeds(budget);

            return(compilation, project.Documents.ToArray());
        }
Exemplo n.º 6
0
        public WebServer(Package package)
        {
            this.package = package ?? throw new ArgumentNullException(nameof(package));

            _listeningAtUri = new AsyncLazy <Uri>(RunKestrel);

            _getHttpClient = new AsyncLazy <HttpClient>(async() =>
            {
                var httpClient = new HttpClient
                {
                    BaseAddress = await EnsureStarted()
                };

                return(httpClient);
            });
        }
Exemplo n.º 7
0
        public async Task The_run_contract_with_no_instrumentation_has_not_been_broken()
        {
            var package = await Package.Copy(await Default.ConsoleWorkspace());

            var requestJson = new WorkspaceRequest(
                new Workspace(
                    workspaceType: package.Name,
                    buffers: new[]
            {
                EntrypointCode("int a = 1; int b = 2; a = 3; b = a;")
            },
                    includeInstrumentation: false),
                requestId: "TestRun"
                ).ToJson();

            var response = await CallRun(requestJson);

            var result = await response.Content.ReadAsStringAsync();

            this.Assent(RemoveMachineSpecificPaths(result).FormatJson(), configuration);
        }
Exemplo n.º 8
0
        public static async Task <Compilation> Compile(
            this Package package,
            Workspace workspace,
            Budget budget,
            BufferId activeBufferId)
        {
            var sourceFiles = workspace.GetSourceFiles().ToArray();

            var(compilation, documents) = await package.GetCompilationForRun(sourceFiles, SourceCodeKind.Regular, workspace.Usings, budget);

            var viewports = workspace.ExtractViewPorts();

            var diagnostics = compilation.GetDiagnostics();

            if (workspace.IncludeInstrumentation && !diagnostics.ContainsError())
            {
                var activeDocument = GetActiveDocument(documents, activeBufferId);
                compilation = await AugmentCompilationAsync(viewports, compilation, activeDocument, activeBufferId, package);
            }

            return(compilation);
        }
Exemplo n.º 9
0
        public async Task The_signature_help_contract_has_not_been_broken()
        {
            var package = await Package.Copy(await Default.ConsoleWorkspace());

            var viewport = ViewportCode("Console.Write($$);");

            var requestJson = new WorkspaceRequest(
                new Workspace(
                    workspaceType: package.Name,
                    buffers: new[]
            {
                EntrypointCode(),
                viewport
            }),
                activeBufferId: viewport.Id,
                requestId: "TestRun").ToJson();

            var response = await CallSignatureHelp(requestJson);

            var result = await response.Content.ReadAsStringAsync();

            this.Assent(result.FormatJson(), configuration);
        }
Exemplo n.º 10
0
 protected abstract Workspace CreateWorkspaceWithMainContaining(
     string text,
     Package package);
Exemplo n.º 11
0
        private static async Task <Compilation> AugmentCompilationAsync(
            IEnumerable <Viewport> viewports,
            Compilation compilation,
            Document document,
            BufferId activeBufferId,
            Package build)
        {
            var regions = InstrumentationLineMapper.FilterActiveViewport(viewports, activeBufferId)
                          .Where(v => v.Destination?.Name != null)
                          .GroupBy(v => v.Destination.Name,
                                   v => v.Region,
                                   (name, region) => new InstrumentationMap(name, region))
                          .ToArray();

            var solution       = document.Project.Solution;
            var newCompilation = compilation;

            foreach (var tree in newCompilation.SyntaxTrees)
            {
                var replacementRegions = regions.FirstOrDefault(r => tree.FilePath.EndsWith(r.FileToInstrument))?.InstrumentationRegions;

                var subdocument = solution.GetDocument(tree);
                var visitor     = new InstrumentationSyntaxVisitor(subdocument, await subdocument.GetSemanticModelAsync(), replacementRegions);
                var linesWithInstrumentation = visitor.Augmentations.Data.Keys;

                var activeViewport = viewports.DefaultIfEmpty(null).First();

                var(augmentationMap, variableLocationMap) =
                    await InstrumentationLineMapper.MapLineLocationsRelativeToViewportAsync(
                        visitor.Augmentations,
                        visitor.VariableLocations,
                        document,
                        activeViewport);

                var rewrite = new InstrumentationSyntaxRewriter(
                    linesWithInstrumentation,
                    variableLocationMap,
                    augmentationMap);
                var newRoot = rewrite.Visit(tree.GetRoot());
                var newTree = tree.WithRootAndOptions(newRoot, tree.Options);

                newCompilation = newCompilation.ReplaceSyntaxTree(tree, newTree);
            }

            var instrumentationSyntaxTree = build.GetInstrumentationEmitterSyntaxTree();

            newCompilation = newCompilation.AddSyntaxTrees(instrumentationSyntaxTree);

            var augmentedDiagnostics = newCompilation.GetDiagnostics();

            if (augmentedDiagnostics.ContainsError())
            {
                throw new InvalidOperationException(
                          $@"Augmented source failed to compile

Diagnostics
-----------
{string.Join(NewLine, augmentedDiagnostics)}

Source
------
{newCompilation.SyntaxTrees.Select(s => $"// {s.FilePath ?? "(anonymous)"}{NewLine}//---------------------------------{NewLine}{NewLine}{s}").Join(NewLine + NewLine)}");
            }

            return(newCompilation);
        }
Exemplo n.º 12
0
 public static Task <(Compilation compilation, IReadOnlyCollection <Document> documents)> GetCompilationForRun(
     this Package package,
     IReadOnlyCollection <SourceFile> sources,
     SourceCodeKind sourceCodeKind,
     IEnumerable <string> defaultUsings,
     Budget budget) =>
        public async Task Get_documentation_with_signature_help_for_console_writeline()
        {
            #region bufferSources

            var program = @"using System;
using System.Linq;

namespace FibonacciTest
{
    public class Program
    {
        public static void Main()
        {
            foreach (var i in FibonacciGenerator.Fibonacci().Take(20))
            {
                Console.WriteLine(i);
            }
        }
    }
}".EnforceLF();

            var generator = @"using System.Collections.Generic;
using System;
namespace FibonacciTest
{
    public static class FibonacciGenerator
    {
        public static IEnumerable<int> Fibonacci()
        {
            int current = 1, next = 1;
            while (true)
            {
                yield return current;
                next = current + (current = next);
                Console.WriteLine($$);
            }
        }
    }
}".EnforceLF();

            #endregion

            var(processed, position) = CodeManipulation.ProcessMarkup(generator);
            var package = await Package.Copy(await Default.ConsoleWorkspace());

            var workspace = new Workspace(workspaceType: package.Name, buffers: new[]
            {
                new Buffer("Program.cs", program),
                new Buffer("generators/FibonacciGenerator.cs", processed, position)
            });

            var request = new WorkspaceRequest(workspace, activeBufferId: "generators/FibonacciGenerator.cs");
            var server  = GetLanguageService();
            var result  = await server.GetSignatureHelp(request);

            result.Signatures.Should().NotBeNullOrEmpty();

            var sample = result.Signatures.Where(e => e.Label == "void Console.WriteLine(string format, params object[] arg)").First();
            sample.Documentation.Value.Should().Contain("Writes the text representation of the specified array of objects, followed by the current line terminator, to the standard output stream using the specified format information.");
            sample.Parameters.Should().HaveCount(2);

            sample.Parameters.ElementAt(0).Name.Should().Be("format");
            sample.Parameters.ElementAt(0).Label.Should().Be("string format");
            sample.Parameters.ElementAt(0).Documentation.Value.Should().Contain("A composite format string.");

            sample.Parameters.ElementAt(1).Name.Should().Be("arg");
            sample.Parameters.ElementAt(1).Label.Should().Be("params object[] arg");
            sample.Parameters.ElementAt(1).Documentation.Value.Should().Contain("An array of objects to write using format.");
        }
        public async Task Get_documentation_with_autocompletion_of_console_methods()
        {
            #region bufferSources

            var program = @"using System;
using System.Linq;

namespace FibonacciTest
{
    public class Program
    {
        public static void Main()
        {
            foreach (var i in FibonacciGenerator.Fibonacci().Take(20))
            {
                Console.WriteLine(i);
            }
        }
    }
}".EnforceLF();

            var generator = @"using System.Collections.Generic;
using System;
namespace FibonacciTest
{
    public static class FibonacciGenerator
    {
        public static IEnumerable<int> Fibonacci()
        {
            int current = 1, next = 1;
            while (true)
            {
                yield return current;
                next = current + (current = next);
                Console.$$
            }
        }
    }
}".EnforceLF();

            #endregion

            var package = await Package.Copy(await Default.ConsoleWorkspace());

            var(processed, position) = CodeManipulation.ProcessMarkup(generator);

            var workspace = new Workspace(workspaceType: package.Name, buffers: new[]
            {
                new Buffer("Program.cs", program),
                new Buffer("generators/FibonacciGenerator.cs", processed, position)
            });

            var request = new WorkspaceRequest(workspace, activeBufferId: "generators/FibonacciGenerator.cs");
            var server  = GetLanguageService();
            var result  = await server.GetCompletionList(request);

            result.Should().NotBeNull();
            result.Items.Should().NotBeNullOrEmpty();

            result.Items
            .Where(i => i.Documentation != null && !string.IsNullOrWhiteSpace(i.Documentation.Value))
            .Select(i => i.Documentation.Value)
            .Should()
            .Contain(d => d == "Writes the text representation of the specified Boolean value to the standard output stream.");
        }