private SimpleDiagnostic(
                DiagnosticDescriptor descriptor,
                DiagnosticSeverity severity,
                int warningLevel,
                Location location,
                IEnumerable<Location> additionalLocations,
                object[] messageArgs)
            {
                if ((warningLevel == 0 && severity != DiagnosticSeverity.Error) ||
                    (warningLevel != 0 && severity == DiagnosticSeverity.Error))
                {
                    throw new ArgumentException(nameof(warningLevel));
                }

                if(descriptor == null)
                {
                    throw new ArgumentNullException(nameof(descriptor));
                }

                _descriptor = descriptor;
                _severity = severity;
                _warningLevel = warningLevel;
                _location = location ?? Location.None;
                _additionalLocations = additionalLocations == null ? SpecializedCollections.EmptyReadOnlyList<Location>() : additionalLocations.ToImmutableArray();
                _messageArgs = messageArgs ?? SpecializedCollections.EmptyArray<object>();
            }
Beispiel #2
0
 public Diagnostic(TextSpan textSpan, DiagnosticId diagnosticId, string message)
 {
     Span = textSpan;
     Message = message;
     DiagnosticId = diagnosticId;
     Severity = DiagnosticFacts.GetSeverity(diagnosticId);
 }
            private SimpleDiagnostic(
                DiagnosticDescriptor descriptor,
                DiagnosticSeverity severity,
                int warningLevel,
                Location location,
                IEnumerable<Location> additionalLocations,
                object[] messageArgs,
                ImmutableDictionary<string, string> properties,
                bool isSuppressed)
            {
                if ((warningLevel == 0 && severity != DiagnosticSeverity.Error) ||
                    (warningLevel != 0 && severity == DiagnosticSeverity.Error))
                {
                    throw new ArgumentException(nameof(warningLevel));
                }

                if (descriptor == null)
                {
                    throw new ArgumentNullException(nameof(descriptor));
                }

                _descriptor = descriptor;
                _severity = severity;
                _warningLevel = warningLevel;
                _location = location ?? Location.None;
                _additionalLocations = additionalLocations?.ToImmutableArray() ?? SpecializedCollections.EmptyReadOnlyList<Location>();
                _messageArgs = messageArgs ?? Array.Empty<object>();
                _properties = properties ?? ImmutableDictionary<string, string>.Empty;
                _isSuppressed = isSuppressed;
            }
Beispiel #4
0
        public readonly TextSpan TextSpan; //opt

        #endregion Fields

        #region Constructors

        public Diagnostic(DiagnosticSeverity severity, int code, string message, TextSpan textSpan)
        {
            Severity = severity;
            Code = code;
            Message = message;
            TextSpan = textSpan;
        }
            internal SimpleDiagnostic(string id, string category, string message, DiagnosticSeverity severity, bool isEnabledByDefault,
                                      int warningLevel, bool isWarningAsError, Location location,
                                      IEnumerable<Location> additionalLocations)
            {
                if (isWarningAsError && severity != DiagnosticSeverity.Warning)
                {
                    throw new ArgumentException("isWarningAsError");
                }

                if ((warningLevel == 0 && severity == DiagnosticSeverity.Warning) ||
                    (warningLevel != 0 && severity != DiagnosticSeverity.Warning))
                {
                    throw new ArgumentException("warningLevel");
                }

                this.id = id;
                this.category = category;
                this.message = message;
                this.severity = severity;
                this.isEnabledByDefault = isEnabledByDefault;
                this.warningLevel = warningLevel;
                this.isWarningAsError = isWarningAsError;
                this.location = location;
                this.additionalLocations = additionalLocations == null ? SpecializedCollections.EmptyReadOnlyList<Location>() : additionalLocations.ToImmutableArray();
            }
 /// <summary>
 /// インスタンスを初期化します。
 /// </summary>
 /// <param name="id">解析したルールの識別子</param>
 /// <param name="message">解析結果のメッセージ</param>
 /// <param name="severity">解析したルールの重大度</param>
 /// <param name="locations">解析結果が示すソースコードの位置</param>
 public DiagnosticResult(string id, string message, DiagnosticSeverity? severity, params DiagnosticResultLocation[] locations)
 {
     Id = id;
     Message = message;
     Severity = severity;
     Locations = locations ?? new DiagnosticResultLocation[0];
 }
