Beispiel #1
0
        /// <summary>
        /// Create a RuleSet with a global effective action applied on it.
        /// </summary>
        public RuleSet WithEffectiveAction(ReportDiagnostic action)
        {
            if (!_includes.IsEmpty)
            {
                throw new ArgumentException("Effective action cannot be applied to rulesets with Includes");
            }

            switch (action)
            {
                case ReportDiagnostic.Default:
                    return this;
                case ReportDiagnostic.Suppress:
                    return null;
                case ReportDiagnostic.Error:
                case ReportDiagnostic.Warn:
                case ReportDiagnostic.Info:
                case ReportDiagnostic.Hidden:
                    var generalOption = _generalDiagnosticOption == ReportDiagnostic.Default ? ReportDiagnostic.Default : action;
                    var specificOptions = _specificDiagnosticOptions.ToBuilder();
                    foreach (var item in _specificDiagnosticOptions)
                    {
                        if (item.Value != ReportDiagnostic.Suppress && item.Value != ReportDiagnostic.Default)
                        {
                            specificOptions[item.Key] = action;
                        }
                    }
                    return new RuleSet(FilePath, generalOption, specificOptions.ToImmutable(), _includes);
                default:
                    return null;
            }
        }
Beispiel #2
0
 public DiagnosticItem(AnalyzerItem analyzerItem, DiagnosticDescriptor descriptor, ReportDiagnostic effectiveSeverity)
     : base(string.Format("{0}: {1}", descriptor.Id, descriptor.Title))
 {
     _analyzerItem = analyzerItem;
     _descriptor = descriptor;
     _effectiveSeverity = effectiveSeverity;
 }
Beispiel #3
0
 /// <summary>
 /// Create a RuleSet.
 /// </summary>
 public RuleSet(string filePath, ReportDiagnostic generalOption, ImmutableDictionary<string, ReportDiagnostic> specificOptions, ImmutableArray<RuleSetInclude> includes)
 {
     _filePath = filePath;
     _generalDiagnosticOption = generalOption;
     _specificDiagnosticOptions = specificOptions == null ? ImmutableDictionary<string, ReportDiagnostic>.Empty : specificOptions;
     _includes = includes.IsDefault ? ImmutableArray<RuleSetInclude>.Empty : includes;
 }
Beispiel #4
0
 /// <summary>
 /// Create a RuleSet.
 /// </summary>
 public RuleSet(string filePath, ReportDiagnostic generalOption, IDictionary<string, ReportDiagnostic> specificOptions, IEnumerable<RuleSetInclude> includes)
 {
     this.filePath = filePath;
     this.generalDiagnosticOption = generalOption;
     this.specificDiagnosticOptions = specificOptions == null ? ImmutableDictionary<string, ReportDiagnostic>.Empty : specificOptions.ToImmutableDictionary();
     this.includes = includes == null ? ImmutableArray<RuleSetInclude>.Empty : includes.ToImmutableArray();
 }
        // Take a warning and return the final deposition of the given warning,
        // based on both command line options and pragmas.
        // If you update this method, also update DiagnosticItemSource.GetEffectiveSeverity. 
        internal static ReportDiagnostic GetDiagnosticReport(DiagnosticSeverity severity, bool isEnabledByDefault, string id, int diagnosticWarningLevel, Location location, string category, int warningLevelOption, ReportDiagnostic generalDiagnosticOption, IDictionary<string, ReportDiagnostic> specificDiagnosticOptions)
        {
            // Read options (e.g., /nowarn or /warnaserror)
            ReportDiagnostic report = ReportDiagnostic.Default;
            var isSpecified = specificDiagnosticOptions.TryGetValue(id, out report);
            if (!isSpecified)
            {
                report = isEnabledByDefault ? ReportDiagnostic.Default : ReportDiagnostic.Suppress;
            }

            // Compute if the reporting should be suppressed.
            if (diagnosticWarningLevel > warningLevelOption  // honor the warning level
                || report == ReportDiagnostic.Suppress)                // check options (/nowarn)
            {
                return ReportDiagnostic.Suppress;
            }

            // If location is available, check out pragmas
            if (location != null &&
                location.SourceTree != null &&
                ((SyntaxTree)location.SourceTree).GetPragmaDirectiveWarningState(id, location.SourceSpan.Start) == ReportDiagnostic.Suppress)
            {
                return ReportDiagnostic.Suppress;
            }

            // Unless specific warning options are defined (/warnaserror[+|-]:<n> or /nowarn:<n>, 
            // follow the global option (/warnaserror[+|-] or /nowarn).
            if (report == ReportDiagnostic.Default)
            {
                switch (generalDiagnosticOption)
                {
                    case ReportDiagnostic.Error:
                        // If we've been asked to do warn-as-error then don't raise severity for anything below warning (info or hidden).
                        if (severity == DiagnosticSeverity.Warning)
                        {
                            // In the case where /warnaserror+ is followed by /warnaserror-:<n> on the command line,
                            // do not promote the warning specified in <n> to an error.
                            if (!isSpecified && (report == ReportDiagnostic.Default))
                            {
                                return ReportDiagnostic.Error;
                            }
                        }
                        break;
                    case ReportDiagnostic.Suppress:
                        // When doing suppress-all-warnings, don't lower severity for anything other than warning and info.
                        // We shouldn't suppress hidden diagnostics here because then features that use hidden diagnostics to
                        // display a lightbulb would stop working if someone has suppress-all-warnings (/nowarn) specified in their project.
                        if (severity == DiagnosticSeverity.Warning || severity == DiagnosticSeverity.Info)
                        {
                            return ReportDiagnostic.Suppress;
                        }
                        break;
                    default:
                        break;
                }
            }

            return report;
        }
