Exemple #1
0
        public InteractiveHostTests()
        {
            _host = new InteractiveHost(typeof(CSharpReplServiceProvider), ".", millisecondsTimeout: -1, joinOutputWritingThreadsOnDisposal: true);

            RedirectOutput();

            _host.ResetAsync(new InteractiveHostOptions(GetInteractiveHostDirectory(), initializationFile: null, culture: CultureInfo.InvariantCulture)).Wait();

            var remoteService = _host.TryGetService();

            Assert.NotNull(remoteService);

            _host.SetPathsAsync(new[] { s_fxDir }, new[] { s_homeDir }, s_homeDir).Wait();

            // assert and remove logo:
            var output      = SplitLines(ReadOutputToEnd());
            var errorOutput = ReadErrorOutputToEnd();

            Assert.Equal("", errorOutput);
            Assert.Equal(2, output.Length);
            var version = CommonCompiler.GetProductVersion(typeof(CSharpReplServiceProvider));

            Assert.Equal(string.Format(CSharpScriptingResources.LogoLine1, version), output[0]);
            // "Type "#help" for more information."
            Assert.Equal(InteractiveHostResources.Type_Sharphelp_for_more_information, output[1]);

            // remove logo:
            ClearOutput();
        }
Exemple #2
0
        internal static int Run(string[] args)
        {
            FatalError.Handler = FailFast.OnFatalException;

            var responseFile = CommonCompiler.GetResponseFileFullPath(VisualBasicCompiler.ResponseFileName);
            Vbc compiler     = new Vbc(responseFile, Directory.GetCurrentDirectory(), args);

            // We store original encoding and restore it later to revert
            // the changes that might be done by /utf8output options
            // NOTE: original encoding may not be restored if process terminated
            Encoding origEncoding = Console.OutputEncoding;

            try
            {
                if (compiler.Arguments.Utf8Output && Console.IsOutputRedirected)
                {
                    Console.OutputEncoding = Encoding.UTF8;
                }
                return(compiler.Run(Console.Out, default(CancellationToken)));
            }
            finally
            {
                try
                {
                    Console.OutputEncoding = origEncoding;
                }
                catch
                { // Try to reset the output encoding, ignore if we can't
                }
            }
        }
Exemple #3
0
        internal static (int Result, string Output) Run(this CommonCompiler compiler, CancellationToken cancellationToken = default)
        {
            using var writer = new StringWriter();
            var result = compiler.Run(writer, cancellationToken);

            return(result, writer.ToString());
        }
 public bool TryCreateCompiler(RunRequest request, out CommonCompiler compiler)
 {
     switch (request.Language)
     {
         case LanguageNames.CSharp:
             compiler = new CSharpCompilerServer(
                 this,
                 args: request.Arguments,
                 clientDirectory: ClientDirectory,
                 baseDirectory: request.CurrentDirectory,
                 sdkDirectory: SdkDirectory,
                 libDirectory: request.LibDirectory,
                 analyzerLoader: AnalyzerAssemblyLoader);
             return true;
         case LanguageNames.VisualBasic:
             compiler = new VisualBasicCompilerServer(
                 this,
                 args: request.Arguments,
                 clientDirectory: ClientDirectory,
                 baseDirectory: request.CurrentDirectory,
                 sdkDirectory: SdkDirectory,
                 libDirectory: request.LibDirectory,
                 analyzerLoader: AnalyzerAssemblyLoader);
             return true;
         default:
             compiler = null;
             return false;
     }
 }
