protected static Diagnostic[] GetSortedDiagnostics(DiagnosticAnalyzer analyzerOpt, Document[] documents, TextSpan?[] spans = null, TestValidationMode validationMode = DefaultTestValidationMode, IEnumerable <TestAdditionalDocument> additionalFiles = null)
        {
            if (analyzerOpt == null)
            {
                return(SpecializedCollections.EmptyArray <Diagnostic>());
            }

            var projects = new HashSet <Project>();

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

            var           analyzerOptions = additionalFiles != null ? new AnalyzerOptions(additionalFiles.ToImmutableArray <AdditionalText>()) : null;
            DiagnosticBag diagnostics     = DiagnosticBag.GetInstance();

            foreach (Project project in projects)
            {
                Compilation compilation = project.GetCompilationAsync().Result;
                compilation = EnableAnalyzer(analyzerOpt, compilation);

                ImmutableArray <Diagnostic> diags = compilation.GetAnalyzerDiagnostics(new[] { analyzerOpt }, validationMode, analyzerOptions);
                if (spans == null)
                {
                    diagnostics.AddRange(diags);
                }
                else
                {
                    Debug.Assert(spans.Length == documents.Length);
                    foreach (Diagnostic diag in diags)
                    {
                        if (diag.Location == Location.None || diag.Location.IsInMetadata)
                        {
                            diagnostics.Add(diag);
                        }
                        else
                        {
                            for (int i = 0; i < documents.Length; i++)
                            {
                                Document   document = documents[i];
                                SyntaxTree tree     = document.GetSyntaxTreeAsync().Result;
                                if (tree == diag.Location.SourceTree)
                                {
                                    TextSpan?span = spans[i];
                                    if (span == null || span.Value.Contains(diag.Location.SourceSpan))
                                    {
                                        diagnostics.Add(diag);
                                    }
                                }
                            }
                        }
                    }
                }
            }

            Diagnostic[] results = diagnostics.AsEnumerable().OrderBy(d => d.Location.SourceSpan.Start).ToArray();
            diagnostics.Free();
            return(results);
        }
            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 ?? SpecializedCollections.EmptyArray <object>();
                _properties          = properties ?? ImmutableDictionary <string, string> .Empty;
                _isSuppressed        = isSuppressed;
            }
Exemple #3
0
 internal RudeEditDiagnosticDescription(RudeEditKind rudeEditKind, string squiggle, string[] arguments, string firstLine)
 {
     _rudeEditKind = rudeEditKind;
     _squiggle     = squiggle;
     _firstLine    = firstLine;
     _arguments    = arguments ?? SpecializedCollections.EmptyArray <string>();
 }
Exemple #4
0
        private static IReadOnlyList <ILVisualizer.HandlerSpan> ToHandlerSpans(MetadataDecoder decoder, ImmutableArray <ExceptionRegion> entries)
        {
            if (entries.Length == 0)
            {
                return(SpecializedCollections.EmptyArray <ILVisualizer.HandlerSpan>());
            }

            var result = new List <ILVisualizer.HandlerSpan>();

            foreach (ExceptionRegion entry in entries)
            {
                int tryStartOffset = entry.TryOffset;
                int tryEndOffset   = entry.TryOffset + entry.TryLength;
                var span           = new ILVisualizer.HandlerSpan(ILVisualizer.HandlerKind.Try, null, (uint)tryStartOffset, (uint)tryEndOffset);

                if (result.Count == 0 || span.CompareTo(result[result.Count - 1]) != 0)
                {
                    result.Add(span);
                }
            }

            foreach (ExceptionRegion entry in entries)
            {
                int handlerStartOffset = entry.HandlerOffset;
                int handlerEndOffset   = entry.HandlerOffset + entry.HandlerLength;

                ILVisualizer.HandlerSpan span;
                switch (entry.Kind)
                {
                case ExceptionRegionKind.Catch:
                    var exceptionType = (Cci.ITypeReference)decoder.GetSymbolForILToken(entry.CatchType);
                    if (exceptionType == null)
                    {
                        throw new InvalidOperationException();
                    }

                    span = new ILVisualizer.HandlerSpan(ILVisualizer.HandlerKind.Catch, exceptionType, (uint)handlerStartOffset, (uint)handlerEndOffset);
                    break;

                case ExceptionRegionKind.Fault:
                    span = new ILVisualizer.HandlerSpan(ILVisualizer.HandlerKind.Fault, null, (uint)handlerStartOffset, (uint)handlerEndOffset);
                    break;

                case ExceptionRegionKind.Filter:
                    span = new ILVisualizer.HandlerSpan(ILVisualizer.HandlerKind.Filter, null, (uint)handlerStartOffset, (uint)handlerEndOffset, (uint)entry.FilterOffset);
                    break;

                case ExceptionRegionKind.Finally:
                    span = new ILVisualizer.HandlerSpan(ILVisualizer.HandlerKind.Finally, null, (uint)handlerStartOffset, (uint)handlerEndOffset);
                    break;

                default:
                    throw new InvalidOperationException();
                }

                result.Add(span);
            }

            return(result);
        }