Beispiel #6
0
 public DiagnosticItem(AnalyzerItem analyzerItem, DiagnosticDescriptor descriptor, ReportDiagnostic effectiveSeverity, IContextMenuController contextMenuController)
     : base(string.Format("{0}: {1}", descriptor.Id, descriptor.Title))
 {
     _analyzerItem = analyzerItem;
     _descriptor = descriptor;
     _effectiveSeverity = effectiveSeverity;
     _contextMenuController = contextMenuController;
 }
        internal void UpdateEffectiveSeverity(ReportDiagnostic newEffectiveSeverity)
        {
            if (_effectiveSeverity != newEffectiveSeverity)
            {
                _effectiveSeverity = newEffectiveSeverity;

                NotifyPropertyChanged(nameof(EffectiveSeverity));
                NotifyPropertyChanged(nameof(IconMoniker));
            }
        }
        /// <summary>
        /// Modifies an input <see cref="Diagnostic"/> per the given options. For example, the
        /// severity may be escalated, or the <see cref="Diagnostic"/> may be filtered out entirely
        /// (by returning null).
        /// </summary>
        /// <param name="d">The input diagnostic</param>
        /// <param name="warningLevelOption">The maximum warning level to allow. Diagnostics with a higher warning level will be filtered out.</param>
        /// <param name="generalDiagnosticOption">How warning diagnostics should be reported</param>
        /// <param name="specificDiagnosticOptions">How specific diagnostics should be reported</param>
        /// <returns>A diagnostic updated to reflect the options, or null if it has been filtered out</returns>
        public static Diagnostic Filter(Diagnostic d, int warningLevelOption, ReportDiagnostic generalDiagnosticOption, IDictionary<string, ReportDiagnostic> specificDiagnosticOptions)
        {
            if (d == null)
            {
                return d;
            }
            else if (d.IsNotConfigurable())
            {
                if (d.IsEnabledByDefault)
                {
                    // Enabled NotConfigurable should always be reported as it is.
                    return d;
                }
                else
                {
                    // Disabled NotConfigurable should never be reported.
                    return null;
                }
            }
            else if (d.Severity == InternalDiagnosticSeverity.Void)
            {
                return null;
            }

            //In the native compiler, all warnings originating from alink.dll were issued
            //under the id WRN_ALinkWarn - 1607. If a customer used nowarn:1607 they would get
            //none of those warnings. In Roslyn, we've given each of these warnings their
            //own number, so that they may be configured independently. To preserve compatibility
            //if a user has specifically configured 1607 and we are reporting one of the alink warnings, use
            //the configuration specified for 1607. As implemented, this could result in customers 
            //specifying warnaserror:1607 and getting a message saying "warning as error CS8012..."
            //We don't permit configuring 1607 and independently configuring the new warnings.
            ReportDiagnostic reportAction;
            if (s_alinkWarnings.Contains((ErrorCode)d.Code) &&
                specificDiagnosticOptions.Keys.Contains(CSharp.MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ALinkWarn)))
            {
                reportAction = GetDiagnosticReport(ErrorFacts.GetSeverity(ErrorCode.WRN_ALinkWarn),
                    d.IsEnabledByDefault,
                    CSharp.MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ALinkWarn),
                    ErrorFacts.GetWarningLevel(ErrorCode.WRN_ALinkWarn),
                    d.Location as Location,
                    d.Category,
                    warningLevelOption,
                    generalDiagnosticOption,
                    specificDiagnosticOptions);
            }
            else
            {
                reportAction = GetDiagnosticReport(d.Severity, d.IsEnabledByDefault, d.Id, d.WarningLevel, d.Location as Location, d.Category, warningLevelOption, generalDiagnosticOption, specificDiagnosticOptions);
            }

            return d.WithReportDiagnostic(reportAction);
        }
        /// <summary>
        /// Modifies an input <see cref="Diagnostic"/> per the given options. For example, the
        /// severity may be escalated, or the <see cref="Diagnostic"/> may be filtered out entirely
        /// (by returning null).
        /// </summary>
        /// <param name="d">The input diagnostic</param>
        /// <param name="warningLevelOption">The maximum warning level to allow. Diagnostics with a higher warning level will be filtered out.</param>
        /// <param name="generalDiagnosticOption">How warning diagnostics should be reported</param>
        /// <param name="specificDiagnosticOptions">How specific diagnostics should be reported</param>
        /// <returns>A diagnostic updated to reflect the options, or null if it has been filtered out</returns>
        public static Diagnostic Filter(Diagnostic d, int warningLevelOption, ReportDiagnostic generalDiagnosticOption, IDictionary<string, ReportDiagnostic> specificDiagnosticOptions)
        {
            if (d == null) return d;
            switch (d.Severity)
            {
                case DiagnosticSeverity.Error:
                    // If it is a compiler error, keep it as it is.
                    // TODO: We currently use .Category to detect whether the diagnostic is a compiler diagnostic.
                    // Perhaps there should be a stronger way of checking this that avoids the possibility of an
                    // inadvertent clash for some custom diagnostic that happens to use the same category string.
                    if (d.Category == Diagnostic.CompilerDiagnosticCategory)
                    {
                        return d;
                    }
                    break;
                case InternalDiagnosticSeverity.Void:
                    return null;
                default:
                    break;
            }

            //In the native compiler, all warnings originating from alink.dll were issued
            //under the id WRN_ALinkWarn - 1607. If a customer used nowarn:1607 they would get
            //none of those warnings. In Roslyn, we've given each of these warnings their
            //own number, so that they may be configured independently. To preserve compatibility
            //if a user has specifically configured 1607 and we are reporting one of the alink warnings, use
            //the configuration specified for 1607. As implemented, this could result in customers 
            //specifying warnaserror:1607 and getting a message saying "warning as error CS8012..."
            //We don't permit configuring 1607 and independently configuring the new warnings.
            ReportDiagnostic reportAction;
            if (AlinkWarnings.Contains((ErrorCode)d.Code) &&
                specificDiagnosticOptions.Keys.Contains(CSharp.MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ALinkWarn)))
            {
                reportAction = GetDiagnosticReport(ErrorFacts.GetSeverity(ErrorCode.WRN_ALinkWarn),
                    d.IsEnabledByDefault,
                    CSharp.MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ALinkWarn),
                    ErrorFacts.GetWarningLevel(ErrorCode.WRN_ALinkWarn),
                    d.Location as Location,
                    d.Category,
                    warningLevelOption,
                    generalDiagnosticOption,
                    specificDiagnosticOptions);
            }
            else
            {
                reportAction = GetDiagnosticReport(d.Severity, d.IsEnabledByDefault, d.Id, d.WarningLevel, d.Location as Location, d.Category, warningLevelOption, generalDiagnosticOption, specificDiagnosticOptions);
            }

            return d.WithReportDiagnostic(reportAction);
        }
 private static string ConvertReportDiagnosticToAction(ReportDiagnostic value)
 {
     switch (value)
     {
         case ReportDiagnostic.Default:
             return "Default";
         case ReportDiagnostic.Error:
             return "Error";
         case ReportDiagnostic.Warn:
             return "Warning";
         case ReportDiagnostic.Info:
             return "Info";
         case ReportDiagnostic.Hidden:
             return "Hidden";
         case ReportDiagnostic.Suppress:
             return "None";
         default:
             throw ExceptionUtilities.Unreachable;
     }
 }
        internal static void SetSeverity(this XDocument ruleSet, string analyzerId, string ruleId, ReportDiagnostic value)
        {
            var newAction = ConvertReportDiagnosticToAction(value);

            var rules = FindOrCreateRulesElement(ruleSet, analyzerId);
            var rule = FindOrCreateRuleElement(rules, ruleId);

            if (value == ReportDiagnostic.Default)
            {
                // If the new severity is 'Default' we just delete the entry for the rule from the ruleset file.
                // In the absence of an explicit entry in the ruleset file, the rule reverts back to its 'Default'
                // severity (so far as the 'current' ruleset file is concerned - the rule's effective severity
                // could still be decided by other factors such as project settings or a base ruleset file).
                rule.Remove();
            }
            else
            {
                rule.Attribute("Action").Value = newAction;
            }

            var allMatchingRules = ruleSet.Root
                                       .Descendants("Rule")
                                       .Where(r => r.Attribute("Id").Value.Equals(ruleId))
                                       .ToList();

            foreach (var matchingRule in allMatchingRules)
            {
                if (value == ReportDiagnostic.Default)
                {
                    // If the new severity is 'Default' we just delete the entry for the rule from the ruleset file.
                    // In the absence of an explicit entry in the ruleset file, the rule reverts back to its 'Default'
                    // severity (so far as the 'current' ruleset file is concerned - the rule's effective severity
                    // could still be decided by other factors such as project settings or a base ruleset file).
                    matchingRule.Remove();
                }
                else
                {
                    matchingRule.Attribute("Action").Value = newAction;
                }
            }
        }
Beispiel #12
0
 public CSharpProject(string projectFile)
 {
     if (!File.Exists(projectFile))
         throw new Exception(string.Format("project file not found \"{0}\"", projectFile));
     WriteLine(1, "compile project \"{0}\"", projectFile);
     _projectFile = projectFile;
     _projectDirectory = Path.GetDirectoryName(projectFile);
     _projectDocument = XDocument.Load(projectFile);
     _frameworkDirectory = GetValue("FrameworkDirectory");
     WriteLine(2, "  framework directory               : \"{0}\"", _frameworkDirectory);
     _assemblyName = GetValue("AssemblyName");
     WriteLine(2, "  assembly name                     : \"{0}\"", _assemblyName);
     string outputDirectory = PathCombine(_projectDirectory, GetValue("OutputDirectory"));
     WriteLine(2, "  output directory                  : \"{0}\"", outputDirectory);
     _languageVersion = GetLanguageVersion(GetValue("LanguageVersion"));
     WriteLine(2, "  language version                  : \"{0}\"", _languageVersion);
     _outputKind = GetOutputKind(GetValue("OutputKind"));
     WriteLine(2, "  output kind                       : \"{0}\"", _outputKind);
     _optimizationLevel = GetOptimizationLevel(GetValue("OptimizationLevel"));
     WriteLine(2, "  optimization level                : \"{0}\"", _optimizationLevel);
     _platform = GetPlatform(GetValue("Platform"));
     WriteLine(2, "  platform                          : \"{0}\"", _platform);
     _generalDiagnosticOption = ReportDiagnostic.Default;
     WriteLine(2, "  general diagnostic option         : \"{0}\"", _generalDiagnosticOption);
     _warningLevel = 4;
     WriteLine(2, "  warning level                     : \"{0}\"", _warningLevel);
     _outputPath = PathCombine(outputDirectory, GetValue("OutputPath"));
     WriteLine(2, "  output path                       : \"{0}\"", _outputPath);
     _pdbPath = PathCombine(outputDirectory, GetValue("PdbPath"));
     WriteLine(2, "  pdb path                          : \"{0}\"", _pdbPath);
     _win32ResourceFile = PathCombine(_projectDirectory, GetValue("Win32ResourceFile"));
     WriteLine(2, "  win32 resource file               : \"{0}\"", _win32ResourceFile);
     _preprocessorSymbols = GetPreprocessorSymbols();
     _sourceFiles = GetSources();
     _resourceFiles = GetResourceFiles();
     _assembliesFiles = GetAssembliesFiles();
 }