Exemple #5
0
        public bool TryCreateCompiler(RunRequest request, out CommonCompiler compiler)
        {
            var buildPaths = new BuildPaths(ClientDirectory, request.CurrentDirectory, SdkDirectory, request.TempDirectory);

            switch (request.Language)
            {
            case LanguageNames.CSharp:
                compiler = new CSharpCompilerServer(
                    AssemblyReferenceProvider,
                    args: request.Arguments,
                    buildPaths: buildPaths,
                    libDirectory: request.LibDirectory,
                    analyzerLoader: AnalyzerAssemblyLoader);
                return(true);

            case LanguageNames.VisualBasic:
                compiler = new VisualBasicCompilerServer(
                    AssemblyReferenceProvider,
                    args: request.Arguments,
                    buildPaths: buildPaths,
                    libDirectory: request.LibDirectory,
                    analyzerLoader: AnalyzerAssemblyLoader);
                return(true);

            default:
                compiler = null;
                return(false);
            }
        }
 public bool TryCreateCompiler(RunRequest request, out CommonCompiler compiler)
 {
     var buildPaths = new BuildPaths(ClientDirectory, request.CurrentDirectory, SdkDirectory, request.TempDirectory);
     switch (request.Language)
     {
         case LanguageNames.CSharp:
             compiler = new CSharpCompilerServer(
                 AssemblyReferenceProvider,
                 args: request.Arguments,
                 buildPaths: buildPaths,
                 libDirectory: request.LibDirectory,
                 analyzerLoader: AnalyzerAssemblyLoader);
             return true;
         case LanguageNames.VisualBasic:
             compiler = new VisualBasicCompilerServer(
                 AssemblyReferenceProvider,
                 args: request.Arguments,
                 buildPaths: buildPaths,
                 libDirectory: request.LibDirectory,
                 analyzerLoader: AnalyzerAssemblyLoader);
             return true;
         default:
             compiler = null;
             return false;
     }
 }
        /// <summary>
        /// csi.exe and vbi.exe entry point.
        /// </summary>
        private static int RunInteractiveCore(CommonCompiler compiler, TextWriter consoleOutput, ErrorLogger errorLogger)
        {
            Debug.Assert(compiler.Arguments.IsInteractive);

            var hasScriptFiles = compiler.Arguments.SourceFiles.Any(file => file.IsScript);

            if (compiler.Arguments.DisplayLogo && !hasScriptFiles)
            {
                compiler.PrintLogo(consoleOutput);
            }

            if (compiler.Arguments.DisplayHelp)
            {
                compiler.PrintHelp(consoleOutput);
                return(0);
            }

            // TODO (tomat):
            // When we have command line REPL enabled we'll launch it if there are no input files.
            IEnumerable <Diagnostic> errors = compiler.Arguments.Errors;

            if (!hasScriptFiles)
            {
                errors = errors.Concat(new[] { Diagnostic.Create(compiler.MessageProvider, compiler.MessageProvider.ERR_NoScriptsSpecified) });
            }

            if (compiler.ReportErrors(errors, consoleOutput, errorLogger))
            {
                return(CommonCompiler.Failed);
            }

            // arguments are always available when executing script code:
            Debug.Assert(compiler.Arguments.ScriptArguments != null);

            var compilation = compiler.CreateCompilation(consoleOutput, touchedFilesLogger: null, errorLogger: errorLogger);

            if (compilation == null)
            {
                return(CommonCompiler.Failed);
            }

            byte[] compiledAssembly;
            using (MemoryStream output = new MemoryStream())
            {
                EmitResult emitResult = compilation.Emit(output);
                if (compiler.ReportErrors(emitResult.Diagnostics, consoleOutput, errorLogger))
                {
                    return(CommonCompiler.Failed);
                }

                compiledAssembly = output.ToArray();
            }

            var assembly = CorLightup.Desktop.LoadAssembly(compiledAssembly);

            return(Execute(assembly, compilation.GetEntryPoint(default(CancellationToken)), compiler.Arguments.ScriptArguments.ToArray()));
        }
        public void TryGetCompilerDiagnosticCode_WrongPrefix()
        {
            string diagnosticId = "AB1011";

            uint code;
            var  result = CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "CS", out code);

            Assert.False(result);
        }
        public void TryGetCompilerDiagnosticCode_Invalid()
        {
            string diagnosticId = "MyAwesomeDiagnostic";

            uint code;
            var  result = CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "CS", out code);

            Assert.False(result);
        }
        public void TryGetCompilerDiagnosticCode_Valid()
        {
            string diagnosticId = "CS1011";

            uint code;
            var  result = CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "CS", out code);

            Assert.True(result);
            Assert.Equal(expected: 1011U, actual: code);
        }
        /// <summary>
        /// csi.exe and vbi.exe entry point.
        /// </summary>
        private static int RunInteractiveCore(CommonCompiler compiler, TextWriter consoleOutput, ErrorLogger errorLogger)
        {
            Debug.Assert(compiler.Arguments.IsInteractive);

            var hasScriptFiles = compiler.Arguments.SourceFiles.Any(file => file.IsScript);

            if (compiler.Arguments.DisplayLogo && !hasScriptFiles)
            {
                compiler.PrintLogo(consoleOutput);
            }

            if (compiler.Arguments.DisplayHelp)
            {
                compiler.PrintHelp(consoleOutput);
                return 0;
            }

            // TODO (tomat):
            // When we have command line REPL enabled we'll launch it if there are no input files. 
            IEnumerable<Diagnostic> errors = compiler.Arguments.Errors;
            if (!hasScriptFiles)
            {
                errors = errors.Concat(new[] { Diagnostic.Create(compiler.MessageProvider, compiler.MessageProvider.ERR_NoScriptsSpecified) });
            }

            if (compiler.ReportErrors(errors, consoleOutput, errorLogger))
            {
                return CommonCompiler.Failed;
            }

            // arguments are always available when executing script code:
            Debug.Assert(compiler.Arguments.ScriptArguments != null);

            var compilation = compiler.CreateCompilation(consoleOutput, touchedFilesLogger: null, errorLogger: errorLogger);
            if (compilation == null)
            {
                return CommonCompiler.Failed;
            }

            byte[] compiledAssembly;
            using (MemoryStream output = new MemoryStream())
            {
                EmitResult emitResult = compilation.Emit(output);
                if (compiler.ReportErrors(emitResult.Diagnostics, consoleOutput, errorLogger))
                {
                    return CommonCompiler.Failed;
                }

                compiledAssembly = output.ToArray();
            }

            var assembly = Assembly.Load(compiledAssembly);

            return Execute(assembly, compiler.Arguments.ScriptArguments.ToArray());
        }