Exemple #5
0
        /// <summary>
        /// Construct a new PatternMatcher using the specified culture.
        /// </summary>
        /// <param name="pattern">The pattern to make the pattern matcher for.</param>
        /// <param name="culture">The culture to use for string searching and comparison.</param>
        /// <param name="verbatimIdentifierPrefixIsWordCharacter">Whether to consider "@" as a word character</param>
        /// <param name="allowFuzzyMatching">Whether or not close matches should count as matches.</param>
        public PatternMatcher(
            string pattern,
            CultureInfo culture,
            bool verbatimIdentifierPrefixIsWordCharacter,
            bool allowFuzzyMatching)
        {
            pattern             = pattern.Trim();
            _compareInfo        = culture.CompareInfo;
            _allowFuzzyMatching = allowFuzzyMatching;

            _fullPatternSegment = new Segment(pattern, verbatimIdentifierPrefixIsWordCharacter, allowFuzzyMatching);

            if (pattern.IndexOf('.') < 0)
            {
                // PERF: Avoid string.Split allocations when the pattern doesn't contain a dot.
                _dotSeparatedSegments = pattern.Length > 0 ? new Segment[1] {
                    _fullPatternSegment
                } : SpecializedCollections.EmptyArray <Segment>();
            }
            else
            {
                _dotSeparatedSegments = pattern.Split(s_dotCharacterArray, StringSplitOptions.RemoveEmptyEntries)
                                        .Select(text => new Segment(text.Trim(), verbatimIdentifierPrefixIsWordCharacter, allowFuzzyMatching))
                                        .ToArray();
            }

            _invalidPattern = _dotSeparatedSegments.Length == 0 || _dotSeparatedSegments.Any(s => s.IsInvalid);
        }
        public static DiagnosticData Create(Document document, Diagnostic diagnostic)
        {
            var location = CreateLocation(document, diagnostic.Location);

            var additionalLocations = diagnostic.AdditionalLocations.Count == 0
                ? (IReadOnlyCollection <DiagnosticDataLocation>)SpecializedCollections.EmptyArray <DiagnosticDataLocation>()
                : diagnostic.AdditionalLocations.Where(loc => loc.IsInSource).Select(loc => CreateLocation(document.Project.GetDocument(loc.SourceTree), loc)).ToReadOnlyCollection();

            return(new DiagnosticData(
                       diagnostic.Id,
                       diagnostic.Descriptor.Category,
                       diagnostic.GetMessage(CultureInfo.CurrentUICulture),
                       diagnostic.GetMessage(USCultureInfo), // We use the ENU version of the message for bing search.
                       diagnostic.Severity,
                       diagnostic.DefaultSeverity,
                       diagnostic.Descriptor.IsEnabledByDefault,
                       diagnostic.WarningLevel,
                       diagnostic.Descriptor.CustomTags.AsImmutableOrEmpty(),
                       diagnostic.Properties,
                       document.Project.Solution.Workspace,
                       document.Project.Id,
                       location,
                       additionalLocations,
                       title: diagnostic.Descriptor.Title.ToString(CultureInfo.CurrentUICulture),
                       description: diagnostic.Descriptor.Description.ToString(CultureInfo.CurrentUICulture),
                       helpLink: diagnostic.Descriptor.HelpLinkUri));
        }
