Exemplo n.º 1
0
 /// <summary>
 /// Add a diagnostic to the bag.
 /// </summary>
 /// <param name="diagnostics"></param>
 /// <param name="code"></param>
 /// <param name="location"></param>
 /// <param name="args"></param>
 /// <returns></returns>
 internal static CSDiagnosticInfo Add(this DiagnosticBag diagnostics, ErrorCode code, Location location, params object[] args)
 {
     var info = new CSDiagnosticInfo(code, args);
     var diag = new CSDiagnostic(info, location);
     diagnostics.Add(diag);
     return info;
 }
        private static void VerifyDiagnosticLocation(DiagnosticAnalyzer analyzer, Diagnostic diagnostic, Location actual, DiagnosticResultLocation expected)
        {
            var actualSpan = actual.GetLineSpan();

            Assert.True(actualSpan.Path == expected.Path || (actualSpan.Path != null && actualSpan.Path.Contains("Test0.") && expected.Path.Contains("Test.")),
                string.Format("Expected diagnostic to be in file \"{0}\" was actually in file \"{1}\"\r\n\r\nDiagnostic:\r\n    {2}\r\n",
                    expected.Path, actualSpan.Path, FormatDiagnostics(analyzer, diagnostic)));

            var actualLinePosition = actualSpan.StartLinePosition;

            // Only check line position if there is an actual line in the real diagnostic
            if (actualLinePosition.Line > 0)
            {
                if (actualLinePosition.Line + 1 != expected.Line)
                {
                    Assert.True(false,
                        string.Format("Expected diagnostic to be on line \"{0}\" was actually on line \"{1}\"\r\n\r\nDiagnostic:\r\n    {2}\r\n",
                            expected.Line, actualLinePosition.Line + 1, FormatDiagnostics(analyzer, diagnostic)));
                }
            }

            // Only check column position if there is an actual column position in the real diagnostic
            if (actualLinePosition.Character > 0)
            {
                if (actualLinePosition.Character + 1 != expected.Column)
                {
                    Assert.True(false,
                        string.Format("Expected diagnostic to start at column \"{0}\" was actually at column \"{1}\"\r\n\r\nDiagnostic:\r\n    {2}\r\n",
                            expected.Column, actualLinePosition.Character + 1, FormatDiagnostics(analyzer, diagnostic)));
                }
            }
        }
Exemplo n.º 3
0
 internal static CSDiagnosticInfo Add(this DiagnosticBag diagnostics, ErrorCode code, Location location, ImmutableArray<Symbol> symbols, params object[] args)
 {
     var info = new CSDiagnosticInfo(code, args, symbols, ImmutableArray<Location>.Empty);
     var diag = new CSDiagnostic(info, location);
     diagnostics.Add(diag);
     return info;
 }
Exemplo n.º 4
0
        // 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;
        }
        internal override bool EnsureSingleDefinition(Symbol symbol, string name, Location location, DiagnosticBag diagnostics)
        {
            ParameterSymbol existingDeclaration;
            var map = this.definitionMap;
            if (map != null && map.TryGetValue(name, out existingDeclaration))
            {
                return InMethodBinder.ReportConflictWithParameter(existingDeclaration, symbol, name, location, diagnostics);
            }

            return false;
        }
Exemplo n.º 6
0
        /// <returns>True if a diagnostic was reported, or would have been reported if not for
        /// the suppress flag.</returns>
        private bool ReportUnsafeIfNotAllowed(Location location, TypeSymbol sizeOfTypeOpt, DiagnosticBag diagnostics)
        {
            var diagnosticInfo = GetUnsafeDiagnosticInfo(sizeOfTypeOpt);
            if (diagnosticInfo == null || this.Flags.Includes(BinderFlags.SuppressUnsafeDiagnostics))
            {
                return false;
            }

            diagnostics.Add(new CSDiagnostic(diagnosticInfo, location));
            return true;
        }