Beispiel #7
0
 // Given a message identifier (e.g., CS0219), severity, warning as error and a culture, 
 // get the entire prefix (e.g., "error CS0219: Warning as Error:" for C#) used on error messages.
 public override string GetMessagePrefix(string id, DiagnosticSeverity severity, bool isWarningAsError, CultureInfo culture)
 {
     return String.Format(culture, "{0} {1}{2}",
         severity == DiagnosticSeverity.Error || isWarningAsError ? "error" : "warning",
         id,
         isWarningAsError ? ErrorFacts.GetMessage(MessageID.IDS_WarnAsError, culture) : "");
 }
 public DiagnosticData(
     string id,
     string category,
     string message,
     string enuMessageForBingSearch,
     DiagnosticSeverity severity,
     bool isEnabledByDefault,
     int warningLevel,
     Workspace workspace,
     ProjectId projectId,
     DocumentId documentId = null,
     TextSpan? span = null,
     string originalFilePath = null,
     int originalStartLine = 0,
     int originalStartColumn = 0,
     int originalEndLine = 0,
     int originalEndColumn = 0,
     string title = null,
     string description = null,
     string helpLink = null) :
         this(
             id, category, message, enuMessageForBingSearch,
             severity, severity, isEnabledByDefault, warningLevel,
             ImmutableArray<string>.Empty, ImmutableDictionary<string, string>.Empty,
             workspace, projectId, documentId, span,
             null, originalStartLine, originalStartColumn, originalEndLine, originalEndColumn,
             originalFilePath, originalStartLine, originalStartColumn, originalEndLine, originalEndColumn,
             title, description, helpLink)
 {
 }
Beispiel #9
0
        public AnalyzerDetails(string className, 
                               AnalyzerCategoryDetails category,
                               DefaultState defaultState,
                               DiagnosticSeverity severity,
                               string titleResourceName,
                               string descriptionResourceName,
                               string messageFormatResourceName,
                               IList<Type> suppressionAttributes)
        {
            var decomposedDetails = DecomposeDetailsFromClassName(className);
            var code = decomposedDetails.Item1;
            Name = decomposedDetails.Item2;
            NameWithCode = $"{decomposedDetails.Item3} - {Name}";
            Category = category;
            _defaultState = defaultState;
            Severity = severity;
            SuppressionAttributes = suppressionAttributes;

            Title = LocalizableStringFactory.LocalizableResourceString(titleResourceName);
            Description = LocalizableStringFactory.LocalizableResourceString(descriptionResourceName);
            MessageFormat = LocalizableStringFactory.LocalizableResourceString(messageFormatResourceName);
            DiagnosticId = Title.ToString().Replace("-", "");

            if (Title.ToString() != code)
            {
                throw new ArgumentException($@"Title resource value isn't of the correct format: should be {code}",
                                            nameof(titleResourceName));
            }
        }
Beispiel #10
0
 public EnforcementLevel(DiagnosticSeverity severity)
 {
     Value = severity;
     switch (severity)
     {
         case DiagnosticSeverity.Hidden:
             Name = "None";
             Moniker = KnownMonikers.None;
             return;
         case DiagnosticSeverity.Info:
             Name = "Suggestion";
             Moniker = KnownMonikers.StatusInformation;
             return;
         case DiagnosticSeverity.Warning:
             Name = "Warning";
             Moniker = KnownMonikers.StatusWarning;
             return;
         case DiagnosticSeverity.Error:
             Name = "Error";
             Moniker = KnownMonikers.StatusError;
             return;
         default:
             throw new ArgumentException("Unexpected DiagnosticSeverity", nameof(severity));
     }
 }
        static void TestParseEditorConfigCodeStyleOption(string args, bool isEnabled, DiagnosticSeverity severity)
        {
            var notificationOption = NotificationOption.None;
            switch (severity)
            {
                case DiagnosticSeverity.Hidden:
                    notificationOption = NotificationOption.None;
                    break;
                case DiagnosticSeverity.Info:
                    notificationOption = NotificationOption.Suggestion;
                    break;
                case DiagnosticSeverity.Warning:
                    notificationOption = NotificationOption.Warning;
                    break;
                case DiagnosticSeverity.Error:
                    notificationOption = NotificationOption.Error;
                    break;
            }

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

            var result = CodeStyleHelpers.ParseEditorConfigCodeStyleOption(args);
            Assert.True(result.Value == isEnabled,
                        $"Expected {nameof(isEnabled)} to be {isEnabled}, was {result.Value}");
            Assert.True(result.Notification.Value == severity,
                        $"Expected {nameof(severity)} to be {severity}, was {result.Notification.Value}");
        }
 private DiagnosticDescriptor CreateDescriptorWithId(string id, LocalizableString title, LocalizableString message, DiagnosticSeverity severity, params string[] customTags)
     => new DiagnosticDescriptor(
         id, title, message,
         DiagnosticCategory.Style,
         severity,
         isEnabledByDefault: true,
         customTags: customTags);
