public void CompilationAnalyzerTest()
        {
            string           test     = @"
class C
{
    public void M()
    {
    }
}";
            DiagnosticResult expected = new DiagnosticResult
            {
                Id       = DiagnosticIds.CompilationAnalyzerRuleId,
                Message  = string.Format(CompilationAnalyzer.MessageFormat, DiagnosticIds.SymbolAnalyzerRuleId),
                Severity = DiagnosticSeverity.Warning
            };

            KeyValuePair <string, ReportDiagnostic> specificOption =
                new KeyValuePair <string, ReportDiagnostic>(DiagnosticIds.SymbolAnalyzerRuleId, ReportDiagnostic.Error);

            CSharpCompilationOptions compilationOptions =
                new CSharpCompilationOptions(OutputKind.ConsoleApplication,
                                             specificDiagnosticOptions: new[] { specificOption });

            VerifyCSharpDiagnostic(test, parseOptions: null, compilationOptions: compilationOptions);

            specificOption     = new KeyValuePair <string, ReportDiagnostic>(DiagnosticIds.SymbolAnalyzerRuleId, ReportDiagnostic.Suppress);
            compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(new[] { specificOption });
            VerifyCSharpDiagnostic(test, parseOptions: null, compilationOptions: compilationOptions, expected: expected);
        }
예제 #2
0
        /// <summary>
        /// Creates a solution that will be used as parent for the sources that need to be checked.
        /// </summary>
        /// <param name="projectId">The project identifier to use.</param>
        /// <param name="language">The language for which the solution is being created.</param>
        /// <returns>The created solution.</returns>
        protected virtual Solution CreateSolution(ProjectId projectId, string language)
        {
            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true);

            var additionalDiagnosticOptions = this.GetDisabledDiagnostics().Select(id => new KeyValuePair <string, ReportDiagnostic>(id, ReportDiagnostic.Suppress));
            var newSpecificOptions          = compilationOptions.SpecificDiagnosticOptions.AddRange(additionalDiagnosticOptions);

            compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(newSpecificOptions);

            Solution solution = new AdhocWorkspace()
                                .CurrentSolution
                                .AddProject(projectId, TestProjectName, TestProjectName, language)
                                .WithProjectCompilationOptions(projectId, compilationOptions)
                                .AddMetadataReference(projectId, CorlibReference)
                                .AddMetadataReference(projectId, SystemReference)
                                .AddMetadataReference(projectId, SystemCoreReference)
                                .AddMetadataReference(projectId, CSharpSymbolsReference)
                                .AddMetadataReference(projectId, CodeAnalysisReference);

            var settings = this.GetSettings();

            if (!string.IsNullOrEmpty(settings))
            {
                var documentId = DocumentId.CreateNewId(projectId);
                solution = solution.AddAdditionalDocument(documentId, SettingsFileName, settings);
            }

            ParseOptions parseOptions = solution.GetProject(projectId).ParseOptions;

            return(solution.WithProjectParseOptions(projectId, parseOptions.WithDocumentationMode(DocumentationMode.Diagnose)));
        }