Exemple #7
0
        internal void TestOverloadResolutionWithDiff(string source, MetadataReference[] additionalRefs = null)
        {
            // The mechanism of this test is: we build the bound tree for the code passed in and then extract
            // from it the nodes that describe the method symbols. We then compare the description of
            // the symbols given to the comment that follows the call.

            var mscorlibRef = AssemblyMetadata.CreateFromImage(ProprietaryTestResources.NetFX.v4_0_30316_17626.mscorlib).GetReference(display: "mscorlib");
            var references = new[] { mscorlibRef }.Concat(additionalRefs ?? SpecializedCollections.EmptyArray <MetadataReference>());

            var compilation = CreateCompilation(source, references, TestOptions.ReleaseDll);

            var method      = (SourceMethodSymbol)compilation.GlobalNamespace.GetTypeMembers("C").Single().GetMembers("M").Single();
            var diagnostics = new DiagnosticBag();
            var block       = MethodCompiler.BindMethodBody(method, new TypeCompilationState(method.ContainingType, compilation, null), diagnostics);
            var tree        = BoundTreeDumperNodeProducer.MakeTree(block);
            var results     = string.Join("\n", tree.PreorderTraversal().Select(edge => edge.Value)
                                          .Where(x => x.Text == "method" && x.Value != null)
                                          .Select(x => x.Value)
                                          .ToArray());

            // var r = string.Join("\n", tree.PreorderTraversal().Select(edge => edge.Value).ToArray();

            var expected = string.Join("\n", source
                                       .Split(new[] { "\r\n" }, System.StringSplitOptions.RemoveEmptyEntries)
                                       .Where(x => x.Contains("//-"))
                                       .Select(x => x.Substring(x.IndexOf("//-") + 3))
                                       .ToArray());

            AssertEx.Equal(expected, results);
        }
Exemple #8
0
        private static string[] GetNonTypeMemberNames(
            CoreInternalSyntax.SyntaxList <Syntax.InternalSyntax.MemberDeclarationSyntax> members, ref SingleTypeDeclaration.TypeDeclarationFlags declFlags)
        {
            bool anyMethodHadExtensionSyntax = false;
            bool anyMemberHasAttributes      = false;
            bool anyNonTypeMembers           = false;

            var set = PooledHashSet <string> .GetInstance();

            foreach (var member in members)
            {
                AddNonTypeMemberNames(member, set, ref anyNonTypeMembers);

                // Check to see if any method contains a 'this' modifier on its first parameter.
                // This data is used to determine if a type needs to have its members materialized
                // as part of extension method lookup.
                if (!anyMethodHadExtensionSyntax && CheckMethodMemberForExtensionSyntax(member))
                {
                    anyMethodHadExtensionSyntax = true;
                }

                if (!anyMemberHasAttributes && CheckMemberForAttributes(member))
                {
                    anyMemberHasAttributes = true;
                }
            }

            if (anyMethodHadExtensionSyntax)
            {
                declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasExtensionMethodSyntax;
            }

            if (anyMemberHasAttributes)
            {
                declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.AnyMemberHasAttributes;
            }

            if (anyNonTypeMembers)
            {
                declFlags |= SingleTypeDeclaration.TypeDeclarationFlags.HasAnyNontypeMembers;
            }

            // PERF: The member names collection tends to be long-lived. Use a string array since
            // that uses less memory than a HashSet<string>.
            string[] result;
            if (set.Count == 0)
            {
                result = SpecializedCollections.EmptyArray <string>();
            }
            else
            {
                result = new string[set.Count];
                set.CopyTo(result);
            }

            set.Free();
            return(result);
        }
Exemple #9
0
        internal byte[] ToArray(int start, int length)
        {
            if (_length == 0)
            {
                return(SpecializedCollections.EmptyArray <byte>());
            }

            byte[] result = new byte[length];
            Array.Copy(_buffer, start, result, 0, result.Length);
            return(result);
        }
Exemple #10
0
        internal byte[] ToArray()
        {
            if (this.Length == 0)
            {
                return(SpecializedCollections.EmptyArray <byte>());
            }

            byte[] result = new byte[this.Length];
            Array.Copy(this.Buffer, result, result.Length);
            return(result);
        }
        public static ChecksumCollection GetOrCreateEmptyChecksumCollection(Serializer serializer, string kind)
        {
            var map = s_emptyChecksumCollectionCache.GetValue(serializer, s_emptyChecksumCollectionCallback);

            ChecksumCollection collection;

            if (map.TryGetValue(kind, out collection))
            {
                return(collection);
            }

            return(map.GetOrAdd(kind, _ => new ChecksumCollection(serializer, kind, SpecializedCollections.EmptyArray <object>())));
        }