Beispiel #13
0
 // Only the compiler creates instances.
 internal DiagnosticInfo(CommonMessageProvider messageProvider, int errorCode)
 {
     _messageProvider = messageProvider;
     _errorCode = errorCode;
     _defaultSeverity = messageProvider.GetSeverity(errorCode);
     _effectiveSeverity = _defaultSeverity;
 }
        // 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;
        }
		public Result (TextSpan region, string message, DiagnosticSeverity level, IssueMarker inspectionMark, bool underline = true)
		{
			this.Region = region;
			this.Message = message;
			this.Level = level;
			this.InspectionMark = inspectionMark;
			this.Underline = underline;
		}
Beispiel #16
0
 /// <summary>
 /// Create a DiagnosticDescriptor, which provides description about a <see cref="Diagnostic"/>.
 /// </summary>
 /// <param name="id">A unique identifier for the diagnostic. For example, code analysis diagnostic ID "CA1001".</param>
 /// <param name="description">A short localizable description of the diagnostic. For example, for CA1001: "Types that own disposable fields should be disposable".</param>
 /// <param name="messageFormat">A localizable format message string, which can be passed as the first argument to <see cref="M:System.String.Format"/> when creating the diagnostic message with this descriptor.
 /// For example, for CA1001: "Implement IDisposable on '{0}' because it creates members of the following IDisposable types: '{1}'."</param>
 /// <param name="category">The category of the diagnostic (like Design, Naming etc.). For example, for CA1001: "Microsoft.Design".</param>
 /// <param name="defaultSeverity">Default severity of the diagnostic.</param>
 public DiagnosticDescriptor(string id, string description, string messageFormat, string category, DiagnosticSeverity defaultSeverity)
 {
     this.Id = id;
     this.Description = description;
     this.Category = category;
     this.MessageFormat = messageFormat;
     this.DefaultSeverity = defaultSeverity;
 }
 private DiagnosticDescriptor CreateDiagnosticDescriptor(DiagnosticSeverity severity) =>
     new DiagnosticDescriptor(
         _diagnosticId,
         _title,
         _message,
         DiagnosticCategory.Style,
         severity,
         isEnabledByDefault: true);
 public static CodeAction Create(TextSpan textSpan, DiagnosticSeverity severity, string description, Func<CancellationToken, Task<Solution>> createChangedSolution)
 {
     if (description == null)
         throw new ArgumentNullException(nameof(description));
     if (createChangedSolution == null)
         throw new ArgumentNullException(nameof(createChangedSolution));
     return new DocumentChangeAction(textSpan, severity, description, createChangedSolution);
 }
 private static DiagnosticDescriptor CreateDiagnosticDescriptor(
     string name, string id, string category, DiagnosticSeverity defaultSeverity, bool isEnabledByDefault)
 {
     var title = GetDiagnosticResourceString(name, nameof(DiagnosticDescriptor.Title));
     var messageFormat = GetDiagnosticResourceString(name, nameof(DiagnosticDescriptor.MessageFormat));
     var description = GetDiagnosticResourceString(name, nameof(DiagnosticDescriptor.Description));
     return new DiagnosticDescriptor(id, title, messageFormat, category, defaultSeverity, isEnabledByDefault, description);
 }
 public static CodeAction Create(TextSpan textSpan, DiagnosticSeverity severity, string description, Solution changedSolution)
 {
     if (description == null)
         throw new ArgumentNullException(nameof(description));
     if (changedSolution == null)
         throw new ArgumentNullException(nameof(changedSolution));
     return new DocumentChangeAction(textSpan, severity, description, ct => Task.FromResult<Solution>(changedSolution));
 }
 public static CodeAction Create(TextSpan textSpan, DiagnosticSeverity severity, string description, Document changedDocument)
 {
     if (description == null)
         throw new ArgumentNullException("description");
     if (changedDocument == null)
         throw new ArgumentNullException("changedDocument");
     return new DocumentChangeAction(textSpan, severity, description, ct => Task.FromResult<Document>(changedDocument));
 }