예제 #3
0
        public static CSharpCompilationOptions CreateCompilationOptions(this ProjectFileInfo projectFileInfo)
        {
            var result = new CSharpCompilationOptions(projectFileInfo.OutputKind);

            result = result.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);

            if (projectFileInfo.AllowUnsafeCode)
            {
                result = result.WithAllowUnsafe(true);
            }

            result = result.WithSpecificDiagnosticOptions(CompilationOptionsHelper.GetDefaultSuppressedDiagnosticOptions(projectFileInfo.SuppressedDiagnosticIds));

            if (projectFileInfo.SignAssembly && !string.IsNullOrEmpty(projectFileInfo.AssemblyOriginatorKeyFile))
            {
                var keyFile = Path.Combine(projectFileInfo.Directory, projectFileInfo.AssemblyOriginatorKeyFile);
                result = result.WithStrongNameProvider(new DesktopStrongNameProvider())
                         .WithCryptoKeyFile(keyFile);
            }

            if (!string.IsNullOrWhiteSpace(projectFileInfo.DocumentationFile))
            {
                result = result.WithXmlReferenceResolver(XmlFileResolver.Default);
            }

            return(result);
        }
        public void Test1()
        {
            var test = @"
class C
{
    public void M()
    {
    }
}";
            var expected = new DiagnosticResult
            {
                Id = DiagnosticIds.CompilationAnalyzerRuleId,
                Message = string.Format(Resources.CompilationAnalyzerMessageFormat, DiagnosticIds.SymbolAnalyzerRuleId),
                Severity = DiagnosticSeverity.Warning
            };

            var specificOption = new KeyValuePair<string, ReportDiagnostic>(DiagnosticIds.SymbolAnalyzerRuleId, ReportDiagnostic.Error);

            var compilationOptions = new CSharpCompilationOptions(OutputKind.ConsoleApplication,
                specificDiagnosticOptions: new[]{ specificOption });
            VerifyCSharpDiagnostic(test, parseOptions: null, compilationOptions: compilationOptions);

            specificOption = new KeyValuePair<string, ReportDiagnostic>(DiagnosticIds.SymbolAnalyzerRuleId, ReportDiagnostic.Suppress);
            compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(new[] { specificOption });
            VerifyCSharpDiagnostic(test, parseOptions: null, compilationOptions: compilationOptions, expected: expected);
        }
예제 #5
0
 public static CSharpCompilationOptions WithSpecificDiagnosticOptions(
     this CSharpCompilationOptions options,
     string key,
     ReportDiagnostic value
     )
 {
     return(options.WithSpecificDiagnosticOptions(
                ImmutableDictionary <string, ReportDiagnostic> .Empty.Add(key, value)
                ));
 }
예제 #6
0
    protected virtual CSharpCompilationOptions GetCompilationOptions()
    {
        var csharpCompilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

        // Disable 1702 until roslyn turns this off by default
        csharpCompilationOptions = csharpCompilationOptions.WithSpecificDiagnosticOptions(
            new Dictionary <string, ReportDiagnostic>
        {
            { "CS1701", ReportDiagnostic.Suppress },       // Binding redirects
            { "CS1702", ReportDiagnostic.Suppress },
            { "CS1705", ReportDiagnostic.Suppress }
        });

        return(csharpCompilationOptions.WithOptimizationLevel(OptimizationLevel.Release));
    }
예제 #7
0
        private static CSharpCompilationOptions GetCompilationOptions(
            IWebHostEnvironment hostingEnvironment,
            DependencyContextCompilationOptions dependencyContextOptions)
        {
            var csharpCompilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            // Disable 1702 until roslyn turns this off by default
            csharpCompilationOptions = csharpCompilationOptions.WithSpecificDiagnosticOptions(
                new Dictionary <string, ReportDiagnostic>
            {
                { "CS1701", ReportDiagnostic.Suppress },   // Binding redirects
                { "CS1702", ReportDiagnostic.Suppress },
                { "CS1705", ReportDiagnostic.Suppress }
            });

            if (dependencyContextOptions.AllowUnsafe.HasValue)
            {
                csharpCompilationOptions = csharpCompilationOptions.WithAllowUnsafe(
                    dependencyContextOptions.AllowUnsafe.Value);
            }

            OptimizationLevel optimizationLevel;

            if (dependencyContextOptions.Optimize.HasValue)
            {
                optimizationLevel = dependencyContextOptions.Optimize.Value ?
                                    OptimizationLevel.Release :
                                    OptimizationLevel.Debug;
            }
            else
            {
                optimizationLevel = hostingEnvironment.IsDevelopment() ?
                                    OptimizationLevel.Debug :
                                    OptimizationLevel.Release;
            }
            csharpCompilationOptions = csharpCompilationOptions.WithOptimizationLevel(optimizationLevel);

            if (dependencyContextOptions.WarningsAsErrors.HasValue)
            {
                var reportDiagnostic = dependencyContextOptions.WarningsAsErrors.Value ?
                                       ReportDiagnostic.Error :
                                       ReportDiagnostic.Default;
                csharpCompilationOptions = csharpCompilationOptions.WithGeneralDiagnosticOption(reportDiagnostic);
            }

            return(csharpCompilationOptions);
        }