Exemplo n.º 7
0
        internal override Diagnostic WithLocation(Location location)
        {
            if (location == null)
            {
                throw new ArgumentNullException(nameof(location));
            }

            if (location != this.Location)
            {
                return new CSDiagnostic(this.Info, location);
            }

            return this;
        }
 private Diagnostic GetUnsafeDiagnostic(Location location, TypeSymbol sizeOfTypeOpt)
 {
     if (this.IsIndirectlyInIterator)
     {
         // Spec 8.2: "An iterator block always defines a safe context, even when its declaration
         // is nested in an unsafe context."
         return new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_IllegalInnerUnsafe), location);
     }
     else if (!this.InUnsafeRegion)
     {
         return ReferenceEquals(sizeOfTypeOpt, null)
             ? new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_UnsafeNeeded), location)
             : new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_SizeofUnsafe, sizeOfTypeOpt), location);
     }
     else
     {
         return null;
     }
 }
Exemplo n.º 9
0
        internal static bool Add(
            this DiagnosticBag diagnostics,
            Location location,
            HashSet<DiagnosticInfo> useSiteDiagnostics)
        {
            if (useSiteDiagnostics.IsNullOrEmpty())
            {
                return false;
            }

            bool haveErrors = false;

            foreach (var info in useSiteDiagnostics)
            {
                if (info.Severity == DiagnosticSeverity.Error)
                {
                    haveErrors = true;
                }

                diagnostics.Add(new CSDiagnostic(info, location));
            }

            return haveErrors;
        }
        internal static bool AppendUseSiteDiagnostics(
            Location location,
            HashSet<DiagnosticInfo> useSiteDiagnostics,
            DiagnosticBag diagnostics)
        {
            if (useSiteDiagnostics.IsNullOrEmpty())
            {
                return false;
            }

            bool haveErrors = false;

            foreach (var info in useSiteDiagnostics)
            {
                if (info.Severity == DiagnosticSeverity.Error)
                {
                    haveErrors = true;
                }

                Error(diagnostics, info, location);
            }

            return haveErrors;
        }
        /// <summary>
        /// This method implements the checks in spec section 15.2.
        /// </summary>
        private bool MethodGroupIsCompatibleWithDelegate(BoundExpression receiverOpt, bool isExtensionMethod, MethodSymbol method, NamedTypeSymbol delegateType, Location errorLocation, DiagnosticBag diagnostics)
        {
            Debug.Assert(delegateType.TypeKind == TypeKind.Delegate);
            Debug.Assert((object)delegateType.DelegateInvokeMethod != null && !delegateType.DelegateInvokeMethod.HasUseSiteError,
                         "This method should only be called for valid delegate types.");

            MethodSymbol delegateMethod = delegateType.DelegateInvokeMethod;

            Debug.Assert(!isExtensionMethod || (receiverOpt != null));

            // - Argument types "match", and
            var delegateParameters = delegateMethod.Parameters;
            var methodParameters = method.Parameters;
            int numParams = delegateParameters.Length;

            if (methodParameters.Length != numParams + (isExtensionMethod ? 1 : 0))
            {
                // This can happen if "method" has optional parameters.
                Debug.Assert(methodParameters.Length > numParams + (isExtensionMethod ? 1 : 0));
                Error(diagnostics, ErrorCode.ERR_MethDelegateMismatch, errorLocation, method, delegateType);
                return false;
            }

            HashSet<DiagnosticInfo> useSiteDiagnostics = null;

            // If this is an extension method delegate, the caller should have verified the
            // receiver is compatible with the "this" parameter of the extension method.
            Debug.Assert(!isExtensionMethod ||
                (Conversions.ConvertExtensionMethodThisArg(methodParameters[0].Type, receiverOpt.Type, ref useSiteDiagnostics).Exists && useSiteDiagnostics.IsNullOrEmpty()));

            useSiteDiagnostics = null;

            for (int i = 0; i < numParams; i++)
            {
                var delegateParameterType = delegateParameters[i].Type;
                var methodParameterType = methodParameters[isExtensionMethod ? i + 1 : i].Type;

                if (!Conversions.HasIdentityOrImplicitReferenceConversion(delegateParameterType, methodParameterType, ref useSiteDiagnostics))
                {
                    // No overload for '{0}' matches delegate '{1}'
                    Error(diagnostics, ErrorCode.ERR_MethDelegateMismatch, errorLocation, method, delegateType);
                    diagnostics.Add(errorLocation, useSiteDiagnostics);
                    return false;
                }
            }

            // - Return types "match"
            var returnsMatch =
                method.ReturnsVoid && delegateMethod.ReturnsVoid ||
                Conversions.HasIdentityOrImplicitReferenceConversion(method.ReturnType, delegateMethod.ReturnType, ref useSiteDiagnostics);
            if (!returnsMatch)
            {
                Error(diagnostics, ErrorCode.ERR_BadRetType, errorLocation, method, method.ReturnType);
                diagnostics.Add(errorLocation, useSiteDiagnostics);
                return false;
            }

            diagnostics.Add(errorLocation, useSiteDiagnostics);

            if (method.IsConditional)
            {
                // CS1618: Cannot create delegate with '{0}' because it has a Conditional attribute
                Error(diagnostics, ErrorCode.ERR_DelegateOnConditional, errorLocation, method);
                return false;
            }

            var sourceMethod = method as SourceMemberMethodSymbol;
            if ((object)sourceMethod != null && sourceMethod.IsPartialWithoutImplementation)
            {
                // CS0762: Cannot create delegate from method '{0}' because it is a partial method without an implementing declaration
                Error(diagnostics, ErrorCode.ERR_PartialMethodToDelegate, errorLocation, method);
                return false;
            }

            return true;
        }
 /// <remarks>
 /// Respects the DocumentationMode at the source location.
 /// </remarks>
 private void RecordSyntaxDiagnostics(CSharpSyntaxNode treelessSyntax, Location sourceLocation)
 {
     if (treelessSyntax.ContainsDiagnostics && ((SyntaxTree)sourceLocation.SourceTree).ReportDocumentationCommentDiagnostics())
     {
         // NOTE: treelessSyntax doesn't have its own SyntaxTree, so we have to access the diagnostics
         // via the Dummy tree.
         foreach (Diagnostic diagnostic in CSharpSyntaxTree.Dummy.GetDiagnostics(treelessSyntax))
         {
             diagnostics.Add(diagnostic.WithLocation(sourceLocation));
         }
     }
 }
 /// <remarks>
 /// Respects the DocumentationMode at the source location.
 /// </remarks>
 private void RecordBindingDiagnostics(DiagnosticBag bindingDiagnostics, Location sourceLocation)
 {
     if (!bindingDiagnostics.IsEmptyWithoutResolution && ((SyntaxTree)sourceLocation.SourceTree).ReportDocumentationCommentDiagnostics())
     {
         foreach (Diagnostic diagnostic in bindingDiagnostics.AsEnumerable())
         {
             // CONSIDER: Dev11 actually uses the originating location plus the offset into the cref/name,
             // but that just seems silly.
             diagnostics.Add(diagnostic.WithLocation(sourceLocation));
         }
     }
 }
            private bool EnterIncludeElement(Location location)
            {
                if (this.inProgressIncludeElementNodes == null)
                {
                    this.inProgressIncludeElementNodes = new HashSet<Location>();
                }

                return this.inProgressIncludeElementNodes.Add(location);
            }
 private bool LeaveIncludeElement(Location location)
 {
     Debug.Assert(this.inProgressIncludeElementNodes != null);
     bool result = this.inProgressIncludeElementNodes.Remove(location);
     Debug.Assert(result);
     return result;
 }