Exemple #12
0
            private string GetDebuggerDisplay()
            {
#if DEBUG
                var visType = System.Type.GetType("Roslyn.Test.Utilities.ILBuilderVisualizer, Roslyn.Test.Utilities", false);
                if (visType != null)
                {
                    var method = visType.GetTypeInfo().GetDeclaredMethod("BasicBlockToString");
                    return((string)method.Invoke(this, SpecializedCollections.EmptyArray <object>()));
                }
#endif

                return("");
            }
        internal static byte[] GetPublicKey(IAssemblyName nameObject)
        {
            byte[] result = GetPropertyBytes(nameObject, PropertyId.PUBLIC_KEY);
            if (result != null)
            {
                return(result);
            }

            if (IsKeyOrTokenEmpty(nameObject, PropertyId.NULL_PUBLIC_KEY))
            {
                return(SpecializedCollections.EmptyArray <byte>());
            }

            return(null);
        }
Exemple #14
0
            private static            TextChunk[] BreakPatternIntoTextChunks(
                string pattern, bool verbatimIdentifierPrefixIsWordCharacter, bool allowFuzzyMatching)
            {
                int partCount = CountTextChunks(pattern, verbatimIdentifierPrefixIsWordCharacter);

                if (partCount == 0)
                {
                    return(SpecializedCollections.EmptyArray <TextChunk>());
                }

                var result      = new TextChunk[partCount];
                int resultIndex = 0;
                int wordStart   = 0;
                int wordLength  = 0;

                for (int i = 0; i < pattern.Length; i++)
                {
                    var ch = pattern[i];
                    if (IsWordChar(ch, verbatimIdentifierPrefixIsWordCharacter))
                    {
                        if (wordLength++ == 0)
                        {
                            wordStart = i;
                        }
                    }
                    else
                    {
                        if (wordLength > 0)
                        {
                            result[resultIndex++] = new TextChunk(pattern.Substring(wordStart, wordLength), allowFuzzyMatching);
                            wordLength            = 0;
                        }
                    }
                }

                if (wordLength > 0)
                {
                    result[resultIndex++] = new TextChunk(pattern.Substring(wordStart, wordLength), allowFuzzyMatching);
                }

                return(result);
            }
Exemple #15
0
        private static string[] BreakPatternIntoParts(string pattern, bool verbatimIdentifierPrefixIsWordCharacter)
        {
            int partCount = CountParts(pattern, verbatimIdentifierPrefixIsWordCharacter);

            if (partCount == 0)
            {
                return(SpecializedCollections.EmptyArray <string>());
            }

            var result      = new string[partCount];
            int resultIndex = 0;
            int wordStart   = 0;
            int wordLength  = 0;

            for (int i = 0; i < pattern.Length; i++)
            {
                var ch = pattern[i];
                if (IsWordChar(ch, verbatimIdentifierPrefixIsWordCharacter))
                {
                    if (wordLength++ == 0)
                    {
                        wordStart = i;
                    }
                }
                else
                {
                    if (wordLength > 0)
                    {
                        result[resultIndex++] = pattern.Substring(wordStart, wordLength);
                        wordLength            = 0;
                    }
                }
            }

            if (wordLength > 0)
            {
                result[resultIndex++] = pattern.Substring(wordStart, wordLength);
            }

            return(result);
        }
Exemple #16
0
            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("warningLevel");
                }

                _descriptor          = descriptor;
                _severity            = severity;
                _warningLevel        = warningLevel;
                _location            = location;
                _additionalLocations = additionalLocations == null?SpecializedCollections.EmptyReadOnlyList <Location>() : additionalLocations.ToImmutableArray();

                _messageArgs = messageArgs ?? SpecializedCollections.EmptyArray <object>();
            }