예제 #8
0
        private static CSharpCompilationOptions CreateCompilationOptions(ProjectFileInfo projectFileInfo)
        {
            var result = new CSharpCompilationOptions(projectFileInfo.OutputKind);

            result = result.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);

            if (projectFileInfo.AllowUnsafeCode)
            {
                result = result.WithAllowUnsafe(true);
            }

            var specificDiagnosticOptions = new Dictionary <string, ReportDiagnostic>(projectFileInfo.SuppressedDiagnosticIds.Count)
            {
                // Ensure that specific warnings about assembly references are always suppressed.
                { "CS1701", ReportDiagnostic.Suppress },
                { "CS1702", ReportDiagnostic.Suppress },
                { "CS1705", ReportDiagnostic.Suppress }
            };

            if (projectFileInfo.SuppressedDiagnosticIds.Any())
            {
                foreach (var id in projectFileInfo.SuppressedDiagnosticIds)
                {
                    if (!specificDiagnosticOptions.ContainsKey(id))
                    {
                        specificDiagnosticOptions.Add(id, ReportDiagnostic.Suppress);
                    }
                }
            }

            result = result.WithSpecificDiagnosticOptions(specificDiagnosticOptions);

            if (projectFileInfo.SignAssembly && !string.IsNullOrEmpty(projectFileInfo.AssemblyOriginatorKeyFile))
            {
                var keyFile = Path.Combine(projectFileInfo.Directory, projectFileInfo.AssemblyOriginatorKeyFile);
                result = result.WithStrongNameProvider(new DesktopStrongNameProvider())
                         .WithCryptoKeyFile(keyFile);
            }

            if (!string.IsNullOrWhiteSpace(projectFileInfo.DocumentationFile))
            {
                result = result.WithXmlReferenceResolver(XmlFileResolver.Default);
            }

            return(result);
        }
예제 #9
0
        private static IEnumerable<Diagnostic> GetDiagnostics(Compilation compilation,
            DiagnosticAnalyzer diagnosticAnalyzer)
        {
            using (var tokenSource = new CancellationTokenSource())
            {
                var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
                compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(
                    diagnosticAnalyzer.SupportedDiagnostics
                        .Select(diagnostic =>
                            new KeyValuePair<string, ReportDiagnostic>(diagnostic.Id, ReportDiagnostic.Warn)));

                var compilationWithOptions = compilation.WithOptions(compilationOptions);
                var compilationWithAnalyzer = compilationWithOptions
                    .WithAnalyzers(ImmutableArray.Create(diagnosticAnalyzer), null, tokenSource.Token);

                return compilationWithAnalyzer.GetAnalyzerDiagnosticsAsync().Result;
            }
        }
예제 #10
0
        internal static IEnumerable <Diagnostic> GetDiagnostics(Compilation compilation,
                                                                DiagnosticAnalyzer diagnosticAnalyzer)
        {
            using (var tokenSource = new CancellationTokenSource())
            {
                var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
                compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(
                    diagnosticAnalyzer.SupportedDiagnostics
                    .Select(diagnostic =>
                            new KeyValuePair <string, ReportDiagnostic>(diagnostic.Id, ReportDiagnostic.Warn)));

                var compilationWithOptions  = compilation.WithOptions(compilationOptions);
                var compilationWithAnalyzer = compilationWithOptions
                                              .WithAnalyzers(ImmutableArray.Create(diagnosticAnalyzer), null, tokenSource.Token);

                return(compilationWithAnalyzer.GetAnalyzerDiagnosticsAsync().Result
                       .Where(diag => diag.Id == diagnosticAnalyzer.SupportedDiagnostics.Single().Id));
            }
        }