Exemplo n.º 16
0
 public override Diagnostic CreateDiagnostic(int code, Location location, params object[] args)
 {
     var info = new CSDiagnosticInfo((ErrorCode)code, args, ImmutableArray<Symbol>.Empty, ImmutableArray<Location>.Empty);
     return new CSDiagnostic(info, location);
 }
 private string MakeCommentMessage(Location location, MessageID messageId)
 {
     if (location.IsInSource)
     {
         // TODO: use culture from compilation instead of invariant culture?
         return ErrorFacts.GetMessage(messageId, CultureInfo.InvariantCulture);
     }
     else
     {
         return null;
     }
 }
Exemplo n.º 18
0
        internal static bool ReportConflictWithParameter(Symbol parameter, Symbol newSymbol, string name, Location newLocation, DiagnosticBag diagnostics)
        {
            var oldLocation = parameter.Locations[0];

#if PATTERNS_FIXED
            Debug.Assert(oldLocation != newLocation || oldLocation == Location.None || newLocation.SourceTree?.GetRoot().ContainsDiagnostics == true,
                         "same nonempty location refers to different symbols?");
#else
            if (oldLocation == newLocation)
            {
                return(false);
            }
#endif
            SymbolKind parameterKind = parameter.Kind;

            // Quirk of the way we represent lambda parameters.
            SymbolKind newSymbolKind = (object)newSymbol == null ? SymbolKind.Parameter : newSymbol.Kind;

            if (newSymbolKind == SymbolKind.ErrorType)
            {
                return(true);
            }

            if (parameterKind == SymbolKind.Parameter)
            {
                if (newSymbolKind == SymbolKind.Parameter || newSymbolKind == SymbolKind.Local ||
                    (newSymbolKind == SymbolKind.Method &&
                     ((MethodSymbol)newSymbol).MethodKind == MethodKind.LocalFunction))
                {
                    // A local or parameter named '{0}' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
                    diagnostics.Add(ErrorCode.ERR_LocalIllegallyOverrides, newLocation, name);
                    return(true);
                }

                if (newSymbolKind == SymbolKind.RangeVariable)
                {
                    // The range variable '{0}' conflicts with a previous declaration of '{0}'
                    diagnostics.Add(ErrorCode.ERR_QueryRangeVariableOverrides, newLocation, name);
                    return(true);
                }
            }

            if (parameterKind == SymbolKind.TypeParameter)
            {
                if (newSymbolKind == SymbolKind.Parameter || newSymbolKind == SymbolKind.Local ||
                    (newSymbolKind == SymbolKind.Method &&
                     ((MethodSymbol)newSymbol).MethodKind == MethodKind.LocalFunction))
                {
                    // CS0412: '{0}': a parameter, local variable, or local function cannot have the same name as a method type parameter
                    diagnostics.Add(ErrorCode.ERR_LocalSameNameAsTypeParam, newLocation, name);
                    return(true);
                }

                if (newSymbolKind == SymbolKind.TypeParameter)
                {
                    // Type parameter declaration name conflicts are detected elsewhere
                    return(false);
                }

                if (newSymbolKind == SymbolKind.RangeVariable)
                {
                    // The range variable '{0}' cannot have the same name as a method type parameter
                    diagnostics.Add(ErrorCode.ERR_QueryRangeVariableSameAsTypeParam, newLocation, name);
                    return(true);
                }
            }

            Debug.Assert(false, "what else could be defined in a method?");
            return(true);
        }