Beispiel #13
0
        private void AnalyzeForEachStatement(
            SyntaxNodeAnalysisContext context, ForEachStatementSyntax forEachStatement, ReportDiagnostic severity)
        {
            if (!TryAnalyzeForEachStatement(
                    context.SemanticModel, forEachStatement, out _,
                    out var memberAccessExpressions, context.CancellationToken))
            {
                return;
            }

            context.ReportDiagnostic(DiagnosticHelper.Create(
                                         Descriptor,
                                         forEachStatement.Identifier.GetLocation(),
                                         severity,
                                         additionalLocations: null,
                                         properties: null));
        }
 /// <summary>
 /// Creates a new options instance with the specified general diagnostic option.
 /// </summary>
 public CompilationOptions WithGeneralDiagnosticOption(ReportDiagnostic value)
 {
     return(CommonWithGeneralDiagnosticOption(value));
 }
Beispiel #15
0
        private void GenerateSqmData(CompilationOptions compilationOptions, ImmutableArray <Diagnostic> diagnostics)
        {
            // Generate SQM data file for Compilers
            if (Arguments.SqmSessionGuid != Guid.Empty)
            {
                IVsSqmMulti sqm        = null;
                uint        sqmSession = 0u;
                try
                {
                    sqm = SqmServiceProvider.TryGetSqmService(_clientDirectory);
                    if (sqm != null)
                    {
                        sqm.BeginSession(this.GetSqmAppID(), false, out sqmSession);
                        sqm.SetGlobalSessionGuid(Arguments.SqmSessionGuid);

                        // Build Version
                        sqm.SetStringDatapoint(sqmSession, SqmServiceProvider.DATAID_SQM_BUILDVERSION, GetAssemblyFileVersion());

                        // Write Errors and Warnings from build
                        foreach (var diagnostic in diagnostics)
                        {
                            switch (diagnostic.Severity)
                            {
                            case DiagnosticSeverity.Error:
                                sqm.AddItemToStream(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_ERRORNUMBERS, (uint)diagnostic.Code);
                                break;

                            case DiagnosticSeverity.Warning:
                                sqm.AddItemToStream(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_WARNINGNUMBERS, (uint)diagnostic.Code);
                                break;

                            case DiagnosticSeverity.Hidden:
                            case DiagnosticSeverity.Info:
                                break;

                            default:
                                throw ExceptionUtilities.UnexpectedValue(diagnostic.Severity);
                            }
                        }

                        //Suppress Warnings / warningCode as error / warningCode as warning
                        foreach (var item in compilationOptions.SpecificDiagnosticOptions)
                        {
                            uint code;
                            if (TryGetCompilerDiagnosticCode(item.Key, out code))
                            {
                                ReportDiagnostic options = item.Value;
                                switch (options)
                                {
                                case ReportDiagnostic.Suppress:
                                    sqm.AddItemToStream(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_SUPPRESSWARNINGNUMBERS, code);          // Suppress warning
                                    break;

                                case ReportDiagnostic.Error:
                                    sqm.AddItemToStream(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_WARNASERRORS_NUMBERS, code);           // Warning as errors
                                    break;

                                case ReportDiagnostic.Warn:
                                    sqm.AddItemToStream(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_WARNASWARNINGS_NUMBERS, code);         // Warning as warnings
                                    break;

                                default:
                                    break;
                                }
                            }
                        }
                        sqm.SetDatapoint(sqmSession, SqmServiceProvider.DATAID_SQM_ROSLYN_OUTPUTKIND, (uint)compilationOptions.OutputKind);
                        CompilerSpecificSqm(sqm, sqmSession);
                    }
                }
                finally
                {
                    if (sqm != null)
                    {
                        sqm.EndSession(sqmSession);
                    }
                }
            }
        }
Beispiel #16
0
 public override bool TryGetDiagnosticValue(SyntaxTree tree, string diagnosticId, CancellationToken _, out ReportDiagnostic severity)
 {
     if (_options.TryGetValue(tree, out var value))
     {
         return(value.DiagnosticOptions.TryGetValue(diagnosticId, out severity));
     }
     severity = ReportDiagnostic.Default;
     return(false);
 }
Beispiel #17
0
        /// <summary>
        /// Modifies an input <see cref="Diagnostic"/> per the given options. For example, the
        /// severity may be escalated, or the <see cref="Diagnostic"/> may be filtered out entirely
        /// (by returning null).
        /// </summary>
        /// <param name="d">The input diagnostic</param>
        /// <param name="warningLevelOption">The maximum warning level to allow. Diagnostics with a higher warning level will be filtered out.</param>
        /// <param name="generalDiagnosticOption">How warning diagnostics should be reported</param>
        /// <param name="specificDiagnosticOptions">How specific diagnostics should be reported</param>
        /// <returns>A diagnostic updated to reflect the options, or null if it has been filtered out</returns>
        public static Diagnostic Filter(Diagnostic d, int warningLevelOption, ReportDiagnostic generalDiagnosticOption, IDictionary <string, ReportDiagnostic> specificDiagnosticOptions)
        {
            if (d == null)
            {
                return(d);
            }
            else if (d.IsNotConfigurable())
            {
                if (d.IsEnabledByDefault)
                {
                    // Enabled NotConfigurable should always be reported as it is.
                    return(d);
                }
                else
                {
                    // Disabled NotConfigurable should never be reported.
                    return(null);
                }
            }
            else if (d.Severity == InternalDiagnosticSeverity.Void)
            {
                return(null);
            }

            //In the native compiler, all warnings originating from alink.dll were issued
            //under the id WRN_ALinkWarn - 1607. If a customer used nowarn:1607 they would get
            //none of those warnings. In Roslyn, we've given each of these warnings their
            //own number, so that they may be configured independently. To preserve compatibility
            //if a user has specifically configured 1607 and we are reporting one of the alink warnings, use
            //the configuration specified for 1607. As implemented, this could result in customers
            //specifying warnaserror:1607 and getting a message saying "warning as error CS8012..."
            //We don't permit configuring 1607 and independently configuring the new warnings.
            ReportDiagnostic reportAction;
            bool             hasPragmaSuppression;

            if (s_alinkWarnings.Contains((ErrorCode)d.Code) &&
                specificDiagnosticOptions.Keys.Contains(CSharp.MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ALinkWarn)))
            {
                reportAction = GetDiagnosticReport(ErrorFacts.GetSeverity(ErrorCode.WRN_ALinkWarn),
                                                   d.IsEnabledByDefault,
                                                   CSharp.MessageProvider.Instance.GetIdForErrorCode((int)ErrorCode.WRN_ALinkWarn),
                                                   ErrorFacts.GetWarningLevel(ErrorCode.WRN_ALinkWarn),
                                                   d.Location as Location,
                                                   d.Category,
                                                   warningLevelOption,
                                                   generalDiagnosticOption,
                                                   specificDiagnosticOptions,
                                                   out hasPragmaSuppression);
            }
            else
            {
                reportAction = GetDiagnosticReport(d.Severity, d.IsEnabledByDefault, d.Id, d.WarningLevel, d.Location as Location,
                                                   d.Category, warningLevelOption, generalDiagnosticOption, specificDiagnosticOptions, out hasPragmaSuppression);
            }

            if (hasPragmaSuppression)
            {
                d = d.WithIsSuppressed(true);
            }

            return(d.WithReportDiagnostic(reportAction));
        }