예제 #11
0
        public IEnumerable<Diagnostic> GetDiagnostics(Compilation compilation)
        {
            if (diagnosticAnalyzers.IsDefaultOrEmpty)
            {
                return new Diagnostic[0];
            }

            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);
            compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(
                diagnosticAnalyzers.SelectMany(analyzer => analyzer.SupportedDiagnostics)
                    .Select(diagnostic =>
                        new KeyValuePair<string, ReportDiagnostic>(diagnostic.Id, ReportDiagnostic.Warn)));

            var modifiedCompilation = compilation.WithOptions(compilationOptions);

            using (var tokenSource = new CancellationTokenSource())
            {
                var compilationWithAnalyzer = modifiedCompilation.WithAnalyzers(diagnosticAnalyzers, null,
                    tokenSource.Token);

                return compilationWithAnalyzer.GetAnalyzerDiagnosticsAsync().Result;
            }
        }
        public static CSharpCompilationOptions CreateCompilationOptions(this ProjectFileInfo projectFileInfo)
        {
            var compilationOptions = new CSharpCompilationOptions(projectFileInfo.OutputKind);

            compilationOptions = compilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);

            if (projectFileInfo.AllowUnsafeCode)
            {
                compilationOptions = compilationOptions.WithAllowUnsafe(true).WithGeneralDiagnosticOption(ReportDiagnostic.Error);
            }

            if (projectFileInfo.TreatWarningsAsErrors)
            {
                compilationOptions = compilationOptions.WithGeneralDiagnosticOption(ReportDiagnostic.Error);
            }

            if (projectFileInfo.NullableContextOptions != compilationOptions.NullableContextOptions)
            {
                compilationOptions = compilationOptions.WithNullableContextOptions(projectFileInfo.NullableContextOptions);
            }

            compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(CompilationOptionsHelper.GetDefaultSuppressedDiagnosticOptions(projectFileInfo.SuppressedDiagnosticIds));

            if (projectFileInfo.SignAssembly && !string.IsNullOrEmpty(projectFileInfo.AssemblyOriginatorKeyFile))
            {
                var keyFile = Path.Combine(projectFileInfo.Directory, projectFileInfo.AssemblyOriginatorKeyFile);
                compilationOptions = compilationOptions.WithStrongNameProvider(new DesktopStrongNameProvider())
                                     .WithCryptoKeyFile(keyFile);
            }

            if (!string.IsNullOrWhiteSpace(projectFileInfo.DocumentationFile))
            {
                compilationOptions = compilationOptions.WithXmlReferenceResolver(XmlFileResolver.Default);
            }

            return(compilationOptions);
        }
예제 #13
0
        public IEnumerable <Diagnostic> GetDiagnostics(Compilation compilation)
        {
            if (diagnosticAnalyzers.IsDefaultOrEmpty)
            {
                return(new Diagnostic[0]);
            }

            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

            compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(
                diagnosticAnalyzers.SelectMany(analyzer => analyzer.SupportedDiagnostics)
                .Select(diagnostic =>
                        new KeyValuePair <string, ReportDiagnostic>(diagnostic.Id, ReportDiagnostic.Warn)));

            var modifiedCompilation = compilation.WithOptions(compilationOptions);

            using (var tokenSource = new CancellationTokenSource())
            {
                var compilationWithAnalyzer = modifiedCompilation.WithAnalyzers(diagnosticAnalyzers, null,
                                                                                tokenSource.Token);

                return(compilationWithAnalyzer.GetAnalyzerDiagnosticsAsync().Result);
            }
        }