Beispiel #22
0
 public NamingRule(string title, ImmutableArray<NamingRule> children, SymbolSpecification symbolSpecification, NamingStyle namingStyle, DiagnosticSeverity enforcementLevel)
 {
     Title = title;
     Children = children;
     SymbolSpecification = symbolSpecification;
     NamingStyle = namingStyle;
     EnforcementLevel = enforcementLevel;
 }
 public static CodeAction CreateInsertion(TextSpan textSpan, DiagnosticSeverity severity, string description, Func<CancellationToken, Task<InsertionResult>> createInsertion)
 {
     if (description == null)
         throw new ArgumentNullException(nameof(description));
     if (createInsertion == null)
         throw new ArgumentNullException(nameof(createInsertion));
     return new InsertionAction(textSpan, severity, description, createInsertion);
 }
 /// <summary>
 /// DiagnosticRecord: The constructor for DiagnosticRecord class.
 /// </summary>
 /// <param name="message">A string about why this diagnostic was created</param>
 /// <param name="extent">The place in the script this diagnostic refers to</param>
 /// <param name="ruleName">The name of the rule that created this diagnostic</param>
 /// <param name="severity">The severity of this diagnostic</param>
 /// <param name="scriptName">The name of the script file being analyzed</param>
 public DiagnosticRecord(string message, IScriptExtent extent, string ruleName, DiagnosticSeverity severity, string scriptName, string ruleId = null)
 {
     Message  = string.IsNullOrEmpty(message)  ? string.Empty : message;
     RuleName = string.IsNullOrEmpty(ruleName) ? string.Empty : ruleName;
     Extent   = extent;
     Severity = severity;
     ScriptName = string.IsNullOrEmpty(scriptName) ? string.Empty : scriptName;
     ruleSuppressionId = ruleId;
 }
Beispiel #25
0
        internal override Diagnostic WithSeverity(DiagnosticSeverity severity)
        {
            if (this.Severity != severity)
            {
                return new CSDiagnostic(this.Info.GetInstanceWithSeverity(severity), this.Location);
            }

            return this;
        }
 public static DiagnosticSeverity? GetWorst(this DiagnosticSeverity? value1, DiagnosticSeverity? value2) {
     if(value1 == null) {
         return value2;
     }
     if (value2 == null) {
         return value1;
     }
     return GetWorst(value1.Value, value2.Value);
 }
 internal DiagnosticResult(Type serviceType, string description, DiagnosticType diagnosticType,
     DiagnosticSeverity severity, object value)
 {
     this.ServiceType = serviceType;
     this.Description = description;
     this.DiagnosticType = diagnosticType;
     this.Severity = severity;
     this.Value = value;
 }
 internal static SimpleDiagnostic Create(string id, LocalizableString title, string category, LocalizableString message, LocalizableString description, string helpLink,
                           DiagnosticSeverity severity, DiagnosticSeverity defaultSeverity,
                           bool isEnabledByDefault, int warningLevel, Location location,
                           IEnumerable<Location> additionalLocations, IEnumerable<string> customTags)
 {
     var descriptor = new DiagnosticDescriptor(id, title, message,
          category, defaultSeverity, isEnabledByDefault, description, helpLink, customTags.ToImmutableArrayOrEmpty());
     return new SimpleDiagnostic(descriptor, severity, warningLevel, location, additionalLocations, messageArgs: null);
 }
 public TestDiagnostic(DiagnosticDescriptor descriptor, string kind, DiagnosticSeverity severity, Location location, string message, params object[] arguments)
 {
     _descriptor = descriptor;
     _kind = kind;
     _severity = severity;
     _location = location;
     _message = message;
     _arguments = arguments;
 }