Exemple #12
0
        internal TestableCompiler(CommonCompiler compiler, TestableFileSystem fileSystem, BuildPaths buildPaths)
        {
            if (!object.ReferenceEquals(compiler.FileSystem, fileSystem))
            {
                throw new ArgumentException(null, nameof(fileSystem));
            }

            Compiler   = compiler;
            FileSystem = fileSystem;
            BuildPaths = buildPaths;
        }
        public AdditionalTextFile(CommandLineSourceFile sourceFile, CommonCompiler compiler)
        {
            if (compiler == null)
            {
                throw new ArgumentNullException(nameof(compiler));
            }

            _sourceFile  = sourceFile;
            _compiler    = compiler;
            _diagnostics = SpecializedCollections.EmptyList <DiagnosticInfo>();
        }
        private static void BuildTouchedFiles(CommonCompiler cmd,
                                              string outputPath,
                                              out List <string> expectedReads,
                                              out List <string> expectedWrites)
        {
            expectedReads = new List <string>();
            expectedReads.AddRange(cmd.Arguments.MetadataReferences.Select(r => r.Reference));

            if (cmd.Arguments is VisualBasicCommandLineArguments {
                DefaultCoreLibraryReference : { } reference
            })
Exemple #15
0
        internal override string GetExpectedOutputForNoDiagnostics(CommonCompiler cmd)
        {
            var expectedHeader = GetExpectedErrorLogHeader(cmd);
            var expectedIssues = @"
      ""results"": [
      ]
    }
  ]
}";

            return(expectedHeader + expectedIssues);
        }
Exemple #16
0
        internal CommandLineRunner(ConsoleIO console, CommonCompiler compiler, ScriptCompiler scriptCompiler, ObjectFormatter objectFormatter)
        {
            Debug.Assert(console != null);
            Debug.Assert(compiler != null);
            Debug.Assert(scriptCompiler != null);
            Debug.Assert(objectFormatter != null);

            _console         = console;
            _compiler        = compiler;
            _scriptCompiler  = scriptCompiler;
            _objectFormatter = objectFormatter;
        }