Exemple #17
0
        private object[] GetSelectedObjects(ISelectionContainer selectionContainer)
        {
            if (selectionContainer == null)
            {
                return(SpecializedCollections.EmptyArray <object>());
            }

            uint selectedObjectCount = 0;

            if (selectionContainer.CountObjects((uint)Constants.GETOBJS_SELECTED, out selectedObjectCount) < 0 || selectedObjectCount == 0)
            {
                return(SpecializedCollections.EmptyArray <object>());
            }

            object[] selectedObjects = new object[selectedObjectCount];
            if (selectionContainer.GetObjects((uint)Constants.GETOBJS_SELECTED, selectedObjectCount, selectedObjects) < 0)
            {
                return(SpecializedCollections.EmptyArray <object>());
            }

            return(selectedObjects);
        }
            /// <remarks>
            /// Rewrites nodes in <paramref name="nodes"/>, which is a snapshot of nodes from the original document.
            /// We're mutating the tree as we rewrite, so it's important to grab a snapshot of the
            /// nodes that we're going to reparent before we enumerate them.
            /// </remarks>
            private XNode[] RewriteMany(XNode[] nodes, string currentXmlFilePath, CSharpSyntaxNode originatingSyntax)
            {
                Debug.Assert(nodes != null);

                ArrayBuilder <XNode> builder = null;

                foreach (XNode child in nodes)
                {
                    if (builder == null)
                    {
                        builder = ArrayBuilder <XNode> .GetInstance();
                    }

                    builder.AddRange(Rewrite(child, currentXmlFilePath, originatingSyntax));
                }

                // Nodes returned by this method are going to be attached to a new parent, so it's
                // important that they don't already have parents.  If a node with a parent is
                // attached to a new parent, it is copied and its annotations are dropped.
                Debug.Assert(builder == null || builder.All(node => node.Parent == null));

                return(builder == null?SpecializedCollections.EmptyArray <XNode>() : builder.ToArrayAndFree());
            }
Exemple #19
0
        internal static async Task <TestWorkspace> CreateAsync(
            string language,
            CompilationOptions compilationOptions,
            ParseOptions parseOptions,
            string[] files,
            ExportProvider exportProvider,
            string[] metadataReferences = null,
            string workspaceKind        = null,
            string extension            = null,
            bool commonReferences       = true)
        {
            var documentElements = new List <XElement>();
            var index            = 1;

            if (extension == null)
            {
                extension = language == LanguageNames.CSharp
                ? CSharpExtension
                : VisualBasicExtension;
            }

            foreach (var file in files)
            {
                documentElements.Add(CreateDocumentElement(file, "test" + index++ + extension, parseOptions));
            }

            metadataReferences = metadataReferences ?? SpecializedCollections.EmptyArray <string>();
            foreach (var reference in metadataReferences)
            {
                documentElements.Add(CreateMetadataReference(reference));
            }

            var workspaceElement = CreateWorkspaceElement(
                CreateProjectElement(compilationOptions?.ModuleName ?? "Test", language, commonReferences, parseOptions, compilationOptions, documentElements));

            return(await CreateAsync(workspaceElement, exportProvider : exportProvider, workspaceKind : workspaceKind));
        }
Exemple #20
0
        private LocalizableResourceString(ObjectReader reader)
        {
            _resourceSource            = (Type)reader.ReadValue();
            _nameOfLocalizableResource = reader.ReadString();
            _resourceManager           = new ResourceManager(_resourceSource);

            var length = (int)reader.ReadCompressedUInt();

            if (length == 0)
            {
                _formatArguments = SpecializedCollections.EmptyArray <string>();
            }
            else
            {
                var argumentsBuilder = ArrayBuilder <string> .GetInstance(length);

                for (int i = 0; i < length; i++)
                {
                    argumentsBuilder.Add(reader.ReadString());
                }

                _formatArguments = argumentsBuilder.ToArrayAndFree();
            }
        }
        public FileSystemCompletionHelper(
            CompletionProvider completionProvider,
            TextSpan textChangeSpan,
            ICurrentWorkingDirectoryDiscoveryService fileSystemDiscoveryService,
            Glyph folderGlyph,
            Glyph fileGlyph,
            ImmutableArray <string> searchPaths,
            IEnumerable <string> allowableExtensions,
            Func <string, bool> exclude   = null,
            CompletionItemRules itemRules = null)
        {
            Debug.Assert(searchPaths.All(path => PathUtilities.IsAbsolute(path)));

            _completionProvider         = completionProvider;
            _textChangeSpan             = textChangeSpan;
            _searchPaths                = searchPaths;
            _allowableExtensions        = allowableExtensions.Select(e => e.ToLowerInvariant()).ToSet();
            _fileSystemDiscoveryService = fileSystemDiscoveryService;
            _folderGlyph                = folderGlyph;
            _fileGlyph = fileGlyph;
            _exclude   = exclude;
            _itemRules = itemRules;

            _lazyGetDrives = new Lazy <string[]>(() =>
                                                 IOUtilities.PerformIO(Directory.GetLogicalDrives, SpecializedCollections.EmptyArray <string>()));
        }