예제 #14
0
        protected async Task <Diagnostic[]> GetSortedDiagnosticsFromDocumentsAsync(AnalyzerVerificationContext context, DiagnosticAnalyzer analyzer, Document[] documents, params DiagnosticResult[] expected)
        {
            var projects = new HashSet <Project>();

            foreach (var document in documents)
            {
                projects.Add(document.Project);
            }

            var diagnostics = new List <Diagnostic>();

            foreach (var project in projects)
            {
                var analyzers = ImmutableArray.Create(analyzer)
                                .AddRange(GetRelatedAnalyzers(analyzer));

                var compilation = await project.GetCompilationAsync();

                Assert.NotNull(compilation);

                var optionsProvider = new AnalyzerOptionsProvider(context.Options);
                var options         = new AnalyzerOptions(ImmutableArray <AdditionalText> .Empty, optionsProvider);
                var analyzerOptions = new CompilationWithAnalyzersOptions(options, null, true, true, true);

                var compilationOptions        = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, reportSuppressedDiagnostics: true);
                var specificDiagnosticOptions = compilationOptions.SpecificDiagnosticOptions;

                // Force all tested diagnostics to be enabled
                foreach (var descriptor in analyzer.SupportedDiagnostics)
                {
                    specificDiagnosticOptions = specificDiagnosticOptions.SetItem(descriptor.Id, ReportDiagnostic.Info);
                }

                var compilationWithAnalyzers = compilation
                                               .WithOptions(compilationOptions.WithSpecificDiagnosticOptions(specificDiagnosticOptions))
                                               .WithAnalyzers(analyzers, analyzerOptions);

                var allDiagnostics = await compilationWithAnalyzers.GetAllDiagnosticsAsync();

                var errors = allDiagnostics.Where(d => d.Severity == DiagnosticSeverity.Error).ToList();
                foreach (var error in errors)
                {
                    Assert.True(false, $"Line {error.Location.GetLineSpan().StartLinePosition.Line}: {error.GetMessage()}");
                }

                var diags = allDiagnostics
                            .Except(errors)
                            .Where(d => d.Location.IsInSource);             //only keep diagnostics related to a source location

                foreach (var diag in diags)
                {
                    // We should not hit this anymore, but keep in case we change the previous filter
                    if (diag.Location == Location.None || diag.Location.IsInMetadata)
                    {
                        diagnostics.Add(diag);
                    }
                    else
                    {
                        foreach (var document in documents)
                        {
                            var tree = await document.GetSyntaxTreeAsync();

                            if (tree == diag.Location.SourceTree)
                            {
                                diagnostics.Add(diag);
                            }
                        }
                    }
                }
            }

            var results = SortDiagnostics(FilterDiagnostics(diagnostics, context.Filters));

            diagnostics.Clear();
            return(results);
        }