Beispiel #18
0
        private void UpdateRuleSetFile(string pathToRuleSet, ReportDiagnostic value)
        {
            var ruleSetDocument = XDocument.Load(pathToRuleSet);

            ruleSetDocument.SetSeverity(_analyzerItem.AnalyzerReference.Display, _descriptor.Id, value);

            ruleSetDocument.Save(pathToRuleSet);
        }
Beispiel #19
0
 public abstract bool TryGetDiagnosticValue(SyntaxTree tree, string diagnosticId, CancellationToken cancellationToken, out ReportDiagnostic severity);
Beispiel #20
0
        // Expects correct arguments.
        internal CompilationOptions(
            OutputKind outputKind,
            bool reportSuppressedDiagnostics,
            string moduleName,
            string mainTypeName,
            string scriptClassName,
            string cryptoKeyContainer,
            string cryptoKeyFile,
            ImmutableArray<byte> cryptoPublicKey,
            bool? delaySign,
            OptimizationLevel optimizationLevel,
            bool checkOverflow,
            Platform platform,
            ReportDiagnostic generalDiagnosticOption,
            int warningLevel,
            ImmutableDictionary<string, ReportDiagnostic> specificDiagnosticOptions,
            bool concurrentBuild,
            bool extendedCustomDebugInformation,
            bool debugPlusMode,
            XmlReferenceResolver xmlReferenceResolver,
            SourceReferenceResolver sourceReferenceResolver,
            MetadataReferenceResolver metadataReferenceResolver,
            AssemblyIdentityComparer assemblyIdentityComparer,
            StrongNameProvider strongNameProvider,
            MetadataImportOptions metadataImportOptions)
        {
            this.OutputKind = outputKind;
            this.ModuleName = moduleName;
            this.MainTypeName = mainTypeName;
            this.ScriptClassName = scriptClassName ?? WellKnownMemberNames.DefaultScriptClassName;
            this.CryptoKeyContainer = cryptoKeyContainer;
            this.CryptoKeyFile = cryptoKeyFile;
            this.CryptoPublicKey = cryptoPublicKey.NullToEmpty();
            this.DelaySign = delaySign;
            this.CheckOverflow = checkOverflow;
            this.Platform = platform;
            this.GeneralDiagnosticOption = generalDiagnosticOption;
            this.WarningLevel = warningLevel;
            this.SpecificDiagnosticOptions = specificDiagnosticOptions;
            this.ReportSuppressedDiagnostics = reportSuppressedDiagnostics;
            this.OptimizationLevel = optimizationLevel;
            this.ConcurrentBuild = concurrentBuild;
            this.ExtendedCustomDebugInformation = extendedCustomDebugInformation;
            this.DebugPlusMode = debugPlusMode;
            this.XmlReferenceResolver = xmlReferenceResolver;
            this.SourceReferenceResolver = sourceReferenceResolver;
            this.MetadataReferenceResolver = metadataReferenceResolver;
            this.StrongNameProvider = strongNameProvider;
            this.AssemblyIdentityComparer = assemblyIdentityComparer ?? AssemblyIdentityComparer.Default;
            this.MetadataImportOptions = metadataImportOptions;

            _lazyErrors = new Lazy<ImmutableArray<Diagnostic>>(() =>
            {
                var builder = ArrayBuilder<Diagnostic>.GetInstance();
                ValidateOptions(builder);
                return builder.ToImmutableAndFree();
            });
        }
 /// <summary>
 /// checks if style is preferred and the enforcement is not None.
 /// </summary>
 /// <remarks>if predefined type is not preferred, it implies the preference is framework type.</remarks>
 private static bool OptionSettingPrefersFrameworkType(CodeStyleOption <bool> optionValue, ReportDiagnostic severity)
 => !optionValue.Value && severity.WithDefaultSeverity(DiagnosticSeverity.Hidden) < ReportDiagnostic.Hidden;
 private static void TestEffectiveSeverity(
     DiagnosticSeverity defaultSeverity,
     ReportDiagnostic expectedEffectiveSeverity,
     Dictionary<string, ReportDiagnostic> specificOptions = null,
     ReportDiagnostic generalOption = ReportDiagnostic.Default,
     bool isEnabledByDefault = true)
 {
     specificOptions = specificOptions ?? new Dictionary<string, ReportDiagnostic>();
     var options = new CSharpCompilationOptions(OutputKind.ConsoleApplication, generalDiagnosticOption: generalOption, specificDiagnosticOptions: specificOptions);
     var descriptor = new DiagnosticDescriptor(id: "Test0001", title: "Test0001", messageFormat: "Test0001", category: "Test0001", defaultSeverity: defaultSeverity, isEnabledByDefault: isEnabledByDefault);
     var effectiveSeverity = descriptor.GetEffectiveSeverity(options);
     Assert.Equal(expectedEffectiveSeverity, effectiveSeverity);
 }
Beispiel #23
0
        private void AnalyzeVariableDeclaration(
            SyntaxNodeAnalysisContext context, VariableDeclarationSyntax variableDeclaration, ReportDiagnostic severity)
        {
            if (!TryAnalyzeVariableDeclaration(
                    context.SemanticModel, variableDeclaration, out _,
                    out var memberAccessExpressions, context.CancellationToken))
            {
                return;
            }

            context.ReportDiagnostic(DiagnosticHelper.Create(
                                         Descriptor,
                                         variableDeclaration.Variables[0].Identifier.GetLocation(),
                                         severity,
                                         additionalLocations: null,
                                         properties: null));
        }
Beispiel #24
0
        public TypeStyleResult(CSharpTypeStyleHelper helper, TypeSyntax typeName, SemanticModel semanticModel, OptionSet optionSet, bool isStylePreferred, ReportDiagnostic severity, CancellationToken cancellationToken) : this()
        {
            _helper            = helper;
            _typeName          = typeName;
            _semanticModel     = semanticModel;
            _optionSet         = optionSet;
            _cancellationToken = cancellationToken;

            IsStylePreferred = isStylePreferred;
            Severity         = severity;
        }