Exemple #22
0
        /// <summary>
        /// OBSOLETE: Use VerifyDiagnostics from Roslyn.Compilers.CSharp.Test.Utilities instead.
        /// </summary>
        public static void VerifyErrorCodes(IEnumerable <Diagnostic> actualErrors, params ErrorDescription[] expectedErrorDesp)
        {
            if (expectedErrorDesp == null)
            {
                return;
            }

            int expectedLength = expectedErrorDesp.Length;
            int actualLength   = actualErrors.Count();

            Assert.True(
                expectedLength == actualLength,
                String.Format(
                    "ErrCount {0} != {1}{2}Actual errors are:{2}{3}",
                    expectedLength,
                    actualLength,
                    Environment.NewLine,
                    actualLength == 0 ? "<none>" : string.Join(Environment.NewLine, actualErrors)));

            var actualSortedDesp = (from ae in
                                    (from e in actualErrors
                                     let lineSpan = e.Location.GetMappedLineSpan()
                                                    select new ErrorDescription
            {
                Code = e.Code,
                Line = lineSpan.IsValid ? lineSpan.StartLinePosition.Line + 1 : 0,
                Column = lineSpan.IsValid ? lineSpan.StartLinePosition.Character + 1 : 0,
                IsWarning = e.Severity == DiagnosticSeverity.Warning,
                Parameters = (e.Arguments != null && e.Arguments.Count > 0 && e.Arguments[0] != null) ?
                             e.Arguments.Select(x => x != null ? x.ToString() : null).ToArray() : SpecializedCollections.EmptyArray <string>()
            })
                                    orderby ae.Code, ae.Line, ae.Column
                                    select ae).ToList();

            var expectedSortedDesp = (from ee in expectedErrorDesp
                                      orderby ee.Code, ee.Line, ee.Column
                                      select ee).ToList();

            int idx = 0;

            // actual >= expected
            foreach (var experr in expectedSortedDesp)
            {
                while (idx < actualSortedDesp.Count && actualSortedDesp[idx].Code < experr.Code)
                {
                    idx++;
                }

                if (idx >= actualSortedDesp.Count)
                {
                    idx = actualSortedDesp.Count - 1;
                }

                var acterr = actualSortedDesp[idx];

                Assert.Equal(experr.Code, acterr.Code);
                if (experr.Line > 0 && experr.Column > 0)
                {
                    Assert.True(experr.Line == acterr.Line, String.Format("Line {0}!={1}", experr.Line, acterr.Line));
                    Assert.True(experr.Column == acterr.Column, String.Format("Col {0}!={1}", experr.Column, acterr.Column));
                }

                Assert.Equal(experr.IsWarning, acterr.IsWarning);

                //if the expected contains parameters, validate those too.
                if (experr.Parameters != null)
                {
                    Assert.True(experr.Parameters.SequenceEqual(acterr.Parameters), String.Format("Param: {0}!={1}", experr.Parameters.Count(), acterr.Parameters.Count()));
                }

                idx++;
            }
        }
 private static FileSystemInfo[] GetFileSystemInfos(DirectoryInfo directoryInfo)
 {
     return(IOUtilities.PerformIO(directoryInfo.GetFileSystemInfos, SpecializedCollections.EmptyArray <FileSystemInfo>()));
 }
            /// <remarks>
            /// This method boils down to Rewrite(XDocument.Load(fileAttrValue).XPathSelectElements(pathAttrValue)).
            /// Everything else is error handling.
            /// </remarks>
            private XNode[] RewriteIncludeElement(XElement includeElement, string currentXmlFilePath, CSharpSyntaxNode originatingSyntax, out string commentMessage)
            {
                Location location = GetIncludeElementLocation(includeElement, ref currentXmlFilePath, ref originatingSyntax);

                Debug.Assert(originatingSyntax != null);

                bool diagnose = originatingSyntax.SyntaxTree.ReportDocumentationCommentDiagnostics();

                if (!EnterIncludeElement(location))
                {
                    // NOTE: these must exist since we're already processed this node elsewhere in the call stack.
                    XAttribute fileAttr      = includeElement.Attribute(XName.Get(DocumentationCommentXmlNames.FileAttributeName));
                    XAttribute pathAttr      = includeElement.Attribute(XName.Get(DocumentationCommentXmlNames.PathAttributeName));
                    string     filePathValue = fileAttr.Value;
                    string     xpathValue    = pathAttr.Value;

                    if (diagnose)
                    {
                        diagnostics.Add(ErrorCode.WRN_FailedInclude, location, filePathValue, xpathValue, CSharpResources.OperationCausedStackOverflow);
                    }

                    // TODO: use culture from compilation instead of invariant culture?
                    commentMessage = ErrorFacts.GetMessage(MessageID.IDS_XMLNOINCLUDE, CultureInfo.InvariantCulture);

                    // Don't inspect the children - we're already in a cycle.
                    return(new XNode[] { new XComment(commentMessage), includeElement.Copy(copyAttributeAnnotations: false) });
                }

                DiagnosticBag includeDiagnostics = DiagnosticBag.GetInstance();

                try
                {
                    XAttribute fileAttr = includeElement.Attribute(XName.Get(DocumentationCommentXmlNames.FileAttributeName));
                    XAttribute pathAttr = includeElement.Attribute(XName.Get(DocumentationCommentXmlNames.PathAttributeName));

                    bool hasFileAttribute = fileAttr != null;
                    bool hasPathAttribute = pathAttr != null;
                    if (!hasFileAttribute || !hasPathAttribute)
                    {
                        var subMessage = hasFileAttribute ? MessageID.IDS_XMLMISSINGINCLUDEPATH.Localize() : MessageID.IDS_XMLMISSINGINCLUDEFILE.Localize();
                        includeDiagnostics.Add(ErrorCode.WRN_InvalidInclude, location, subMessage);
                        commentMessage = MakeCommentMessage(location, MessageID.IDS_XMLBADINCLUDE);
                        return(null);
                    }

                    string xpathValue    = pathAttr.Value;
                    string filePathValue = fileAttr.Value;

                    var resolver = compilation.Options.XmlReferenceResolver;
                    if (resolver == null)
                    {
                        includeDiagnostics.Add(ErrorCode.WRN_FailedInclude, location, filePathValue, xpathValue, CodeAnalysisResources.XmlReferencesNotSupported);
                        commentMessage = MakeCommentMessage(location, MessageID.IDS_XMLFAILEDINCLUDE);
                        return(null);
                    }

                    string resolvedFilePath = resolver.ResolveReference(filePathValue, currentXmlFilePath);

                    if (resolvedFilePath == null)
                    {
                        // NOTE: same behavior as IOException.
                        includeDiagnostics.Add(ErrorCode.WRN_FailedInclude, location, filePathValue, xpathValue, CodeAnalysisResources.FileNotFound);
                        commentMessage = MakeCommentMessage(location, MessageID.IDS_XMLFAILEDINCLUDE);
                        return(null);
                    }

                    if (includedFileCache == null)
                    {
                        includedFileCache = new DocumentationCommentIncludeCache(resolver);
                    }

                    try
                    {
                        XDocument doc;

                        try
                        {
                            doc = includedFileCache.GetOrMakeDocument(resolvedFilePath);
                        }
                        catch (IOException e)
                        {
                            // NOTE: same behavior as resolvedFilePath == null.
                            includeDiagnostics.Add(ErrorCode.WRN_FailedInclude, location, filePathValue, xpathValue, e.Message);
                            commentMessage = MakeCommentMessage(location, MessageID.IDS_XMLFAILEDINCLUDE);
                            return(null);
                        }

                        Debug.Assert(doc != null);

                        string     errorMessage;
                        bool       invalidXPath;
                        XElement[] loadedElements = XmlUtilities.TrySelectElements(doc, xpathValue, out errorMessage, out invalidXPath);
                        if (loadedElements == null)
                        {
                            includeDiagnostics.Add(ErrorCode.WRN_FailedInclude, location, filePathValue, xpathValue, errorMessage);

                            commentMessage = MakeCommentMessage(location, MessageID.IDS_XMLFAILEDINCLUDE);
                            if (invalidXPath)
                            {
                                // leave the include node as is
                                return(null);
                            }

                            if (location.IsInSource)
                            {
                                // As in Dev11, return only the comment - drop the include element.
                                return(new XNode[] { new XComment(commentMessage) });
                            }
                            else
                            {
                                commentMessage = null;
                                return(SpecializedCollections.EmptyArray <XNode>());
                            }
                        }

                        if (loadedElements != null && loadedElements.Length > 0)
                        {
                            // change the current XML file path for nodes contained in the document:
                            XNode[] result = RewriteMany(loadedElements, resolvedFilePath, originatingSyntax);

                            // The elements could be rewritten away if they are includes that refer to invalid
                            // (but existing and accessible) XML files.  If this occurs, behave as if we
                            // had failed to find any XPath results (as in Dev11).
                            if (result.Length > 0)
                            {
                                // NOTE: in this case, we do NOT visit the children of the include element -
                                // they are dropped.
                                commentMessage = null;
                                return(result);
                            }
                        }

                        commentMessage = MakeCommentMessage(location, MessageID.IDS_XMLNOINCLUDE);
                        return(null);
                    }
                    catch (XmlException e)
                    {
                        // NOTE: invalid XML is handled differently from other errors - we don't include the include element
                        // in the results and the location is in the included (vs includING) file.

                        Location errorLocation = XmlLocation.Create(e, resolvedFilePath);
                        includeDiagnostics.Add(ErrorCode.WRN_XMLParseIncludeError, errorLocation, GetDescription(e)); //NOTE: location is in included file.

                        if (location.IsInSource)
                        {
                            commentMessage = string.Format(ErrorFacts.GetMessage(MessageID.IDS_XMLIGNORED2, CultureInfo.InvariantCulture), resolvedFilePath);

                            // As in Dev11, return only the comment - drop the include element.
                            return(new XNode[] { new XComment(commentMessage) });
                        }
                        else
                        {
                            commentMessage = null;
                            return(SpecializedCollections.EmptyArray <XNode>());
                        }
                    }
                }
                finally
                {
                    if (diagnose)
                    {
                        diagnostics.AddRange(includeDiagnostics);
                    }

                    includeDiagnostics.Free();

                    LeaveIncludeElement(location);
                }
            }