Exemplo n.º 19
0
 public override void ReportDuplicateMetadataReferenceWeak(DiagnosticBag diagnostics, Location location, MetadataReference reference, AssemblyIdentity identity, MetadataReference equivalentReference, AssemblyIdentity equivalentIdentity)
 {
     diagnostics.Add(ErrorCode.ERR_DuplicateImportSimple, location,
         identity.Name,
         reference.Display ?? identity.GetDisplayName());
 }
Exemplo n.º 20
0
        /// <summary>
        /// Report diagnostics that should be reported when using a synthesized attribute. 
        /// </summary>
        internal static void ReportUseSiteDiagnosticForSynthesizedAttribute(
            CSharpCompilation compilation,
            WellKnownMember attributeMember,
            DiagnosticBag diagnostics,
            Location location = null,
            CSharpSyntaxNode syntax = null)
        {
            Debug.Assert((location != null) ^ (syntax != null));

            // Dev11 reports use-site diagnostics when an optional attribute is found but is bad for some other reason 
            // (comes from an unified assembly). When the symbol is not found no error is reported. See test VersionUnification_UseSiteDiagnostics_OptionalAttributes.
            bool isOptional = WellKnownMembers.IsSynthesizedAttributeOptional(attributeMember);

            GetWellKnownTypeMember(compilation, attributeMember, diagnostics, location, syntax, isOptional);
        }
        internal override int CompareSourceLocations(Location loc1, Location loc2)
        {
            Debug.Assert(loc1.IsInSource);
            Debug.Assert(loc2.IsInSource);

            var comparison = CompareSyntaxTreeOrdering(loc1.SourceTree, loc2.SourceTree);
            if (comparison != 0)
            {
                return comparison;
            }

            return loc1.SourceSpan.Start - loc2.SourceSpan.Start;
        }