Beispiel #25
0
 private ImageMoniker MapEffectiveSeverityToIconMoniker(ReportDiagnostic effectiveSeverity)
 => effectiveSeverity switch
 {
Beispiel #26
0
 public BaseDiagnosticItem(DiagnosticDescriptor descriptor, ReportDiagnostic effectiveSeverity)
     : base(string.Format("{0}: {1}", descriptor.Id, descriptor.Title))
 {
     _descriptor        = descriptor;
     _effectiveSeverity = effectiveSeverity;
 }
        private void Workspace_WorkspaceChanged(object sender, WorkspaceChangeEventArgs e)
        {
            if (e.Kind == WorkspaceChangeKind.SolutionCleared ||
                e.Kind == WorkspaceChangeKind.SolutionReloaded ||
                e.Kind == WorkspaceChangeKind.SolutionRemoved)
            {
                _workspace.WorkspaceChanged -= Workspace_WorkspaceChanged;
            }
            else if (e.ProjectId == _projectId)
            {
                if (e.Kind == WorkspaceChangeKind.ProjectRemoved)
                {
                    _workspace.WorkspaceChanged -= Workspace_WorkspaceChanged;
                }
                else if (e.Kind == WorkspaceChangeKind.ProjectChanged)
                {
                    var project = e.NewSolution.GetProject(_projectId);
                    var newGeneralDiagnosticOption = project.CompilationOptions.GeneralDiagnosticOption;
                    var newSpecificDiagnosticOptions = project.CompilationOptions.SpecificDiagnosticOptions;

                    if (newGeneralDiagnosticOption != _generalDiagnosticOption ||
                        !object.ReferenceEquals(newSpecificDiagnosticOptions, _specificDiagnosticOptions))
                    {
                        _generalDiagnosticOption = newGeneralDiagnosticOption;
                        _specificDiagnosticOptions = newSpecificDiagnosticOptions;

                        foreach (var item in _diagnosticItems)
                        {
                            item.UpdateEffectiveSeverity(GetEffectiveSeverity(item.Descriptor.Id, _specificDiagnosticOptions, _generalDiagnosticOption, item.Descriptor.DefaultSeverity, item.Descriptor.IsEnabledByDefault));
                        }
                    }
                }
            }
        }
Beispiel #28
0
 private static bool OptionSettingPrefersFrameworkType(CodeStyleOption <bool> optionValue, ReportDiagnostic severity)
 => !optionValue.Value && severity != ReportDiagnostic.Suppress;
Beispiel #29
0
 protected abstract CompilationOptions CommonWithGeneralDiagnosticOption(ReportDiagnostic generalDiagnosticOption);
Beispiel #30
0
 protected abstract void Recurse(
     SyntaxTreeAnalysisContext context,
     Dictionary <int, int> preferredOrder,
     ReportDiagnostic severity,
     SyntaxNode root);
Beispiel #31
0
 internal void SetSeverity(ReportDiagnostic value, string pathToRuleSet)
 {
     UpdateRuleSetFile(pathToRuleSet, value);
 }
        // Take a warning and return the final deposition of the given warning,
        // based on both command line options and pragmas.
        internal static ReportDiagnostic GetDiagnosticReport(
            DiagnosticSeverity severity,
            bool isEnabledByDefault,
            string id,
            int diagnosticWarningLevel,
            Location location,
            string category,
            int warningLevelOption,
            bool nullableOption,
            ReportDiagnostic generalDiagnosticOption,
            IDictionary <string, ReportDiagnostic> specificDiagnosticOptions,
            out bool hasPragmaSuppression)
        {
            hasPragmaSuppression = false;

            // Read options (e.g., /nowarn or /warnaserror)
            ReportDiagnostic report = ReportDiagnostic.Default;
            var isSpecified         = specificDiagnosticOptions.TryGetValue(id, out report);

            if (!isSpecified)
            {
                report = isEnabledByDefault ? ReportDiagnostic.Default : ReportDiagnostic.Suppress;
            }

            // Compute if the reporting should be suppressed.
            if (diagnosticWarningLevel > warningLevelOption)  // honor the warning level
            {
                return(ReportDiagnostic.Suppress);
            }

            bool isNullableFlowAnalysisWarning = ErrorFacts.NullableFlowAnalysisWarnings.Contains(id);

            if (report == ReportDiagnostic.Suppress && // check options (/nowarn)
                !isNullableFlowAnalysisWarning)
            {
                return(ReportDiagnostic.Suppress);
            }

            var pragmaWarningState = Syntax.PragmaWarningState.Default;

            // If location is available, check out pragmas
            if (location != null &&
                location.SourceTree != null &&
                (pragmaWarningState = location.SourceTree.GetPragmaDirectiveWarningState(id, location.SourceSpan.Start)) == Syntax.PragmaWarningState.Disabled)
            {
                hasPragmaSuppression = true;
            }

            if (pragmaWarningState == Syntax.PragmaWarningState.Enabled)
            {
                switch (report)
                {
                case ReportDiagnostic.Error:
                case ReportDiagnostic.Hidden:
                case ReportDiagnostic.Info:
                case ReportDiagnostic.Warn:
                    // No need to adjust the current report state, it already means "enabled"
                    return(report);

                case ReportDiagnostic.Suppress:
                    // Enable the warning
                    return(ReportDiagnostic.Default);

                case ReportDiagnostic.Default:
                    if (generalDiagnosticOption == ReportDiagnostic.Error && promoteToAnError())
                    {
                        return(ReportDiagnostic.Error);
                    }

                    return(ReportDiagnostic.Default);

                default:
                    throw ExceptionUtilities.UnexpectedValue(report);
                }
            }
            else if (report == ReportDiagnostic.Suppress) // check options (/nowarn)
            {
                return(ReportDiagnostic.Suppress);
            }

            // Nullable flow analysis warnings cannot be turned on by specific diagnostic options.
            // They can be turned on by nullable options and specific diagnostic options
            // can either turn them off, or adjust the way they are reported.
            if (isNullableFlowAnalysisWarning && !nullableOption)
            {
                return(ReportDiagnostic.Suppress);
            }

            // Unless specific warning options are defined (/warnaserror[+|-]:<n> or /nowarn:<n>,
            // follow the global option (/warnaserror[+|-] or /nowarn).
            if (report == ReportDiagnostic.Default)
            {
                switch (generalDiagnosticOption)
                {
                case ReportDiagnostic.Error:
                    if (promoteToAnError())
                    {
                        return(ReportDiagnostic.Error);
                    }
                    break;

                case ReportDiagnostic.Suppress:
                    // When doing suppress-all-warnings, don't lower severity for anything other than warning and info.
                    // We shouldn't suppress hidden diagnostics here because then features that use hidden diagnostics to
                    // display a lightbulb would stop working if someone has suppress-all-warnings (/nowarn) specified in their project.
                    if (severity == DiagnosticSeverity.Warning || severity == DiagnosticSeverity.Info)
                    {
                        return(ReportDiagnostic.Suppress);
                    }
                    break;

                default:
                    break;
                }
            }

            return(report);

            bool promoteToAnError()
            {
                Debug.Assert(report == ReportDiagnostic.Default);
                Debug.Assert(generalDiagnosticOption == ReportDiagnostic.Error);

                // If we've been asked to do warn-as-error then don't raise severity for anything below warning (info or hidden).
                return(severity == DiagnosticSeverity.Warning &&
                       // In the case where /warnaserror+ is followed by /warnaserror-:<n> on the command line,
                       // do not promote the warning specified in <n> to an error.
                       !isSpecified);
            }
        }
        private void ReportDiagnostics(
            SyntaxNodeAnalysisContext syntaxContext,
            StatementSyntax firstStatement,
            IfStatementSyntax ifStatement,
            ExpressionStatementSyntax expressionStatement,
            ReportDiagnostic severity,
            ImmutableArray <Location> additionalLocations,
            string kind
            )
        {
            var tree = syntaxContext.Node.SyntaxTree;

            var properties = ImmutableDictionary <string, string> .Empty.Add(Constants.Kind, kind);

            var previousToken = expressionStatement.GetFirstToken().GetPreviousToken();
            var nextToken     = expressionStatement.GetLastToken().GetNextToken();

            // Fade out the code up to the expression statement.
            var fadeLocation = Location.Create(
                tree,
                TextSpan.FromBounds(firstStatement.SpanStart, previousToken.Span.End)
                );

            syntaxContext.ReportDiagnostic(
                DiagnosticHelper.CreateWithLocationTags(
                    Descriptor,
                    fadeLocation,
                    ReportDiagnostic.Default,
                    additionalLocations,
                    additionalUnnecessaryLocations: ImmutableArray.Create(fadeLocation),
                    properties
                    )
                );

            // Put a diagnostic with the appropriate severity on the expression-statement itself.
            syntaxContext.ReportDiagnostic(
                DiagnosticHelper.Create(
                    Descriptor,
                    expressionStatement.GetLocation(),
                    severity,
                    additionalLocations,
                    properties
                    )
                );

            // If the if-statement extends past the expression statement, then fade out the rest.
            if (nextToken.Span.Start < ifStatement.Span.End)
            {
                fadeLocation = Location.Create(
                    tree,
                    TextSpan.FromBounds(nextToken.Span.Start, ifStatement.Span.End)
                    );
                syntaxContext.ReportDiagnostic(
                    DiagnosticHelper.CreateWithLocationTags(
                        Descriptor,
                        fadeLocation,
                        ReportDiagnostic.Default,
                        additionalLocations,
                        additionalUnnecessaryLocations: ImmutableArray.Create(fadeLocation),
                        properties
                        )
                    );
            }
        }
Beispiel #34
0
        private void UpdateRuleSetFile(string pathToRuleSet, ReportDiagnostic value)
        {
            var ruleSetDocument = XDocument.Load(pathToRuleSet);

            var newAction = ConvertReportDiagnosticToAction(value);

            var analyzerID = _analyzerItem.AnalyzerReference.Display;
            var rules = FindOrCreateRulesElement(ruleSetDocument, analyzerID);
            var rule = FindOrCreateRuleElement(rules, _descriptor.Id);
            rule.Attribute("Action").Value = newAction;

            var allMatchingRules = ruleSetDocument.Root
                                   .Descendants("Rule")
                                   .Where(r => r.Attribute("Id").Value.Equals(_descriptor.Id));

            foreach (var matchingRule in allMatchingRules)
            {
                matchingRule.Attribute("Action").Value = newAction;
            }

            ruleSetDocument.Save(pathToRuleSet);
        }
Beispiel #35
0
 public abstract bool TryGetGlobalDiagnosticValue(string diagnosticId, CancellationToken cancellationToken, out ReportDiagnostic severity);
Beispiel #36
0
 protected override CompilationOptions CommonWithGeneralDiagnosticOption(ReportDiagnostic value) => WithGeneralDiagnosticOption(value);
Beispiel #37
0
 public override bool TryGetGlobalDiagnosticValue(string diagnosticId, CancellationToken _, out ReportDiagnostic severity)
 {
     if (_globalOptions.TreeOptions is object)
     {
         return(_globalOptions.TreeOptions.TryGetValue(diagnosticId, out severity));
     }
     severity = ReportDiagnostic.Default;
     return(false);
 }
Beispiel #38
0
 public DiagnosticItem(AnalyzerItem analyzerItem, DiagnosticDescriptor descriptor, ReportDiagnostic effectiveSeverity, IContextMenuController contextMenuController)
     : base(string.Format("{0}: {1}", descriptor.Id, descriptor.Title))
 {
     _analyzerItem          = analyzerItem;
     _descriptor            = descriptor;
     _effectiveSeverity     = effectiveSeverity;
     _contextMenuController = contextMenuController;
 }
Beispiel #39
0
        // Take a warning and return the final deposition of the given warning,
        // based on both command line options and pragmas.
        internal static ReportDiagnostic GetDiagnosticReport(
            DiagnosticSeverity severity,
            bool isEnabledByDefault,
            string id,
            int diagnosticWarningLevel,
            Location location,
            string category,
            int warningLevelOption,
            ReportDiagnostic generalDiagnosticOption,
            IDictionary <string, ReportDiagnostic> specificDiagnosticOptions,
            out bool hasPragmaSuppression)
        {
            hasPragmaSuppression = false;

            // Read options (e.g., /nowarn or /warnaserror)
            ReportDiagnostic report = ReportDiagnostic.Default;
            var isSpecified         = specificDiagnosticOptions.TryGetValue(id, out report);

            if (!isSpecified)
            {
                report = isEnabledByDefault ? ReportDiagnostic.Default : ReportDiagnostic.Suppress;
            }

            // Compute if the reporting should be suppressed.
            if (diagnosticWarningLevel > warningLevelOption || // honor the warning level
                report == ReportDiagnostic.Suppress)                   // check options (/nowarn)
            {
                return(ReportDiagnostic.Suppress);
            }

            // If location is available, check out pragmas
            if (location != null &&
                location.SourceTree != null &&
                ((SyntaxTree)location.SourceTree).GetPragmaDirectiveWarningState(id, location.SourceSpan.Start) == ReportDiagnostic.Suppress)
            {
                hasPragmaSuppression = true;
            }

            // Unless specific warning options are defined (/warnaserror[+|-]:<n> or /nowarn:<n>,
            // follow the global option (/warnaserror[+|-] or /nowarn).
            if (report == ReportDiagnostic.Default)
            {
                switch (generalDiagnosticOption)
                {
                case ReportDiagnostic.Error:
                    // If we've been asked to do warn-as-error then don't raise severity for anything below warning (info or hidden).
                    if (severity == DiagnosticSeverity.Warning)
                    {
                        // In the case where /warnaserror+ is followed by /warnaserror-:<n> on the command line,
                        // do not promote the warning specified in <n> to an error.
                        if (!isSpecified && (report == ReportDiagnostic.Default))
                        {
                            return(ReportDiagnostic.Error);
                        }
                    }
                    break;

                case ReportDiagnostic.Suppress:
                    // When doing suppress-all-warnings, don't lower severity for anything other than warning and info.
                    // We shouldn't suppress hidden diagnostics here because then features that use hidden diagnostics to
                    // display a lightbulb would stop working if someone has suppress-all-warnings (/nowarn) specified in their project.
                    if (severity == DiagnosticSeverity.Warning || severity == DiagnosticSeverity.Info)
                    {
                        return(ReportDiagnostic.Suppress);
                    }
                    break;

                default:
                    break;
                }
            }

            return(report);
        }
        // Expects correct arguments.
        internal CompilationOptions(
            OutputKind outputKind,
            string moduleName,
            string mainTypeName,
            string scriptClassName,
            string cryptoKeyContainer,
            string cryptoKeyFile,
            bool? delaySign,
            OptimizationLevel optimizationLevel,
            bool checkOverflow,
            int fileAlignment,
            ulong baseAddress,
            Platform platform,
            ReportDiagnostic generalDiagnosticOption,
            int warningLevel,
            ImmutableDictionary<string, ReportDiagnostic> specificDiagnosticOptions,
            bool highEntropyVirtualAddressSpace,
            SubsystemVersion subsystemVersion,
            bool concurrentBuild,
            XmlReferenceResolver xmlReferenceResolver,
            SourceReferenceResolver sourceReferenceResolver,
            MetadataReferenceResolver metadataReferenceResolver,
            MetadataReferenceProvider metadataReferenceProvider,
            AssemblyIdentityComparer assemblyIdentityComparer,
            StrongNameProvider strongNameProvider,
            MetadataImportOptions metadataImportOptions,
            ImmutableArray<string> features)
        {
            this.OutputKind = outputKind;
            this.ModuleName = moduleName;
            this.MainTypeName = mainTypeName;
            this.ScriptClassName = scriptClassName;
            this.CryptoKeyContainer = cryptoKeyContainer;
            this.CryptoKeyFile = cryptoKeyFile;
            this.DelaySign = delaySign;
            this.CheckOverflow = checkOverflow;
            this.FileAlignment = fileAlignment;
            this.BaseAddress = baseAddress;
            this.Platform = platform;
            this.GeneralDiagnosticOption = generalDiagnosticOption;
            this.WarningLevel = warningLevel;
            this.SpecificDiagnosticOptions = specificDiagnosticOptions;
            this.HighEntropyVirtualAddressSpace = highEntropyVirtualAddressSpace;
            this.OptimizationLevel = optimizationLevel;
            this.ConcurrentBuild = concurrentBuild;
            this.SubsystemVersion = subsystemVersion;
            this.XmlReferenceResolver = xmlReferenceResolver;
            this.SourceReferenceResolver = sourceReferenceResolver;
            this.MetadataReferenceResolver = metadataReferenceResolver;
            this.MetadataReferenceProvider = metadataReferenceProvider;
            this.StrongNameProvider = strongNameProvider;
            this.AssemblyIdentityComparer = assemblyIdentityComparer ?? AssemblyIdentityComparer.Default;
            this.MetadataImportOptions = metadataImportOptions;
            this.Features = features;

            this.lazyErrors = new Lazy<ImmutableArray<Diagnostic>>(() =>
            {
                var builder = ArrayBuilder<Diagnostic>.GetInstance();
                ValidateOptions(builder);
                return builder.ToImmutableAndFree();
            });
        }
 protected abstract CompilationOptions CommonWithGeneralDiagnosticOption(ReportDiagnostic value);
 private void SetWarnings(string warnings, ReportDiagnostic reportStyle)
 {
     if (!string.IsNullOrEmpty(warnings))
     {
         foreach (var warning in warnings.Split(preprocessorSymbolSeparators, StringSplitOptions.None))
         {
             int warningId;
             if (int.TryParse(warning, out warningId))
             {
                 this.Warnings["CS" + warningId.ToString("0000")] = reportStyle;
             }
         }
     }
 }
        protected void ReadCompilationOptionsFrom(
            ObjectReader reader,
            out OutputKind outputKind,
            out bool reportSuppressedDiagnostics,
            out string moduleName,
            out string mainTypeName,
            out string scriptClassName,
            out OptimizationLevel optimizationLevel,
            out bool checkOverflow,
            out string cryptoKeyContainer,
            out string cryptoKeyFile,
            out ImmutableArray <byte> cryptoPublicKey,
            out bool?delaySign,
            out Platform platform,
            out ReportDiagnostic generalDiagnosticOption,
            out int warningLevel,
            out IEnumerable <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptions,
            out bool concurrentBuild,
            out bool deterministic,
            out bool publicSign,
            out XmlReferenceResolver xmlReferenceResolver,
            out SourceReferenceResolver sourceReferenceResolver,
            out MetadataReferenceResolver metadataReferenceResolver,
            out AssemblyIdentityComparer assemblyIdentityComparer,
            out StrongNameProvider strongNameProvider,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            outputKind = (OutputKind)reader.ReadInt32();
            reportSuppressedDiagnostics = reader.ReadBoolean();
            moduleName   = reader.ReadString();
            mainTypeName = reader.ReadString();

            scriptClassName   = reader.ReadString();
            optimizationLevel = (OptimizationLevel)reader.ReadInt32();
            checkOverflow     = reader.ReadBoolean();

            // REVIEW: is it okay this being not part of snapshot?
            cryptoKeyContainer = reader.ReadString();
            cryptoKeyFile      = reader.ReadString();

            cryptoPublicKey = reader.ReadArray <byte>().ToImmutableArrayOrEmpty();

            delaySign = reader.ReadBoolean() ? (bool?)reader.ReadBoolean() : null;

            platform = (Platform)reader.ReadInt32();
            generalDiagnosticOption = (ReportDiagnostic)reader.ReadInt32();

            warningLevel = reader.ReadInt32();

            // REVIEW: I don't think there is a guarantee on ordering of elements in the immutable dictionary.
            //         unfortunately, we need to sort them to make it deterministic
            //         not sure why CompilationOptions uses SequencialEqual to check options equality
            //         when ordering can change result of it even if contents are same.
            var count = reader.ReadInt32();
            List <KeyValuePair <string, ReportDiagnostic> > specificDiagnosticOptionsList = null;

            if (count > 0)
            {
                specificDiagnosticOptionsList = new List <KeyValuePair <string, ReportDiagnostic> >(count);

                for (var i = 0; i < count; i++)
                {
                    var key   = reader.ReadString();
                    var value = (ReportDiagnostic)reader.ReadInt32();

                    specificDiagnosticOptionsList.Add(KeyValuePair.Create(key, value));
                }
            }

            specificDiagnosticOptions = specificDiagnosticOptionsList ?? SpecializedCollections.EmptyEnumerable <KeyValuePair <string, ReportDiagnostic> >();

            concurrentBuild = reader.ReadBoolean();
            deterministic   = reader.ReadBoolean();
            publicSign      = reader.ReadBoolean();

            // REVIEW: What should I do with these. are these service required when compilation is built ourselves, not through
            //         compiler.
            xmlReferenceResolver      = XmlFileResolver.Default;
            sourceReferenceResolver   = SourceFileResolver.Default;
            metadataReferenceResolver = null;
            assemblyIdentityComparer  = DesktopAssemblyIdentityComparer.Default;
            strongNameProvider        = new DesktopStrongNameProvider();
        }
Beispiel #44
0
 /// <summary>
 /// Returns true if the action1 is stricter than action2.
 /// </summary>
 private static bool IsStricterThan(ReportDiagnostic action1, ReportDiagnostic action2)
 {
     switch (action2)
     {
         case ReportDiagnostic.Suppress:
             return true;
         case ReportDiagnostic.Default:
             return action1 == ReportDiagnostic.Warn || action1 == ReportDiagnostic.Error || action1 == ReportDiagnostic.Info || action1 == ReportDiagnostic.Hidden;
         case ReportDiagnostic.Hidden:
             return action1 == ReportDiagnostic.Warn || action1 == ReportDiagnostic.Error || action1 == ReportDiagnostic.Info;
         case ReportDiagnostic.Info:
             return action1 == ReportDiagnostic.Warn || action1 == ReportDiagnostic.Error;
         case ReportDiagnostic.Warn:
             return action1 == ReportDiagnostic.Error;
         case ReportDiagnostic.Error:
             return false;
         default:
             return false;
     }
 }
Beispiel #45
0
 internal void SetSeverity(ReportDiagnostic value, string pathToRuleSet)
 {
     UpdateRuleSetFile(pathToRuleSet, value);
 }
Beispiel #46
0
 public static CSharpCompilationOptions WithSpecificDiagnosticOptions(this CSharpCompilationOptions options, string key1, string key2, ReportDiagnostic value)
 {
     return(options.WithSpecificDiagnosticOptions(ImmutableDictionary <string, ReportDiagnostic> .Empty.Add(key1, value).Add(key2, value)));
 }
Beispiel #47
0
 /// <summary>
 /// Create a RuleSetInclude given the includepath and the effective action.
 /// </summary>
 public  RuleSetInclude(string includePath, ReportDiagnostic action)
 {
     this.includePath = includePath;
     this.action = action;
 }
        public void TestParseEditorConfigCodeStyleOption(string args, bool isEnabled, ReportDiagnostic severity)
        {
            var notificationOption = NotificationOption.Silent;

            switch (severity)
            {
            case ReportDiagnostic.Hidden:
                notificationOption = NotificationOption.Silent;
                break;

            case ReportDiagnostic.Info:
                notificationOption = NotificationOption.Suggestion;
                break;

            case ReportDiagnostic.Warn:
                notificationOption = NotificationOption.Warning;
                break;

            case ReportDiagnostic.Error:
                notificationOption = NotificationOption.Error;
                break;
            }

            var codeStyleOption = new CodeStyleOption <bool>(value: isEnabled, notification: notificationOption);

            CodeStyleHelpers.TryParseBoolEditorConfigCodeStyleOption(args, out var result);
            Assert.True(result.Value == isEnabled,
                        $"Expected {nameof(isEnabled)} to be {isEnabled}, was {result.Value}");
            Assert.True(result.Notification.Severity == severity,
                        $"Expected {nameof(severity)} to be {severity}, was {result.Notification.Severity}");
        }
        private static void AssertSpecificDiagnostics(int[] expectedCodes, ReportDiagnostic[] expectedOptions, CSharpCommandLineArguments args)
        {
            var actualOrdered = args.CompilationOptions.SpecificDiagnosticOptions.OrderBy(entry => entry.Key);

            AssertEx.Equal(
                expectedCodes.Select(i => MessageProvider.Instance.GetIdForErrorCode(i)),
                actualOrdered.Select(entry => entry.Key));

            AssertEx.Equal(expectedOptions, actualOrdered.Select(entry => entry.Value));
        }
        public void TestParseEditorConfigAccessibilityModifiers(string args, int value, ReportDiagnostic severity)
        {
            var storageLocation = CodeStyleOptions.RequireAccessibilityModifiers.StorageLocations
                                  .OfType <EditorConfigStorageLocation <CodeStyleOption <AccessibilityModifiersRequired> > >()
                                  .Single();
            var allRawConventions = new Dictionary <string, string?> {
                { storageLocation.KeyName, args }
            };

            Assert.True(storageLocation.TryGetOption(allRawConventions, typeof(CodeStyleOption <AccessibilityModifiersRequired>), out var parsedCodeStyleOption));
            var codeStyleOption = (CodeStyleOption <AccessibilityModifiersRequired>)parsedCodeStyleOption !;

            Assert.Equal((AccessibilityModifiersRequired)value, codeStyleOption.Value);
            Assert.Equal(severity, codeStyleOption.Notification.Severity);
        }
Beispiel #51
0
 /// <summary>
 /// Create a RuleSetInclude given the includepath and the effective action.
 /// </summary>
 public RuleSetInclude(string includePath, ReportDiagnostic action)
 {
     _includePath = includePath;
     _action = action;
 }
Beispiel #52
0
 /// <summary>
 /// Create a RuleSetInclude given the include path and the effective action.
 /// </summary>
 public RuleSetInclude(string includePath, ReportDiagnostic action)
 {
     _includePath = includePath;
     _action      = action;
 }
 private bool AnyDiagnosticsWithSeverity(ReportDiagnostic severity)
 {
     return _selectedDiagnosticItems.Any(item => item.EffectiveSeverity == severity);
 }
Beispiel #54
0
 protected override BaseDiagnosticItem CreateItem(DiagnosticDescriptor diagnostic, ReportDiagnostic effectiveSeverity, string language)
 => new LegacyDiagnosticItem(_item, diagnostic, effectiveSeverity, language, CommandHandler.DiagnosticContextMenuController);
        // If you update this method, also consider making updates to CSharpDiagnosticFilter.GetDiagnosticReport and
        // VisualBasicDiagnosticFilter.GetDiagnosticReport.
        internal static ReportDiagnostic GetEffectiveSeverity(string ruleId, IDictionary<string, ReportDiagnostic> specificOptions, ReportDiagnostic generalOption, DiagnosticSeverity defaultSeverity, bool enabledByDefault)
        {
            ReportDiagnostic report = ReportDiagnostic.Default;
            var isSpecified = specificOptions.TryGetValue(ruleId, out report);
            if (!isSpecified)
            {
                report = enabledByDefault ? ReportDiagnostic.Default : ReportDiagnostic.Suppress;
            }

            if (report == ReportDiagnostic.Default)
            {
                switch (generalOption)
                {
                    case ReportDiagnostic.Error:
                        if (defaultSeverity == DiagnosticSeverity.Warning)
                        {
                            if (!isSpecified)
                            {
                                return ReportDiagnostic.Error;
                            }
                        }

                        break;
                    case ReportDiagnostic.Suppress:
                        if (defaultSeverity == DiagnosticSeverity.Warning || defaultSeverity == DiagnosticSeverity.Info)
                        {
                            return ReportDiagnostic.Suppress;
                        }

                        break;
                    default:
                        break;
                }

                return MapSeverityToReport(defaultSeverity);
            }

            return report;
        }
 private bool AnyDiagnosticsWithSeverity(ReportDiagnostic severity)
 {
     return(_tracker.SelectedDiagnosticItems.Any(item => item.EffectiveSeverity == severity));
 }
Beispiel #57
0
 /// <summary>
 /// Creates a new options instance with the specified general diagnostic option.
 /// </summary>
 public CompilationOptions WithGeneralDiagnosticOption(ReportDiagnostic value)
 {
     return CommonWithGeneralDiagnosticOption(value);
 }
        private bool TryCheckVariableAndIfStatementForm(
            SyntaxNodeAnalysisContext syntaxContext,
            IfStatementSyntax ifStatement,
            BinaryExpressionSyntax condition,
            ExpressionStatementSyntax expressionStatement,
            InvocationExpressionSyntax invocationExpression,
            ReportDiagnostic severity)
        {
            var cancellationToken = syntaxContext.CancellationToken;

            cancellationToken.ThrowIfCancellationRequested();

            // look for the form "if (a != null)" or "if (null != a)"
            if (!ifStatement.Parent.IsKind(SyntaxKind.Block))
            {
                return(false);
            }

            if (!IsNullCheckExpression(condition.Left, condition.Right) &&
                !IsNullCheckExpression(condition.Right, condition.Left))
            {
                return(false);
            }

            var expression = invocationExpression.Expression;

            if (!expression.IsKind(SyntaxKind.IdentifierName))
            {
                return(false);
            }

            var conditionName = condition.Left is IdentifierNameSyntax
                ? (IdentifierNameSyntax)condition.Left
                : (IdentifierNameSyntax)condition.Right;

            var invocationName = (IdentifierNameSyntax)expression;

            if (!Equals(conditionName.Identifier.ValueText, invocationName.Identifier.ValueText))
            {
                return(false);
            }

            // Now make sure the previous statement is "var a = ..."
            var parentBlock = (BlockSyntax)ifStatement.Parent;
            var ifIndex     = parentBlock.Statements.IndexOf(ifStatement);

            if (ifIndex == 0)
            {
                return(false);
            }

            var previousStatement = parentBlock.Statements[ifIndex - 1];

            if (!previousStatement.IsKind(SyntaxKind.LocalDeclarationStatement, out LocalDeclarationStatementSyntax localDeclarationStatement))
            {
                return(false);
            }

            var variableDeclaration = localDeclarationStatement.Declaration;

            if (variableDeclaration.Variables.Count != 1)
            {
                return(false);
            }

            var declarator = variableDeclaration.Variables[0];

            if (declarator.Initializer == null)
            {
                return(false);
            }

            cancellationToken.ThrowIfCancellationRequested();
            if (!Equals(declarator.Identifier.ValueText, conditionName.Identifier.ValueText))
            {
                return(false);
            }

            // Syntactically this looks good.  Now make sure that the local is a delegate type.
            var semanticModel = syntaxContext.SemanticModel;

            // The initializer can't be inlined if it's an actual lambda/method reference.
            // These cannot be invoked with `?.` (only delegate *values* can be).
            var initializer = declarator.Initializer.Value.WalkDownParentheses();

            if (initializer.IsAnyLambdaOrAnonymousMethod())
            {
                return(false);
            }

            var initializerSymbol = semanticModel.GetSymbolInfo(initializer, cancellationToken).GetAnySymbol();

            if (initializerSymbol is IMethodSymbol)
            {
                return(false);
            }

            var localSymbol = (ILocalSymbol)semanticModel.GetDeclaredSymbol(declarator, cancellationToken);

            // Ok, we made a local just to check it for null and invoke it.  Looks like something
            // we can suggest an improvement for!
            // But first make sure we're only using the local only within the body of this if statement.
            var analysis = semanticModel.AnalyzeDataFlow(localDeclarationStatement, ifStatement);

            if (analysis.ReadOutside.Contains(localSymbol) || analysis.WrittenOutside.Contains(localSymbol))
            {
                return(false);
            }

            // Looks good!
            var tree = semanticModel.SyntaxTree;
            var additionalLocations = ImmutableArray.Create <Location>(
                Location.Create(tree, localDeclarationStatement.Span),
                Location.Create(tree, ifStatement.Span),
                Location.Create(tree, expressionStatement.Span));

            ReportDiagnostics(syntaxContext,
                              localDeclarationStatement, ifStatement, expressionStatement,
                              severity, additionalLocations, Constants.VariableAndIfStatementForm);

            return(true);
        }
Beispiel #59
0
 private static void AddWarnings(Dictionary<string, ReportDiagnostic> d, ReportDiagnostic kind, IEnumerable<string> items)
 {
     foreach (var id in items)
     {
         ReportDiagnostic existing;
         if (d.TryGetValue(id, out existing))
         {
             // Rewrite the existing value with the latest one unless it is for /nowarn.
             if (existing != ReportDiagnostic.Suppress)
                 d[id] = kind;
         }
         else
         {
             d.Add(id, kind);
         }
     }
 }
Beispiel #60
0
 private ImageMoniker MapEffectiveSeverityToIconMoniker(ReportDiagnostic effectiveSeverity)
 {
     switch (effectiveSeverity)
     {
         case ReportDiagnostic.Error:
             return KnownMonikers.CodeErrorRule;
         case ReportDiagnostic.Warn:
             return KnownMonikers.CodeWarningRule;
         case ReportDiagnostic.Info:
             return KnownMonikers.CodeInformationRule;
         case ReportDiagnostic.Hidden:
             return KnownMonikers.CodeHiddenRule;
         case ReportDiagnostic.Suppress:
             return KnownMonikers.CodeSuppressedRule;
         default:
             return default(ImageMoniker);
     }
 }