public static IReadOnlyCollection <SerializableDiagnostic> ExtractSerializableDiagnosticsFromSemanticModel(
            BufferId bufferId,
            Budget budget,
            SemanticModel semanticModel,
            Workspace workspace)
        {
            var diagnostics = workspace.MapDiagnostics(bufferId, semanticModel.GetDiagnostics().ToArray(), budget);

            return(diagnostics.DiagnosticsInActiveBuffer);
        }
        public static async Task <IReadOnlyCollection <SerializableDiagnostic> > ExtractSerializableDiagnosticsFromDocument(
            BufferId bufferId,
            Budget budget,
            Document selectedDocument,
            Workspace workspace)
        {
            var semanticModel = await selectedDocument.GetSemanticModelAsync();

            return(ExtractSerializableDiagnosticsFromSemanticModel(bufferId, budget, semanticModel, workspace));
        }
Beispiel #3
0
        private async Task <(IReadOnlyCollection <SerializableDiagnostic> DiagnosticsInActiveBuffer, IReadOnlyCollection <SerializableDiagnostic> AllDiagnostics)> ExtractDiagnostics(
            Workspace workspace,
            BufferId activeBufferId,
            ScriptOptions options)
        {
            workspace = await _transformer.TransformAsync(workspace);

            var sourceFile  = workspace.GetSourceFiles().Single();
            var code        = sourceFile.Text.ToString();
            var compilation = CSharpScript.Create(code, options).GetCompilation();

            return(workspace.MapDiagnostics(
                       activeBufferId,
                       compilation.GetDiagnostics()));
        }
        public async Task When_a_public_void_Main_with_parameters_is_present_it_is_invoked()
        {
            var server = GetCodeRunner();

            var workspace = Workspace.FromSource(@"
using System;

public static class Hello
{
    public static void Main(params string[] args)
    {
        Console.WriteLine(""Hello there!"");
    }
}", workspaceType: "console");

            var result = await server.Run(new WorkspaceRequest(workspace));

            result.ShouldSucceedWithOutput("Hello there!");
        }
Beispiel #5
0
        private async Task <CompileWorkerResult> CompileWorker(
            Workspace workspace,
            BufferId activeBufferId,
            Budget budget)
        {
            var package = await _packageFinder.Find <Package>(workspace.WorkspaceType);

            workspace = await _transformer.TransformAsync(workspace);

            var compilation = await package.Compile(workspace, budget, activeBufferId);

            var(diagnosticsInActiveBuffer, allDiagnostics) = workspace.MapDiagnostics(activeBufferId, compilation.GetDiagnostics());

            budget.RecordEntryAndThrowIfBudgetExceeded();
            return(new CompileWorkerResult(
                       compilation,
                       diagnosticsInActiveBuffer,
                       allDiagnostics));
        }
Beispiel #6
0
        public async Task When_a_public_void_Main_with_no_parameters_is_present_it_is_invoked()
        {
            var(server, build) = await GetRunnerAndWorkspaceBuild();

            var workspace = Workspace.FromSource(@"
using System;

public static class Hello
{
    public static void Main()
    {
        Console.WriteLine(""Hello there!"");
    }
}", workspaceType: build.Name);

            var result = await server.Run(new WorkspaceRequest(workspace));

            result.ShouldSucceedWithOutput("Hello there!");
        }
        public async Task Response_indicates_when_compile_is_successful_and_signature_is_like_a_console_app()
        {
            var server = GetCodeRunner();

            var workspace = Workspace.FromSource(@"
using System;

public static class Hello
{
    public static void Main()
    {
    }
}
", workspaceType: "console");

            var result = await server.Run(new WorkspaceRequest(workspace));

            Log.Trace(result.ToString());

            result.ShouldSucceedWithNoOutput();
        }
Beispiel #8
0
        private async Task <CompileWorkerResult> CompileWorker(
            Workspace workspace,
            BufferId activeBufferId,
            Budget budget)
        {
            var package = await _packageFinder.Find <ICreateWorkspace>(workspace.WorkspaceType);

            workspace = await workspace.InlineBuffersAsync();

            var sources = workspace.GetSourceFiles();

            var(compilation, documents) = await package.GetCompilation(sources, SourceCodeKind.Regular, workspace.Usings, () => package.CreateRoslynWorkspaceAsync(budget), budget);

            var(diagnosticsInActiveBuffer, allDiagnostics) = workspace.MapDiagnostics(activeBufferId, compilation.GetDiagnostics());

            budget.RecordEntryAndThrowIfBudgetExceeded();
            return(new CompileWorkerResult(
                       compilation,
                       diagnosticsInActiveBuffer,
                       allDiagnostics));
        }
        public async Task When_an_internal_void_Main_with_no_parameters_is_present_it_is_invoked()
        {
            var server = await GetCodeRunnerAsync();

            var workspace = Workspace.FromSource(@"
using System;

public static class Hello
{
    static void Main()
    {
        Console.WriteLine(""Hello there!"");
    }
}", workspaceType:"console");

            var result = await server.Run(new WorkspaceRequest(workspace));

            Log.Trace(result.ToString());

            result.ShouldSucceedWithOutput("Hello there!");
        }
        public async Task Response_shows_program_output_when_compile_is_successful_and_signature_is_like_a_console_app()
        {
            var output = nameof(Response_shows_program_output_when_compile_is_successful_and_signature_is_like_a_console_app);

            var server = GetCodeRunner();

            var workspace = Workspace.FromSource($@"
using System;

public static class Hello
{{
    public static void Main()
    {{
        Console.WriteLine(""{output}"");
    }}
}}", workspaceType: "console");


            var result = await server.Run(new WorkspaceRequest(workspace));

            result.ShouldSucceedWithOutput(output);
        }
Beispiel #11
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);
        }
Beispiel #12
0
 private IEnumerable <string> GetUsings(Workspace workspace)
 {
     return(workspace.WorkspaceType == "script"
                ? workspace.Usings.Concat(WorkspaceUtilities.DefaultUsings).Distinct()
                : workspace.Usings);
 }
Beispiel #13
0
        internal static (IReadOnlyCollection <SerializableDiagnostic> DiagnosticsInActiveBuffer, IReadOnlyCollection <SerializableDiagnostic> AllDiagnostics) MapDiagnostics(
            this Workspace workspace,
            BufferId activeBufferId,
            IReadOnlyCollection <Diagnostic> diagnostics,
            Budget budget = null)
        {
            if (workspace == null)
            {
                throw new ArgumentNullException(nameof(workspace));
            }

            if (diagnostics == null || diagnostics.Count == 0)
            {
                return(Array.Empty <SerializableDiagnostic>(), Array.Empty <SerializableDiagnostic>());
            }
            else
            {
                diagnostics = diagnostics.RemoveSuppressed();
            }

            budget = budget ?? new Budget();

            var viewPorts = workspace.ExtractViewPorts().ToList();

            budget.RecordEntry();

            var paddingSize = BufferInliningTransformer.PaddingSize;

            var diagnosticsInBuffer = FilterDiagnosticsForViewport().ToArray();
            var projectDiagnostics  = diagnostics.Select(d => d.ToSerializableDiagnostic()).ToArray();

            return(
                diagnosticsInBuffer,
                projectDiagnostics
                );

            IEnumerable <SerializableDiagnostic> FilterDiagnosticsForViewport()
            {
                foreach (var diagnostic in diagnostics)
                {
                    if (diagnostic.Location == Location.None)
                    {
                        continue;
                    }

                    var filePath = diagnostic.Location.SourceTree?.FilePath;

                    // hide warnings that are not within the visible code
                    if (!diagnostic.IsError() &&
                        !string.IsNullOrWhiteSpace(filePath))
                    {
                        if (Path.GetFileName(filePath) != Path.GetFileName(activeBufferId?.FileName))
                        {
                            continue;
                        }
                    }

                    var lineSpan     = diagnostic.Location.GetMappedLineSpan();
                    var lineSpanPath = lineSpan.Path;

                    if (viewPorts.Count == 0 || string.IsNullOrWhiteSpace(activeBufferId?.RegionName))
                    {
                        var errorMessage = RelativizeDiagnosticMessage();

                        yield return(diagnostic.ToSerializableDiagnostic(errorMessage, activeBufferId));
                    }
                    else
                    {
                        var target = viewPorts
                                     .Where(e => e.BufferId.RegionName != null &&
                                            e.BufferId.RegionName == activeBufferId.RegionName &&
                                            (string.IsNullOrWhiteSpace(lineSpanPath) || lineSpanPath.EndsWith(e.Destination.Name)))
                                     .FirstOrDefault(e => e.Region.Contains(diagnostic.Location.SourceSpan.Start));

                        if (target != null && !target.Region.IsEmpty)
                        {
                            var processedDiagnostic = AlignDiagnosticLocation(target, diagnostic, paddingSize);
                            if (processedDiagnostic != null)
                            {
                                yield return(processedDiagnostic);
                            }
                        }
                    }

                    string RelativizeDiagnosticMessage()
                    {
                        var message = diagnostic.ToString();

                        if (!string.IsNullOrWhiteSpace(lineSpanPath))
                        {
                            var directoryPath = new FileInfo(lineSpanPath).Directory?.FullName ?? "";

                            if (!directoryPath.EndsWith(Path.DirectorySeparatorChar.ToString()))
                            {
                                directoryPath += Path.DirectorySeparatorChar;
                            }

                            if (message.StartsWith(directoryPath))
                            {
                                return(message.Substring(directoryPath.Length));
                            }
                        }

                        return(message);
                    }
                }
            }
        }
        private static async Task <RedirectedPackage> CreatePackageWithChanges(Package package, Workspace workspace)
        {
            // copy project and assets to temporary location
            var tempDirName        = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            var packageWithChanges = new RedirectedPackage(workspace, package, Directory.CreateDirectory(tempDirName));

            try
            {
                await CopyDirectory(package.Directory.FullName, packageWithChanges.Directory.FullName);

                // overwrite files
                foreach (var file in workspace.Files)
                {
                    File.WriteAllText(Path.Combine(packageWithChanges.Directory.FullName, Path.GetFileName(file.Name)), file.Text);
                }

                return(packageWithChanges);
            }
            catch
            {
                packageWithChanges.Clean();
                return(null);
            }
        }
        private async Task <(RedirectedPackage, CompileResult)> Compile(Package package, Workspace workspace, string requestId)
        {
            var packageWithChanges = await CreatePackageWithChanges(package, workspace);

            try
            {
                await package.FullBuild(); // ensure `package.EntryPointAssemblyPath.FullName` has a value

                await packageWithChanges.FullBuild();

                // copy the entire output directory back
                await CopyDirectory(
                    Path.GetDirectoryName(packageWithChanges.EntryPointAssemblyPath.FullName),
                    Path.GetDirectoryName(package.EntryPointAssemblyPath.FullName));

                return(packageWithChanges, new CompileResult(
                           true, // succeeded
                           Convert.ToBase64String(File.ReadAllBytes(package.EntryPointAssemblyPath.FullName)),
                           diagnostics: null,
                           requestId: requestId));
            }
            catch (Exception e)
            {
                packageWithChanges.Clean();
                return(null, new CompileResult(
                           false,        // succeeded
                           string.Empty, // assembly base64
                           new SerializableDiagnostic[]
                {
                    // TODO: populate with real compiler diagnostics
                    new SerializableDiagnostic(0, 0, e.Message, DiagnosticSeverity.Error, "Compile error")
                },
                           requestId));
            }
        }
Beispiel #16
0
 private static ScriptOptions CreateOptions(Workspace request) =>
 ScriptOptions.Default
 .AddReferences(GetReferenceAssemblies())
 .AddImports(WorkspaceUtilities.DefaultUsings.Concat(request.Usings));