예제 #15
0
        public HostBuildData Create(HostBuildOptions options)
        {
            var parseOptions = new CSharpParseOptions(languageVersion: LanguageVersion.CSharp6, documentationMode: DocumentationMode.Parse);
            var compilationOptions = new CSharpCompilationOptions(
                OutputKind.ConsoleApplication,
                xmlReferenceResolver: new XmlFileResolver(options.ProjectDirectory),
                sourceReferenceResolver: new SourceFileResolver(ImmutableArray<string>.Empty, options.ProjectDirectory),
                metadataReferenceResolver: new AssemblyReferenceResolver(
                    new MetadataFileReferenceResolver(ImmutableArray<string>.Empty, options.ProjectDirectory),
                    MetadataFileReferenceProvider.Default),
                strongNameProvider: new DesktopStrongNameProvider(ImmutableArray.Create(options.ProjectDirectory, options.OutputDirectory)),
                assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default);
            var warnings = new List<KeyValuePair<string, ReportDiagnostic>>(options.Warnings);

            if (options.OutputKind.HasValue)
            {
                var kind = options.OutputKind.Value;
                compilationOptions = compilationOptions.WithOutputKind(kind);
                if (compilationOptions.Platform == Platform.AnyCpu32BitPreferred &&
                    (kind == OutputKind.DynamicallyLinkedLibrary || kind == OutputKind.NetModule || kind == OutputKind.WindowsRuntimeMetadata))
                {
                    compilationOptions = compilationOptions.WithPlatform(Platform.AnyCpu);
                }
            }

            if (!string.IsNullOrEmpty(options.DefineConstants))
            {
                IEnumerable<Diagnostic> diagnostics;
                parseOptions = parseOptions.WithPreprocessorSymbols(CSharpCommandLineParser.ParseConditionalCompilationSymbols(options.DefineConstants, out diagnostics));
            }

            if (options.DocumentationFile != null)
            {
                parseOptions = parseOptions.WithDocumentationMode(!string.IsNullOrEmpty(options.DocumentationFile) ? DocumentationMode.Diagnose : DocumentationMode.Parse);
            }

            if (options.LanguageVersion != null)
            {
                var languageVersion = CompilationOptionsConversion.GetLanguageVersion(options.LanguageVersion);
                if (languageVersion.HasValue)
                {
                    parseOptions = parseOptions.WithLanguageVersion(languageVersion.Value);
                }
            }

            if (!string.IsNullOrEmpty(options.PlatformWith32BitPreference))
            {
                Platform platform;
                if (Enum.TryParse<Platform>(options.PlatformWith32BitPreference, true, out platform))
                {
                    if (platform == Platform.AnyCpu &&
                        compilationOptions.OutputKind != OutputKind.DynamicallyLinkedLibrary &&
                        compilationOptions.OutputKind != OutputKind.NetModule &&
                        compilationOptions.OutputKind != OutputKind.WindowsRuntimeMetadata)
                    {
                        platform = Platform.AnyCpu32BitPreferred;
                    }

                    compilationOptions = compilationOptions.WithPlatform(platform);
                }
            }

            if (options.AllowUnsafeBlocks.HasValue)
            {
                compilationOptions = compilationOptions.WithAllowUnsafe(options.AllowUnsafeBlocks.Value);
            }

            if (options.CheckForOverflowUnderflow.HasValue)
            {
                compilationOptions = compilationOptions.WithOverflowChecks(options.CheckForOverflowUnderflow.Value);
            }

            if (options.DelaySign != null)
            {
                bool delaySignExplicitlySet = options.DelaySign.Item1;
                bool delaySign = options.DelaySign.Item2;
                compilationOptions = compilationOptions.WithDelaySign(delaySignExplicitlySet ? delaySign : (bool?)null);
            }

            if (!string.IsNullOrEmpty(options.ApplicationConfiguration))
            {
                var appConfigPath = FileUtilities.ResolveRelativePath(options.ApplicationConfiguration, options.ProjectDirectory);
                try
                {
                    using (var appConfigStream = PortableShim.FileStream.Create(appConfigPath, PortableShim.FileMode.Open, PortableShim.FileAccess.Read))
                    {
                        compilationOptions = compilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.LoadFromXml(appConfigStream));
                    }
                }
                catch (Exception)
                {
                }
            }

            if (!string.IsNullOrEmpty(options.KeyContainer))
            {
                compilationOptions = compilationOptions.WithCryptoKeyContainer(options.KeyContainer);
            }

            if (!string.IsNullOrEmpty(options.KeyFile))
            {
                var fullPath = FileUtilities.ResolveRelativePath(options.KeyFile, options.ProjectDirectory);
                compilationOptions = compilationOptions.WithCryptoKeyFile(fullPath);
            }

            if (!string.IsNullOrEmpty(options.MainEntryPoint))
            {
                compilationOptions = compilationOptions.WithMainTypeName(options.MainEntryPoint);
            }

            if (!string.IsNullOrEmpty(options.ModuleAssemblyName))
            {
                compilationOptions = compilationOptions.WithModuleName(options.ModuleAssemblyName);
            }

            if (options.Optimize.HasValue)
            {
                compilationOptions = compilationOptions.WithOptimizationLevel(options.Optimize.Value ? OptimizationLevel.Release : OptimizationLevel.Debug);
            }

            if (!string.IsNullOrEmpty(options.Platform))
            {
                Platform plat;
                if (Enum.TryParse<Platform>(options.Platform, ignoreCase: true, result: out plat))
                {
                    compilationOptions = compilationOptions.WithPlatform(plat);
                }
            }

            // Get options from the ruleset file, if any.
            if (!string.IsNullOrEmpty(options.RuleSetFile))
            {
                var fullPath = FileUtilities.ResolveRelativePath(options.RuleSetFile, options.ProjectDirectory);

                Dictionary<string, ReportDiagnostic> specificDiagnosticOptions;
                var generalDiagnosticOption = RuleSet.GetDiagnosticOptionsFromRulesetFile(fullPath, out specificDiagnosticOptions);
                compilationOptions = compilationOptions.WithGeneralDiagnosticOption(generalDiagnosticOption);
                warnings.AddRange(specificDiagnosticOptions);
            }

            if (options.WarningsAsErrors.HasValue)
            {
                compilationOptions = compilationOptions.WithGeneralDiagnosticOption(options.WarningsAsErrors.Value ? ReportDiagnostic.Error : ReportDiagnostic.Default);
            }

            if (options.WarningLevel.HasValue)
            {
                compilationOptions = compilationOptions.WithWarningLevel(options.WarningLevel.Value);
            }

            compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(warnings);
            return new HostBuildData(
                parseOptions,
                compilationOptions);
        }
        /// <summary>
        /// Creates a solution that will be used as parent for the sources that need to be checked.
        /// </summary>
        /// <param name="projectId">The project identifier to use.</param>
        /// <param name="language">The language for which the solution is being created.</param>
        /// <returns>The created solution.</returns>
        protected virtual Solution CreateSolution(ProjectId projectId, string language)
        {
            var compilationOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary, allowUnsafe: true);

            var additionalDiagnosticOptions = this.GetDisabledDiagnostics().Select(id => new KeyValuePair<string, ReportDiagnostic>(id, ReportDiagnostic.Suppress));
            var newSpecificOptions = compilationOptions.SpecificDiagnosticOptions.AddRange(additionalDiagnosticOptions);
            compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(newSpecificOptions);

            Solution solution = new AdhocWorkspace()
                .CurrentSolution
                .AddProject(projectId, TestProjectName, TestProjectName, language)
                .WithProjectCompilationOptions(projectId, compilationOptions)
                .AddMetadataReference(projectId, MetadataReferences.CorlibReference)
                .AddMetadataReference(projectId, MetadataReferences.SystemReference)
                .AddMetadataReference(projectId, MetadataReferences.SystemCoreReference)
                .AddMetadataReference(projectId, MetadataReferences.CSharpSymbolsReference)
                .AddMetadataReference(projectId, MetadataReferences.CodeAnalysisReference);

            var settings = this.GetSettings();
            if (!string.IsNullOrEmpty(settings))
            {
                var documentId = DocumentId.CreateNewId(projectId);
                solution = solution.AddAdditionalDocument(documentId, SettingsFileName, settings);
            }

            ParseOptions parseOptions = solution.GetProject(projectId).ParseOptions;
            return solution.WithProjectParseOptions(projectId, parseOptions.WithDocumentationMode(DocumentationMode.Diagnose));
        }