Beispiel #30
0
        private DiagnosticInfo(DiagnosticInfo original, DiagnosticSeverity overridenSeverity)
        {
            _messageProvider = original.MessageProvider;
            _errorCode = original._errorCode;
            _defaultSeverity = original.DefaultSeverity;
            _arguments = original._arguments;

            _effectiveSeverity = overridenSeverity;
        }
 /// <summary>
 /// Given a message identifier (e.g., CS0219), severity, warning as error and a culture,
 /// get the entire prefix (e.g., "error CS0219: Warning as Error:" for C# or "error BC42024:" for VB) used on error messages.
 /// </summary>
 public abstract string GetMessagePrefix(string id, DiagnosticSeverity severity, bool isWarningAsError, CultureInfo culture);
 protected DiagnosticDescriptor CreateDescriptorWithTitle(LocalizableString title, DiagnosticSeverity severity, params string[] customTags)
 => CreateDescriptorWithId(DescriptorId, title, title, severity, customTags);
 // Given a message identifier (e.g., CS0219), severity, warning as error and a culture,
 // get the entire prefix (e.g., "error CS0219:" for C#) used on error messages.
 public override string GetMessagePrefix(string id, DiagnosticSeverity severity, bool isWarningAsError, CultureInfo culture)
 {
     return(String.Format(culture, "{0} {1}",
                          severity == DiagnosticSeverity.Error || isWarningAsError ? "error" : "warning",
                          id));
 }
Beispiel #34
0
        public static NotificationOption ToNotificationOption(this ReportDiagnostic reportDiagnostic, DiagnosticSeverity defaultSeverity)
        {
            switch (reportDiagnostic.WithDefaultSeverity(defaultSeverity))
            {
            case ReportDiagnostic.Error:
                return(NotificationOption.Error);

            case ReportDiagnostic.Warn:
                return(NotificationOption.Warning);

            case ReportDiagnostic.Info:
                return(NotificationOption.Suggestion);

            case ReportDiagnostic.Hidden:
                return(NotificationOption.Silent);

            case ReportDiagnostic.Suppress:
                return(NotificationOption.None);

            case ReportDiagnostic.Default:
            default:
                throw ExceptionUtilities.UnexpectedValue(reportDiagnostic);
            }
        }
 /// <summary>
 /// Returns the equivalent <see cref="ReportDiagnostic"/> for a <see cref="DiagnosticSeverity"/> value.
 /// </summary>
 /// <param name="diagnosticSeverity">The <see cref="DiagnosticSeverity"/> value.</param>
 /// <returns>
 /// The equivalent <see cref="ReportDiagnostic"/> for the <see cref="DiagnosticSeverity"/> value.
 /// </returns>
 /// <exception cref="InvalidOperationException">
 /// If <paramref name="diagnosticSeverity"/> is not one of the expected values.
 /// </exception>
 public static ReportDiagnostic ToReportDiagnostic(this DiagnosticSeverity diagnosticSeverity)
 => diagnosticSeverity switch
 {
Beispiel #36
0
 /// <summary>
 /// Create a new instance of this diagnostic with the Severity property changed.
 /// </summary>
 internal abstract Diagnostic WithSeverity(DiagnosticSeverity severity);
Beispiel #37
0
 // Create a copy of this instance with a explicit overridden severity
 internal virtual DiagnosticInfo GetInstanceWithSeverity(DiagnosticSeverity severity) => new(this, severity);
        private bool TryCheckVariableAndIfStatementForm(
            SyntaxNodeAnalysisContext syntaxContext,
            IfStatementSyntax ifStatement,
            BinaryExpressionSyntax condition,
            ExpressionStatementSyntax expressionStatement,
            InvocationExpressionSyntax invocationExpression,
            DiagnosticSeverity 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))
            {
                return(false);
            }

            var localDeclarationStatement = (LocalDeclarationStatementSyntax)previousStatement;
            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;
            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 = new List <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 #39
0
 public override string GetMessagePrefix(string id, DiagnosticSeverity severity, bool isWarningAsError, CultureInfo culture)
 {
     throw new NotImplementedException();
 }
Beispiel #40
0
 public Diagnostic(DiagnosticSeverity severity, string message);
Beispiel #41
0
 public Diagnostic(Range range, DiagnosticSeverity severity, string message, string id);
Beispiel #42
0
 internal override Diagnostic WithSeverity(DiagnosticSeverity severity)
 {
     return(new CompilerDiagnostic(_original.WithSeverity(severity), _properties));
 }
Beispiel #43
0
 private static DiagnosticDescriptor GetOrCreateDescriptor(int errorCode, DiagnosticSeverity defaultSeverity, CommonMessageProvider messageProvider) => ImmutableInterlocked.GetOrAdd(ref s_errorCodeToDescriptorMap, errorCode, code => CreateDescriptor(code, defaultSeverity, messageProvider));