Exemplo n.º 22
0
 internal static void Error(DiagnosticBag diagnostics, ErrorCode code, Location location)
 {
     diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(code), location));
 }
        /// <summary>
        /// This method is a wrapper around MethodGroupConversionHasErrors.  As a preliminary step,
        /// it checks whether a conversion exists.
        /// </summary>
        private bool MethodGroupConversionDoesNotExistOrHasErrors(
            BoundMethodGroup boundMethodGroup,
            NamedTypeSymbol delegateType,
            Location delegateMismatchLocation,
            DiagnosticBag diagnostics,
            out Conversion conversion)
        {
            if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, delegateType, delegateMismatchLocation))
            {
                conversion = Conversion.NoConversion;
                return true;
            }

            HashSet<DiagnosticInfo> useSiteDiagnostics = null;
            conversion = Conversions.GetMethodGroupConversion(boundMethodGroup, delegateType, ref useSiteDiagnostics);
            diagnostics.Add(delegateMismatchLocation, useSiteDiagnostics);
            if (!conversion.Exists)
            {
                // No overload for '{0}' matches delegate '{1}'
                diagnostics.Add(ErrorCode.ERR_MethDelegateMismatch, delegateMismatchLocation, boundMethodGroup.Name, delegateType);
                return true;
            }
            else
            {
                Debug.Assert(conversion.IsValid); // i.e. if it exists, then it is valid.
                // Only cares about nullness and type of receiver, so no need to worry about BoundTypeOrValueExpression.
                return this.MethodGroupConversionHasErrors(boundMethodGroup.Syntax, conversion, boundMethodGroup.ReceiverOpt, conversion.IsExtensionMethod, delegateType, diagnostics);
            }
        }
Exemplo n.º 24
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,
            NullableContextOptions 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 isNullableFlowAnalysisSafetyWarning    = ErrorFacts.NullableFlowAnalysisSafetyWarnings.Contains(id);
            bool isNullableFlowAnalysisNonSafetyWarning = ErrorFacts.NullableFlowAnalysisNonSafetyWarnings.Contains(id);

            Debug.Assert(!isNullableFlowAnalysisSafetyWarning || !isNullableFlowAnalysisNonSafetyWarning);

            if (report == ReportDiagnostic.Suppress && // check options (/nowarn)
                !isNullableFlowAnalysisSafetyWarning && !isNullableFlowAnalysisNonSafetyWarning)
            {
                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.
            switch (nullableOption)
            {
            case NullableContextOptions.Disabled:
                if (isNullableFlowAnalysisSafetyWarning || isNullableFlowAnalysisNonSafetyWarning)
                {
                    return(ReportDiagnostic.Suppress);
                }
                break;

            case NullableContextOptions.SafeOnly:
                if (isNullableFlowAnalysisNonSafetyWarning)
                {
                    return(ReportDiagnostic.Suppress);
                }
                break;
            }

            // 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);
            }
        }