Exemple #17
0
        internal CommandLineRunner(ConsoleIO console, CommonCompiler compiler, ScriptCompiler scriptCompiler, ObjectFormatter objectFormatter)
        {
            Debug.Assert(console != null);
            Debug.Assert(compiler != null);
            Debug.Assert(scriptCompiler != null);
            Debug.Assert(objectFormatter != null);

            _console = console;
            _compiler = compiler;
            _scriptCompiler = scriptCompiler;
            _objectFormatter = objectFormatter;
        }
Exemple #18
0
 internal static int Main(string[] args)
 {
     try
     {
         var responseFile = CommonCompiler.GetResponseFileFullPath(InteractiveResponseFileName);
         return(new Csi(responseFile, Directory.GetCurrentDirectory(), args).RunInteractive(Console.Out));
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.ToString());
         return(1);
     }
 }
Exemple #19
0
        /// <summary>
        /// Main entry point for the process. Initialize the server dispatcher
        /// and wait for connections.
        /// </summary>
        public static int Main(string[] args)
        {
            CompilerServerLogger.Initialize("SRV");
            CompilerServerLogger.Log("Process started");

            TimeSpan?keepAliveTimeout = null;

            try
            {
                int    keepAliveValue;
                string keepAliveStr = ConfigurationManager.AppSettings["keepalive"];
                if (int.TryParse(keepAliveStr, NumberStyles.Integer, CultureInfo.InvariantCulture, out keepAliveValue) &&
                    keepAliveValue >= 0)
                {
                    if (keepAliveValue == 0)
                    {
                        // This is a one time server entry.
                        keepAliveTimeout = null;
                    }
                    else
                    {
                        keepAliveTimeout = TimeSpan.FromSeconds(keepAliveValue);
                    }
                }
                else
                {
                    keepAliveTimeout = s_defaultServerKeepAlive;
                }
            }
            catch (ConfigurationErrorsException e)
            {
                keepAliveTimeout = s_defaultServerKeepAlive;
                CompilerServerLogger.LogException(e, "Could not read AppSettings");
            }

            CompilerServerLogger.Log("Keep alive timeout is: {0} milliseconds.", keepAliveTimeout?.TotalMilliseconds ?? 0);
            FatalError.Handler = FailFast.OnFatalException;

            // VBCSCompiler is installed in the same directory as csc.exe and vbc.exe which is also the
            // location of the response files.
            var responseFileDirectory = CommonCompiler.GetResponseFileDirectory();
            var dispatcher            = new ServerDispatcher(new CompilerRequestHandler(responseFileDirectory), new EmptyDiagnosticListener());

            // Add the process ID onto the pipe name so each process gets a semi-unique and predictable pipe
            // name.  The client must use this algorithm too to connect.
            string pipeName = BuildProtocolConstants.PipeName + Process.GetCurrentProcess().Id.ToString();

            dispatcher.ListenAndDispatchConnections(pipeName, keepAliveTimeout, watchAnalyzerFiles: true);
            return(0);
        }
        private string FormatOutputText(
            string s,
            CommonCompiler compiler,
            params object[] additionalArguments)
        {
            var arguments = new object[] {
                compiler.GetToolName(),
                compiler.GetCompilerVersion(),
                compiler.GetAssemblyVersion(),
                compiler.GetAssemblyVersion().ToString(fieldCount: 3),
                compiler.GetCultureName()
            }.Concat(additionalArguments).ToArray();

            return(string.Format(CultureInfo.InvariantCulture, s, arguments));
        }