Exemple #25
0
 // Construct a list with no sequence points.
 private SequencePointList()
 {
     _points = SpecializedCollections.EmptyArray <OffsetAndSpan>();
 }
Exemple #26
0
 // Create a copy of this instance with a WarningAsError flag
 internal virtual DiagnosticInfo GetInstanceWithReportWarning(bool isWarningAsError)
 {
     return(new DiagnosticInfo(this.messageProvider, isWarningAsError, this.errorCode, this.arguments == null ? SpecializedCollections.EmptyArray <object>() : this.arguments));
 }
Exemple #27
0
 public static int Main(string[] args)
 => Main(args, SpecializedCollections.EmptyArray <string>());
Exemple #28
0
 internal SyntaxAnnotation[] GetAnnotations()
 {
     SyntaxAnnotation[] annotations;
     annotationsTable.TryGetValue(this, out annotations);
     return(annotations ?? SpecializedCollections.EmptyArray <SyntaxAnnotation>());
 }
Exemple #29
0
        public static Task <ChecksumCollection> GetOrCreateEmptyChecksumCollection(Serializer serializer, string kind)
        {
            var map = s_emptyChecksumCollectionTaskCache.GetValue(serializer, s_emptyChecksumCollectionCallback);

            Task <ChecksumCollection> task;

            if (map.TryGetValue(kind, out task))
            {
                return(task);
            }

            return(map.GetOrAdd(kind, _ => Task.FromResult(new ChecksumCollection(serializer, kind, SpecializedCollections.EmptyArray <object>()))));
        }
Exemple #30
0
 internal CSDiagnosticInfo(ErrorCode code)
     : this(code, SpecializedCollections.EmptyArray <object>(), ImmutableArray <Symbol> .Empty, ImmutableArray <Location> .Empty)
 {
 }