Beispiel #44
0
 public FixCommand(
     FixCommandLineOptions options,
     DiagnosticSeverity severityLevel,
     IEnumerable <KeyValuePair <string, string> > diagnosticFixMap,
     IEnumerable <KeyValuePair <string, string> > diagnosticFixerMap,
     in ProjectFilter projectFilter) : base(projectFilter)
Beispiel #45
0
 private static int GetWarningLevel(DiagnosticSeverity severity)
 {
     return(severity == DiagnosticSeverity.Error ? 0 : 1);
 }
Beispiel #46
0
        /// <summary>
        /// Take a warning and return the final disposition of the given warning,
        /// based on both command line options and pragmas. The diagnostic options
        /// have precedence in the following order:
        ///     1. Warning level
        ///     2. Command line options (/nowarn, /warnaserror)
        ///     3. Editor config options (syntax tree level)
        ///     4. Global analyzer config options (compilation level)
        ///     5. Global warning level
        ///
        /// Pragmas are considered separately. If a diagnostic would not otherwise
        /// be suppressed, but is suppressed by a pragma, <paramref name="hasPragmaSuppression"/>
        /// is true but the diagnostic is not reported as suppressed.
        /// </summary>
        internal static ReportDiagnostic GetDiagnosticReport(
            DiagnosticSeverity severity,
            bool isEnabledByDefault,
            string id,
            int diagnosticWarningLevel,
            Location location,
            string category,
            int warningLevelOption,
            NullableContextOptions nullableOption,
            ReportDiagnostic generalDiagnosticOption,
            IDictionary <string, ReportDiagnostic> specificDiagnosticOptions,
            SyntaxTreeOptionsProvider?syntaxTreeOptions,
            CancellationToken cancellationToken,
            out bool hasPragmaSuppression
            )
        {
            hasPragmaSuppression = false;

            Debug.Assert(location.SourceTree is null || location.SourceTree is CSharpSyntaxTree);
            var tree     = location.SourceTree as CSharpSyntaxTree;
            var position = location.SourceSpan.Start;

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

            if (isNullableFlowAnalysisWarning)
            {
                Syntax.NullableContextState.State?warningsState = tree?.GetNullableContextState(
                    position
                    ).WarningsState;
                var nullableWarningsEnabled = warningsState switch
                {
                    Syntax.NullableContextState.State.Enabled => true,
                    Syntax.NullableContextState.State.Disabled => false,
                    Syntax.NullableContextState.State.ExplicitlyRestored
                    => nullableOption.WarningsEnabled(),
                    Syntax.NullableContextState.State.Unknown
                    => tree?.IsGeneratedCode(syntaxTreeOptions, cancellationToken) != true &&
                    nullableOption.WarningsEnabled(),
                    null => nullableOption.WarningsEnabled(),
                    _ => throw ExceptionUtilities.UnexpectedValue(warningsState)
                };

                if (!nullableWarningsEnabled)
                {
                    return(ReportDiagnostic.Suppress);
                }
            }

            // 1. Warning level
            if (diagnosticWarningLevel > warningLevelOption) // honor the warning level
            {
                return(ReportDiagnostic.Suppress);
            }

            ReportDiagnostic report;
            bool             isSpecified = false;
            bool             specifiedWarnAsErrorMinus = false;

            if (specificDiagnosticOptions.TryGetValue(id, out report))
            {
                // 2. Command line options (/nowarn, /warnaserror)
                isSpecified = true;

                // 'ReportDiagnostic.Default' is added to SpecificDiagnosticOptions for "/warnaserror-:DiagnosticId",
                if (report == ReportDiagnostic.Default)
                {
                    specifiedWarnAsErrorMinus = true;
                }
            }

            // Apply syntax tree options, if applicable.
            if (syntaxTreeOptions != null && (!isSpecified || specifiedWarnAsErrorMinus))
            {
                // 3. Editor config options (syntax tree level)
                // 4. Global analyzer config options (compilation level)
                // Do not apply config options if it is bumping a warning to an error and "/warnaserror-:DiagnosticId" was specified on the command line.
                if (
                    (
                        tree != null &&
                        syntaxTreeOptions.TryGetDiagnosticValue(
                            tree,
                            id,
                            cancellationToken,
                            out var reportFromSyntaxTreeOptions
                            ) ||
                        syntaxTreeOptions.TryGetGlobalDiagnosticValue(
                            id,
                            cancellationToken,
                            out reportFromSyntaxTreeOptions
                            )
                    ) &&
                    !(
                        specifiedWarnAsErrorMinus &&
                        severity == DiagnosticSeverity.Warning &&
                        reportFromSyntaxTreeOptions == ReportDiagnostic.Error
                        )
                    )
                {
                    isSpecified = true;
                    report      = reportFromSyntaxTreeOptions;

                    // '/warnaserror' should promote warnings configured in analyzer config to error.
                    if (
                        !specifiedWarnAsErrorMinus &&
                        report == ReportDiagnostic.Warn &&
                        generalDiagnosticOption == ReportDiagnostic.Error
                        )
                    {
                        report = ReportDiagnostic.Error;
                    }
                }
            }

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

            if (report == ReportDiagnostic.Suppress)
            {
                return(ReportDiagnostic.Suppress);
            }

            // If location.SourceTree is available, check out pragmas
            var pragmaWarningState =
                tree?.GetPragmaDirectiveWarningState(id, position)
                ?? Syntax.PragmaWarningState.Default;

            if (pragmaWarningState == Syntax.PragmaWarningState.Disabled)
            {
                hasPragmaSuppression = true;
            }

            // NOTE: this may be removed as part of https://github.com/dotnet/roslyn/issues/36550
            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);
            }

            // 5. Global options
            // 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
                        )
                    {
                        report      = ReportDiagnostic.Suppress;
                        isSpecified = true;
                    }
                    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);
            }
        }
    }