Exemple #21
0
        private void VerifyRoundTrip(CommonCompiler commonCompiler, string peFilePath, string?pdbFilePath = null, CancellationToken cancellationToken = default)
        {
            Assert.True(commonCompiler.Arguments.CompilationOptions.Deterministic);
            var(result, output) = commonCompiler.Run(cancellationToken);
            TestOutputHelper.WriteLine(output);
            Assert.Equal(0, result);

            var peStream  = FilePathToStreamMap[peFilePath].GetStream();
            var pdbStream = pdbFilePath is object?FilePathToStreamMap[pdbFilePath].GetStream() : null;

            using var writer = new StringWriter();
            var compilation = commonCompiler.CreateCompilation(
                writer,
                touchedFilesLogger: null,
                errorLoggerOpt: null,
                analyzerConfigOptions: default,
        public async Task InitializeAsync()
        {
            var initializationFileName = UseDefaultInitializationFile
                ? "CSharpInteractive.rsp"
                : null;

            await Host.ResetAsync(
                InteractiveHostOptions.CreateFromDirectory(
                    TestUtils.HostRootPath,
                    initializationFileName,
                    CultureInfo.InvariantCulture,
                    DefaultPlatform
                    )
                );

            // assert and remove logo:
            var output      = SplitLines(await ReadOutputToEnd());
            var errorOutput = await ReadErrorOutputToEnd();

            AssertEx.AssertEqualToleratingWhitespaceDifferences("", errorOutput);

            var expectedOutput = new List <string>();

            expectedOutput.Add(
                string.Format(
                    CSharpScriptingResources.LogoLine1,
                    CommonCompiler.GetProductVersion(typeof(CSharpReplServiceProvider))
                    )
                );

            if (UseDefaultInitializationFile)
            {
                expectedOutput.Add(
                    string.Format(
                        InteractiveHostResources.Loading_context_from_0,
                        initializationFileName
                        )
                    );
            }

            expectedOutput.Add(InteractiveHostResources.Type_Sharphelp_for_more_information);

            AssertEx.Equal(expectedOutput, output);

            // remove logo:
            ClearOutput();
        }
        /// <summary>
        /// csi.exe and vbi.exe entry point.
        /// </summary>
        internal static int RunInteractive(CommonCompiler compiler, TextWriter consoleOutput)
        {
            ErrorLogger errorLogger = null;
            if (compiler.Arguments.ErrorLogPath != null)
            {
                errorLogger = compiler.GetErrorLogger(consoleOutput, CancellationToken.None);
                if (errorLogger == null)
                {
                    return CommonCompiler.Failed;
                }
            }

            using (errorLogger)
            {
                return RunInteractiveCore(compiler, consoleOutput, errorLogger);
            }
        }
        /// <summary>
        /// csi.exe and vbi.exe entry point.
        /// </summary>
        internal static int RunInteractive(CommonCompiler compiler, TextWriter consoleOutput)
        {
            ErrorLogger errorLogger = null;

            if (compiler.Arguments.ErrorLogPath != null)
            {
                errorLogger = compiler.GetErrorLogger(consoleOutput, CancellationToken.None);
                if (errorLogger == null)
                {
                    return(CommonCompiler.Failed);
                }
            }

            using (errorLogger)
            {
                return(RunInteractiveCore(compiler, consoleOutput, errorLogger));
            }
        }
Exemple #25
0
        public async Task InitializeAsync()
        {
            await _host.ResetAsync(new InteractiveHostOptions(GetInteractiveHostDirectory(), initializationFile : null, culture : CultureInfo.InvariantCulture));

            await _host.SetPathsAsync(new[] { s_fxDir }, new[] { s_homeDir }, s_homeDir);

            // assert and remove logo:
            var output      = SplitLines(await ReadOutputToEnd());
            var errorOutput = await ReadErrorOutputToEnd();

            Assert.Equal("", errorOutput);
            Assert.Equal(2, output.Length);
            var version = CommonCompiler.GetProductVersion(typeof(CSharpReplServiceProvider));

            Assert.Equal(string.Format(CSharpScriptingResources.LogoLine1, version), output[0]);
            // "Type "#help" for more information."
            Assert.Equal(InteractiveHostResources.Type_Sharphelp_for_more_information, output[1]);

            // remove logo:
            ClearOutput();
        }
Exemple #26
0
        /// <summary>
        /// An error/warning directive tells the compiler to indicate a syntactic error/warning
        /// at the current location.
        ///
        /// Format: #error Error message string
        /// Resulting message: from the first non-whitespace character after the directive
        /// keyword until the end of the directive (aka EOD) at the line break or EOF.
        /// Resulting span: [first non-whitespace char, EOD)
        ///
        /// Examples (pipes indicate span):
        /// #error |goo|
        /// #error  |goo|
        /// #error |goo |
        /// #error |goo baz|
        /// #error |//goo|
        /// #error |/*goo*/|
        /// #error |/*goo|
        /// </summary>
        /// <param name="hash">The '#' token.</param>
        /// <param name="keyword">The 'error' or 'warning' token.</param>
        /// <param name="isActive">True if the error/warning should be recorded.</param>
        /// <returns>An ErrorDirective or WarningDirective node.</returns>
        private DirectiveTriviaSyntax ParseErrorOrWarningDirective(SyntaxToken hash, SyntaxToken keyword, bool isActive)
        {
            var  eod     = this.ParseEndOfDirectiveWithOptionalPreprocessingMessage();
            bool isError = keyword.Kind == SyntaxKind.ErrorKeyword;

            if (isActive)
            {
                var triviaBuilder = new System.IO.StringWriter(System.Globalization.CultureInfo.InvariantCulture);
                int triviaWidth   = 0;

                // whitespace and single line comments are trailing trivia on the keyword, the rest
                // of the error message is leading trivia on the eod.
                //
                bool skipping = true;
                foreach (var t in keyword.TrailingTrivia)
                {
                    if (skipping)
                    {
                        if (t.Kind == SyntaxKind.WhitespaceTrivia)
                        {
                            continue;
                        }

                        skipping = false;
                    }

                    t.WriteTo(triviaBuilder, leading: true, trailing: true);
                    triviaWidth += t.FullWidth;
                }

                foreach (var node in eod.LeadingTrivia)
                {
                    node.WriteTo(triviaBuilder, leading: true, trailing: true);
                    triviaWidth += node.FullWidth;
                }

                //relative to leading trivia of eod
                //could be negative if part of the error text comes from the trailing trivia of the keyword token
                int triviaOffset = eod.GetLeadingTriviaWidth() - triviaWidth;

                string errorText = triviaBuilder.ToString();
                eod = this.AddError(eod, triviaOffset, triviaWidth, isError ? ErrorCode.ERR_ErrorDirective : ErrorCode.WRN_WarningDirective, errorText);

                if (isError)
                {
                    if (errorText.Equals("version", StringComparison.Ordinal))
                    {
                        Assembly assembly = typeof(CSharpCompiler).GetTypeInfo().Assembly;
                        string   version  = CommonCompiler.GetAssemblyFileVersion(assembly);
                        eod = this.AddError(eod, triviaOffset, triviaWidth, ErrorCode.ERR_CompilerAndLanguageVersion, version,
                                            this.Options.SpecifiedLanguageVersion.ToDisplayString());
                    }
                    else
                    {
                        const string versionMarker = "version:";
                        if (errorText.StartsWith(versionMarker, StringComparison.Ordinal) &&
                            LanguageVersionFacts.TryParse(errorText.Substring(versionMarker.Length), out var languageVersion))
                        {
                            ErrorCode error = this.Options.LanguageVersion.GetErrorCode();
                            eod = this.AddError(eod, triviaOffset, triviaWidth, error, "version", new CSharpRequiredLanguageVersion(languageVersion));
                        }
                    }
                }
            }

            if (isError)
            {
                return(SyntaxFactory.ErrorDirectiveTrivia(hash, keyword, eod, isActive));
            }
            else
            {
                return(SyntaxFactory.WarningDirectiveTrivia(hash, keyword, eod, isActive));
            }
        }
 public bool TryCreateCompiler(RunRequest request, out CommonCompiler compiler)
 {
     compiler = null;
     return(false);
 }
Exemple #28
0
 protected override bool TryGetCompilerDiagnosticCode(string diagnosticId, out uint code)
 {
     return(CommonCompiler.TryGetCompilerDiagnosticCode(diagnosticId, "CS", out code));
 }
Exemple #29
0
        internal override string GetExpectedOutputForSimpleCompilerDiagnostics(CommonCompiler cmd, string sourceFile)
        {
            var expectedHeader = GetExpectedErrorLogHeader(cmd);
            var expectedIssues = string.Format(@"
      ""results"": [
        {{
          ""ruleId"": ""CS5001"",
          ""level"": ""error"",
          ""message"": ""Program does not contain a static 'Main' method suitable for an entry point""
        }},
        {{
          ""ruleId"": ""CS0169"",
          ""level"": ""warning"",
          ""message"": ""The field 'C.x' is never used"",
          ""locations"": [
            {{
              ""resultFile"": {{
                ""uri"": ""{0}"",
                ""region"": {{
                  ""startLine"": 4,
                  ""startColumn"": 17,
                  ""endLine"": 4,
                  ""endColumn"": 18
                }}
              }}
            }}
          ],
          ""properties"": {{
            ""warningLevel"": 3
          }}
        }}
      ],
      ""rules"": {{
        ""CS0169"": {{
          ""id"": ""CS0169"",
          ""shortDescription"": ""Field is never used"",
          ""defaultLevel"": ""warning"",
          ""helpUri"": ""https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0169)"",
          ""properties"": {{
            ""category"": ""Compiler"",
            ""isEnabledByDefault"": true,
            ""tags"": [
              ""Compiler"",
              ""Telemetry""
            ]
          }}
        }},
        ""CS5001"": {{
          ""id"": ""CS5001"",
          ""defaultLevel"": ""error"",
          ""helpUri"": ""https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS5001)"",
          ""properties"": {{
            ""category"": ""Compiler"",
            ""isEnabledByDefault"": true,
            ""tags"": [
              ""Compiler"",
              ""Telemetry"",
              ""NotConfigurable""
            ]
          }}
        }}
      }}
    }}
  ]
}}", AnalyzerForErrorLogTest.GetUriForPath(sourceFile));

            return(expectedHeader + expectedIssues);
        }