예제 #17
0
        private static (string outputFile, CSharpCompilationOptions compilationOptions, CSharpParseOptions parseOptions) ParseArguments(IEnumerable <string> args)
        {
            var arguments = new Dictionary <string, string>();

            var compilationOptions = new CSharpCompilationOptions(OutputKind.ConsoleApplication);

            compilationOptions = compilationOptions.WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default);
            string outputFile = "";

            var specificDiagnosticOptions = new Dictionary <string, ReportDiagnostic>()
            {
                // Ensure that specific warnings about assembly references are always suppressed.
                { "CS1701", ReportDiagnostic.Suppress },
                { "CS1702", ReportDiagnostic.Suppress },
                { "CS1705", ReportDiagnostic.Suppress }
            };

            compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(specificDiagnosticOptions);

            var parseOptions = new CSharpParseOptions();

            foreach (var arg in args)
            {
                var argParts = arg.Split(':');

                var argument = argParts[0].Replace("+", "").Replace("/", "");
                var value    = "";

                if (argParts.Count() > 1)
                {
                    value = argParts[1];
                }

                switch (argument)
                {
                case "target":
                    compilationOptions = compilationOptions.WithOutputKind(ParseTarget(value));
                    break;

                case "unsafe":
                    compilationOptions = compilationOptions.WithAllowUnsafe(true);
                    break;

                case "nowarn":
                    var warnings = value.Split(',');

                    if (warnings.Count() > 0)
                    {
                        compilationOptions = compilationOptions.WithSpecificDiagnosticOptions(warnings.Select(s => new KeyValuePair <string, ReportDiagnostic>(!s.StartsWith("CS") ? $"CS{s}" : s, ReportDiagnostic.Suppress)));
                    }
                    break;

                case "define":
                    var defines = value.Split(';');

                    if (defines.Count() > 0)
                    {
                        parseOptions = parseOptions.WithPreprocessorSymbols(defines);
                    }
                    break;

                case "optimize":
                    compilationOptions = compilationOptions.WithOptimizationLevel(OptimizationLevel.Release);
                    break;

                case "platform":
                    compilationOptions = compilationOptions.WithPlatform(ParsePlatform(value));
                    break;

                case "out":
                    outputFile = value;
                    break;
                }
            }

            return(outputFile, compilationOptions, parseOptions);
        }