Exemplo n.º 25
0
        internal static bool CheckFeatureAvailability(this MessageID feature, DiagnosticBag diagnostics, Location errorLocation)
        {
            var diag = GetFeatureAvailabilityDiagnosticInfoOpt(feature, (CSharpParseOptions)errorLocation.SourceTree.Options);

            if (!(diag is null))
            {
                diagnostics.Add(diag, errorLocation);
                return(false);
            }
            return(true);
        }
Exemplo n.º 26
0
        public override Diagnostic CreateDiagnostic(int code, Location location, params object[] args)
        {
            var info = new CSDiagnosticInfo((ErrorCode)code, args, ImmutableArray <Symbol> .Empty, ImmutableArray <Location> .Empty);

            return(new CSDiagnostic(info, location));
        }
Exemplo n.º 27
0
 internal static void Error(DiagnosticBag diagnostics, DiagnosticInfo info, Location location)
 {
     diagnostics.Add(new CSDiagnostic(info, location));
 }
Exemplo n.º 28
0
        protected override void ReportUnassignedOutParameter(
            ParameterSymbol parameter,
            SyntaxNode node,
            Location location)
        {
            if (node != null && node is ReturnStatementSyntax && RegionContains(node.Span))
            {
                _dataFlowsIn.Add(parameter);
            }

            base.ReportUnassignedOutParameter(parameter, node, location);
        }
Exemplo n.º 29
0
 internal static void Error(DiagnosticBag diagnostics, ErrorCode code, Location location, params object[] args)
 {
     diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(code, args), location));
 }
Exemplo n.º 30
0
 private bool ValidateLambdaParameterNameConflictsInScope(Location location, string name, DiagnosticBag diagnostics)
 {
     return ValidateNameConflictsInScope(null, location, name, diagnostics);
 }
Exemplo n.º 31
0
 protected override void ReportUnassignedOutParameter(ParameterSymbol parameter, CSharpSyntaxNode node, Location location)
 {
     if (!dataFlowsOut.Contains(parameter) && (node == null || node is ReturnStatementSyntax))
     {
         dataFlowsOut.Add(parameter);
     }
     base.ReportUnassignedOutParameter(parameter, node, location);
 }
Exemplo n.º 32
0
        /// <remarks>
        /// Don't call this one directly - call one of the helpers.
        /// </remarks>
        protected bool ValidateNameConflictsInScope(Symbol symbol, Location location, string name, DiagnosticBag diagnostics)
        {
            if (string.IsNullOrEmpty(name))
            {
                return false;
            }

            bool error = false;
            for (Binder binder = this; binder != null; binder = binder.Next)
            {
                // no local scopes enclose members
                if (binder is InContainerBinder || error)
                {
                    break;
                }

                var scope = binder as LocalScopeBinder;
                if (scope != null)
                {
                    error |= scope.EnsureSingleDefinition(symbol, name, location, diagnostics);
                }
            }

            return error;
        }
Exemplo n.º 33
0
 protected override bool EnsureInvariantMeaningInScope(Symbol symbol, Location location, string name, DiagnosticBag diagnostics, Symbol colorColorVariable = null)
 {
     // This should never happen in the batch compiler, but it may occur as a result of API accesses
     // (if there's no LocalScopeBinder or other overrider in the chain).  Just indicate that no errors
     // need to be reported.
     return false;
 }
Exemplo n.º 34
0
 protected override void ReportUnassignedOutParameter(ParameterSymbol parameter, SyntaxNode node, Location location)
 {
     _result.Add(parameter);
     base.ReportUnassignedOutParameter(parameter, node, location);
 }