Exemple #30
0
 internal abstract string GetExpectedOutputForNoDiagnostics(CommonCompiler cmd);
Exemple #31
0
 internal abstract string GetExpectedOutputForSimpleCompilerDiagnosticsSuppressed(CommonCompiler cmd, string sourceFile);
        internal override string GetExpectedOutputForSimpleCompilerDiagnostics(CommonCompiler cmd, string sourceFile)
        {
            string expectedOutput =
                @"{{
  ""$schema"": ""http://json.schemastore.org/sarif-2.1.0"",
  ""version"": ""2.1.0"",
  ""runs"": [
    {{
      ""results"": [
        {{
          ""ruleId"": ""CS5001"",
          ""ruleIndex"": 0,
          ""level"": ""error"",
          ""message"": {{
            ""text"": ""Program does not contain a static 'Main' method suitable for an entry point""
          }}
        }},
        {{
          ""ruleId"": ""CS0169"",
          ""ruleIndex"": 1,
          ""level"": ""warning"",
          ""message"": {{
            ""text"": ""The field 'C.x' is never used""
          }},
          ""locations"": [
            {{
              ""physicalLocation"": {{
                ""artifactLocation"": {{
                  ""uri"": ""{5}""
                }},
                ""region"": {{
                  ""startLine"": 4,
                  ""startColumn"": 17,
                  ""endLine"": 4,
                  ""endColumn"": 18
                }}
              }}
            }}
          ],
          ""properties"": {{
            ""warningLevel"": 3
          }}
        }}
      ],
      ""tool"": {{
        ""driver"": {{
          ""name"": ""{0}"",
          ""version"": ""{1}"",
          ""dottedQuadFileVersion"": ""{2}"",
          ""semanticVersion"": ""{3}"",
          ""language"": ""{4}"",
          ""rules"": [
            {{
              ""id"": ""CS5001"",
              ""defaultConfiguration"": {{
                ""level"": ""error""
              }},
              ""helpUri"": ""https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS5001)"",
              ""properties"": {{
                ""category"": ""Compiler"",
                ""tags"": [
                  ""Compiler"",
                  ""Telemetry"",
                  ""NotConfigurable""
                ]
              }}
            }},
            {{
              ""id"": ""CS0169"",
              ""shortDescription"": {{
                ""text"": ""Field is never used""
              }},
              ""helpUri"": ""https://msdn.microsoft.com/query/roslyn.query?appId=roslyn&k=k(CS0169)"",
              ""properties"": {{
                ""category"": ""Compiler"",
                ""tags"": [
                  ""Compiler"",
                  ""Telemetry""
                ]
              }}
            }}
          ]
        }}
      }},
      ""columnKind"": ""utf16CodeUnits""
    }}
  ]
}}";

            return(FormatOutputText(
                       expectedOutput,
                       cmd,
                       AnalyzerForErrorLogTest.GetUriForPath(sourceFile)));
        }
        private static void AppendAllLoadedSyntaxTrees(
            ArrayBuilder <SyntaxTree> treesBuilder,
            SyntaxTree tree,
            string scriptClassName,
            SourceReferenceResolver resolver,
            CommonMessageProvider messageProvider,
            bool isSubmission,
            IDictionary <SyntaxTree, int> ordinalMapBuilder,
            IDictionary <SyntaxTree, ImmutableArray <LoadDirective> > loadDirectiveMapBuilder,
            IDictionary <string, SyntaxTree> loadedSyntaxTreeMapBuilder,
            IDictionary <SyntaxTree, Lazy <RootSingleNamespaceDeclaration> > declMapBuilder,
            ref DeclarationTable declTable)
        {
            ArrayBuilder <LoadDirective> loadDirectives = null;

            foreach (var directive in tree.GetCompilationUnitRoot().GetLoadDirectives())
            {
                var fileToken = directive.File;
                var path      = (string)fileToken.Value;
                if (path == null)
                {
                    // If there is no path, the parser should have some Diagnostics to report (if we're in an active region).
                    Debug.Assert(!directive.IsActive || tree.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error));
                    continue;
                }

                var    diagnostics      = DiagnosticBag.GetInstance();
                string resolvedFilePath = null;
                if (resolver == null)
                {
                    diagnostics.Add(
                        messageProvider.CreateDiagnostic(
                            (int)ErrorCode.ERR_SourceFileReferencesNotSupported,
                            directive.Location));
                }
                else
                {
                    resolvedFilePath = resolver.ResolveReference(path, baseFilePath: tree.FilePath);
                    if (resolvedFilePath == null)
                    {
                        diagnostics.Add(
                            messageProvider.CreateDiagnostic(
                                (int)ErrorCode.ERR_NoSourceFile,
                                fileToken.GetLocation(),
                                path,
                                CSharpResources.CouldNotFindFile));
                    }
                    else if (!loadedSyntaxTreeMapBuilder.ContainsKey(resolvedFilePath))
                    {
                        try
                        {
                            var code       = resolver.ReadText(resolvedFilePath);
                            var loadedTree = SyntaxFactory.ParseSyntaxTree(
                                code,
                                tree.Options, // Use ParseOptions propagated from "external" tree.
                                resolvedFilePath);

                            // All #load'ed trees should have unique path information.
                            loadedSyntaxTreeMapBuilder.Add(loadedTree.FilePath, loadedTree);

                            AppendAllSyntaxTrees(
                                treesBuilder,
                                loadedTree,
                                scriptClassName,
                                resolver,
                                messageProvider,
                                isSubmission,
                                ordinalMapBuilder,
                                loadDirectiveMapBuilder,
                                loadedSyntaxTreeMapBuilder,
                                declMapBuilder,
                                ref declTable);
                        }
                        catch (Exception e)
                        {
                            diagnostics.Add(
                                CommonCompiler.ToFileReadDiagnostics(messageProvider, e, resolvedFilePath),
                                fileToken.GetLocation());
                        }
                    }
                    else
                    {
                        // The path resolved, but we've seen this file before,
                        // so don't attempt to load it again.
                        Debug.Assert(diagnostics.IsEmptyWithoutResolution);
                    }
                }

                if (loadDirectives == null)
                {
                    loadDirectives = ArrayBuilder <LoadDirective> .GetInstance();
                }
                loadDirectives.Add(new LoadDirective(resolvedFilePath, diagnostics.ToReadOnlyAndFree()));
            }

            if (loadDirectives != null)
            {
                loadDirectiveMapBuilder.Add(tree, loadDirectives.ToImmutableAndFree());
            }
        }