Beispiel #47
0
 internal override Diagnostic WithSeverity(DiagnosticSeverity severity)
 {
     throw new NotImplementedException();
 }
 public TestDiagnostic(string id, string kind, DiagnosticSeverity severity, Location location, string message, params object[] arguments)
     : this(new DiagnosticDescriptor(id, string.Empty, message, id, severity, isEnabledByDefault : true), kind, severity, location, message, arguments)
 {
 }
        /// <summary>
        /// Take a warning and return the final disposition of the given warning,
        /// based on both command line options and pragmas. The diagnostic options
        /// have precedence in the following order:
        ///     1. Warning level
        ///     2. Syntax tree level
        ///     3. Compilation level
        ///     4. Global warning level
        ///
        /// Pragmas are considered seperately. If a diagnostic would not otherwise
        /// be suppressed, but is suppressed by a pragma, <paramref name="hasPragmaSuppression"/>
        /// is true but the diagnostic is not reported as suppressed.
        /// </summary>
        internal static ReportDiagnostic GetDiagnosticReport(
            DiagnosticSeverity severity,
            bool isEnabledByDefault,
            string id,
            int diagnosticWarningLevel,
            Location location,
            string category,
            int warningLevelOption,
            NullableContextOptions nullableOption,
            ReportDiagnostic generalDiagnosticOption,
            IDictionary <string, ReportDiagnostic> specificDiagnosticOptions,
            out bool hasPragmaSuppression)
        {
            hasPragmaSuppression = false;

            Debug.Assert(location?.SourceTree is null || location.SourceTree is CSharpSyntaxTree);
            var tree     = location?.SourceTree as CSharpSyntaxTree;
            var position = location.SourceSpan.Start;

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

            if (isNullableFlowAnalysisWarning)
            {
                var nullableWarningsGloballyEnabled = nullableOption == NullableContextOptions.Enable || nullableOption == NullableContextOptions.Warnings;
                var nullableWarningsEnabled         = tree?.GetNullableContextState(position).WarningsState ?? nullableWarningsGloballyEnabled;
                if (!nullableWarningsEnabled)
                {
                    return(ReportDiagnostic.Suppress);
                }
            }

            // 1. Warning level
            if (diagnosticWarningLevel > warningLevelOption)  // honor the warning level
            {
                return(ReportDiagnostic.Suppress);
            }

            ReportDiagnostic report;
            bool             isSpecified = false;

            if (tree != null && tree.DiagnosticOptions.TryGetValue(id, out var treeReport))
            {
                // 2. Syntax tree level
                report      = treeReport;
                isSpecified = true;
            }
            else if (specificDiagnosticOptions.TryGetValue(id, out var specificReport))
            {
                // 3. Compilation level
                report      = specificReport;
                isSpecified = true;
            }
            else
            {
                report = isEnabledByDefault ? ReportDiagnostic.Default : ReportDiagnostic.Suppress;
            }

            if (report == ReportDiagnostic.Suppress)
            {
                return(ReportDiagnostic.Suppress);
            }

            // If location.SourceTree is available, check out pragmas
            var pragmaWarningState = tree?.GetPragmaDirectiveWarningState(id, position) ?? Syntax.PragmaWarningState.Default;

            if (pragmaWarningState == Syntax.PragmaWarningState.Disabled)
            {
                hasPragmaSuppression = true;
            }

            // NOTE: this may be removed as part of https://github.com/dotnet/roslyn/issues/36550
            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);
            }

            // 4. Global options
            // 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)
                    {
                        report = ReportDiagnostic.Suppress;
                    }
                    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);
            }
        }
 protected NRefactoryCodeAction(TextSpan textSpan, DiagnosticSeverity severity)
 {
     TextSpan = textSpan;
     Severity = severity;
 }
        /// <summary>
        /// Applies a default severity to a <see cref="ReportDiagnostic"/> value.
        /// </summary>
        /// <param name="reportDiagnostic">The <see cref="ReportDiagnostic"/> value.</param>
        /// <param name="defaultSeverity">The default severity.</param>
        /// <returns>
        /// <para>If <paramref name="reportDiagnostic"/> is <see cref="ReportDiagnostic.Default"/>, returns
        /// <paramref name="defaultSeverity"/>.</para>
        /// <para>-or-</para>
        /// <para>Otherwise, returns <paramref name="reportDiagnostic"/> if it has a non-default value.</para>
        /// </returns>
        public static ReportDiagnostic WithDefaultSeverity(this ReportDiagnostic reportDiagnostic, DiagnosticSeverity defaultSeverity)
        {
            if (reportDiagnostic != ReportDiagnostic.Default)
            {
                return(reportDiagnostic);
            }

            return(defaultSeverity.ToReportDiagnostic());
        }
Beispiel #52
0
 private static ImmutableArray <string> GetCustomTags(DiagnosticSeverity defaultSeverity)
 {
     return(defaultSeverity == DiagnosticSeverity.Error ?
            s_compilerErrorCustomTags :
            s_compilerNonErrorCustomTags);
 }
 internal override Diagnostic WithSeverity(DiagnosticSeverity severity)
 {
     return(new TestDiagnostic(_descriptor, _kind, severity, _location, _message, _arguments));
 }
 protected DiagnosticDescriptor CreateDescriptorWithId(string id, LocalizableString title, LocalizableString message, DiagnosticSeverity severity, params string[] customTags)
 => new DiagnosticDescriptor(
     id, title, message,
     DiagnosticCategory.Style,
     severity,
     isEnabledByDefault: true,
     customTags: customTags);
 private Diagnostic BuildTemplatesDiagnostic(string errorMessage, ParserRuleContext context, DiagnosticSeverity severity = DiagnosticSeverity.Error)
 {
     return(new Diagnostic(context.ConvertToRange(), errorMessage, severity, _templates.Source));
 }
Beispiel #56
0
 public NamingRule(SymbolSpecification symbolSpecification, NamingStyle namingStyle, DiagnosticSeverity enforcementLevel)
 {
     SymbolSpecification = symbolSpecification;
     NamingStyle         = namingStyle;
     EnforcementLevel    = enforcementLevel;
 }
Beispiel #57
0
 // Create a copy of this instance with a explicit overridden severity
 internal DiagnosticInfo GetInstanceWithSeverity(DiagnosticSeverity severity)
 {
     return(new DiagnosticInfo(this, severity));
 }
 public override string GetMessagePrefix(string id, DiagnosticSeverity severity, bool isWarningAsError, CultureInfo culture)
 {
     return(MessageProvider.Instance.GetMessagePrefix(id, severity, isWarningAsError, culture));
 }
Beispiel #59
0
 /// <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, DiagnosticSeverity severity) =>
 !optionValue.Value && severity != DiagnosticSeverity.Hidden;
 protected DiagnosticDescriptor CreateDescriptorWithSeverity(DiagnosticSeverity severity, params string[] customTags)
 => CreateDescriptorWithId(DescriptorId, _localizableTitle, _localizableMessage, severity, customTags);