CSharpNavigationBarItemService.cs 14.7 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Composition;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Editor.Extensibility.NavigationBar;
using Microsoft.CodeAnalysis.Editor.Implementation.NavigationBar;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Internal.Log;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Microsoft.VisualStudio.Text;
using Microsoft.VisualStudio.Text.Editor;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Editor.CSharp.NavigationBar
{
    [ExportLanguageService(typeof(INavigationBarItemService), LanguageNames.CSharp), Shared]
    internal class CSharpNavigationBarItemService : AbstractNavigationBarItemService
    {
        private static readonly SymbolDisplayFormat s_memberFormat =
            new SymbolDisplayFormat(
                genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
                memberOptions: SymbolDisplayMemberOptions.IncludeParameters |
                               SymbolDisplayMemberOptions.IncludeExplicitInterface,
                typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly,
                parameterOptions: SymbolDisplayParameterOptions.IncludeType |
                                  SymbolDisplayParameterOptions.IncludeName |
                                  SymbolDisplayParameterOptions.IncludeDefaultValue |
                                  SymbolDisplayParameterOptions.IncludeParamsRefOut,
                miscellaneousOptions: SymbolDisplayMiscellaneousOptions.UseSpecialTypes);

        public override async Task<IList<NavigationBarItem>> GetItemsAsync(Document document, CancellationToken cancellationToken)
        {
            var typesInFile = await GetTypesInFileAsync(document, cancellationToken).ConfigureAwait(false);
            var tree = await document.GetSyntaxTreeAsync(cancellationToken).ConfigureAwait(false);
            return GetMembersInTypes(tree, typesInFile, cancellationToken);
        }

        private IList<NavigationBarItem> GetMembersInTypes(
            SyntaxTree tree, IEnumerable<INamedTypeSymbol> types, CancellationToken cancellationToken)
        {
            using (Logger.LogBlock(FunctionId.NavigationBar_ItemService_GetMembersInTypes_CSharp, cancellationToken))
            {
                var typeSymbolIndexProvider = new NavigationBarSymbolIdIndexProvider(caseSensitive: true);
                var items = new List<NavigationBarItem>();

                foreach (var type in types)
                {
                    var memberSymbolIndexProvider = new NavigationBarSymbolIdIndexProvider(caseSensitive: true);

                    var memberItems = new List<NavigationBarItem>();
                    foreach (var member in type.GetMembers())
                    {
                        if (member.IsImplicitlyDeclared ||
                            member.Kind == SymbolKind.NamedType ||
                            IsAccessor(member))
                        {
                            continue;
                        }

                        var method = member as IMethodSymbol;
                        if (method != null && method.PartialImplementationPart != null)
                        {
                            memberItems.Add(CreateItemForMember(
                                method,
                                memberSymbolIndexProvider.GetIndexForSymbolId(method.GetSymbolKey()),
                                tree,
                                cancellationToken));

                            memberItems.Add(CreateItemForMember(
                                method.PartialImplementationPart,
                                memberSymbolIndexProvider.GetIndexForSymbolId(method.PartialImplementationPart.GetSymbolKey()),
                                tree,
                                cancellationToken));
                        }
                        else
                        {
                            Debug.Assert(method == null || method.PartialDefinitionPart == null, "NavBar expected GetMembers to return partial method definition parts but the implementation part was returned.");

                            memberItems.Add(CreateItemForMember(
                                member,
                                memberSymbolIndexProvider.GetIndexForSymbolId(member.GetSymbolKey()),
                                tree,
                                cancellationToken));
                        }
                    }

                    memberItems.Sort((x, y) =>
                    {
                        var textComparison = x.Text.CompareTo(y.Text);
                        return textComparison != 0 ? textComparison : x.Grayed.CompareTo(y.Grayed);
                    });

                    var symbolId = type.GetSymbolKey();
                    items.Add(new NavigationBarSymbolItem(
                        text: type.ToDisplayString(s_typeFormat),
                        glyph: type.GetGlyph(),
                        indent: 0,
                        spans: GetSpansInDocument(type, tree, cancellationToken),
                        navigationSymbolId: symbolId,
                        navigationSymbolIndex: typeSymbolIndexProvider.GetIndexForSymbolId(symbolId),
                        childItems: memberItems));
                }

                items.Sort((x1, x2) => x1.Text.CompareTo(x2.Text));
                return items;
            }
        }

        private async Task<IEnumerable<INamedTypeSymbol>> GetTypesInFileAsync(Document document, CancellationToken cancellationToken)
        {
            var semanticModel = await document.GetSemanticModelAsync(cancellationToken).ConfigureAwait(false);

            return GetTypesInFile(semanticModel, cancellationToken);
        }

        private static IEnumerable<INamedTypeSymbol> GetTypesInFile(SemanticModel semanticModel, CancellationToken cancellationToken)
        {
            using (Logger.LogBlock(FunctionId.NavigationBar_ItemService_GetTypesInFile_CSharp, cancellationToken))
            {
                var types = new HashSet<INamedTypeSymbol>();
                var nodesToVisit = new Stack<SyntaxNode>();

                nodesToVisit.Push(semanticModel.SyntaxTree.GetRoot(cancellationToken));

                while (!nodesToVisit.IsEmpty())
                {
                    if (cancellationToken.IsCancellationRequested)
                    {
                        return SpecializedCollections.EmptyEnumerable<INamedTypeSymbol>();
                    }

                    var node = nodesToVisit.Pop();

                    var type = node.TypeSwitch(
                        (BaseTypeDeclarationSyntax t) => semanticModel.GetDeclaredSymbol(t, cancellationToken),
                        (EnumDeclarationSyntax e) => semanticModel.GetDeclaredSymbol(e, cancellationToken),
                        (DelegateDeclarationSyntax d) => semanticModel.GetDeclaredSymbol(d, cancellationToken));

                    if (type != null)
                    {
                        types.Add((INamedTypeSymbol)type);
                    }

                    if (node is BaseMethodDeclarationSyntax ||
                        node is BasePropertyDeclarationSyntax ||
                        node is BaseFieldDeclarationSyntax ||
                        node is StatementSyntax ||
                        node is ExpressionSyntax)
                    {
                        // quick bail out to prevent us from creating every nodes exist in current file
                        continue;
                    }

                    foreach (var child in node.ChildNodes())
                    {
                        nodesToVisit.Push(child);
                    }
                }

                return types;
            }
        }

        private static readonly SymbolDisplayFormat s_typeFormat =
            SymbolDisplayFormat.CSharpErrorMessageFormat.AddGenericsOptions(SymbolDisplayGenericsOptions.IncludeVariance);

        private static bool IsAccessor(ISymbol member)
        {
            if (member.Kind == SymbolKind.Method)
            {
                var method = (IMethodSymbol)member;

                return method.MethodKind == MethodKind.PropertyGet || method.MethodKind == MethodKind.PropertySet;
            }

            return false;
        }

        private NavigationBarItem CreateItemForMember(ISymbol member, int symbolIndex, SyntaxTree tree, CancellationToken cancellationToken)
        {
            var spans = GetSpansInDocument(member, tree, cancellationToken);

            return new NavigationBarSymbolItem(
                member.ToDisplayString(s_memberFormat),
                member.GetGlyph(),
                spans,
                member.GetSymbolKey(),
                symbolIndex,
                grayed: spans.Count == 0);
        }

        private IList<TextSpan> GetSpansInDocument(ISymbol symbol, SyntaxTree tree, CancellationToken cancellationToken)
        {
            var spans = new List<TextSpan>();
            if (!cancellationToken.IsCancellationRequested)
            {
                if (symbol.Kind == SymbolKind.Field)
                {
                    if (symbol.ContainingType.TypeKind == TypeKind.Enum)
                    {
                        AddEnumMemberSpan(symbol, tree, spans);
                    }
                    else
                    {
                        AddFieldSpan(symbol, tree, spans);
                    }
                }
                else
                {
                    foreach (var reference in symbol.DeclaringSyntaxReferences)
                    {
                        if (reference.SyntaxTree.Equals(tree))
                        {
                            var span = reference.Span;

                            spans.Add(span);
                        }
                    }
                }
            }

            return spans;
        }

        /// <summary>
        /// Computes a span for a given field symbol, expanding to the outer 
        /// </summary>
        private static void AddFieldSpan(ISymbol symbol, SyntaxTree tree, List<TextSpan> spans)
        {
            var reference = symbol.DeclaringSyntaxReferences.FirstOrDefault(r => r.SyntaxTree == tree);
            if (reference == null)
            {
                return;
            }

            var declaringNode = reference.GetSyntax();

            int spanStart = declaringNode.SpanStart;
            int spanEnd = declaringNode.Span.End;

            var fieldDeclaration = declaringNode.GetAncestor<FieldDeclarationSyntax>();
            if (fieldDeclaration != null)
            {
                var variables = fieldDeclaration.Declaration.Variables;

                if (variables.FirstOrDefault() == declaringNode)
                {
                    spanStart = fieldDeclaration.SpanStart;
                }

                if (variables.LastOrDefault() == declaringNode)
                {
                    spanEnd = fieldDeclaration.Span.End;
                }
            }

            spans.Add(TextSpan.FromBounds(spanStart, spanEnd));
        }

        private static void AddEnumMemberSpan(ISymbol symbol, SyntaxTree tree, List<TextSpan> spans)
        {
            // Ideally we want the span of this to include the trailing comma, so let's find
            // the declaration
            var reference = symbol.DeclaringSyntaxReferences.FirstOrDefault(r => r.SyntaxTree == tree);
            if (reference == null)
            {
                return;
            }

            var declaringNode = reference.GetSyntax();
            var enumMember = declaringNode as EnumMemberDeclarationSyntax;
            if (enumMember != null)
            {
                var enumDeclaration = enumMember.GetAncestor<EnumDeclarationSyntax>();

                if (enumDeclaration != null)
                {
                    var index = enumDeclaration.Members.IndexOf(enumMember);
                    if (index != -1 && index < enumDeclaration.Members.SeparatorCount)
                    {
                        // Cool, we have a comma, so do it
                        var start = enumMember.SpanStart;
                        var end = enumDeclaration.Members.GetSeparator(index).Span.End;

                        spans.Add(TextSpan.FromBounds(start, end));
                        return;
                    }
                }
            }

            spans.Add(declaringNode.Span);
        }

        protected internal override VirtualTreePoint? GetSymbolItemNavigationPoint(Document document, NavigationBarSymbolItem item, CancellationToken cancellationToken)
        {
            var compilation = document.Project.GetCompilationAsync(cancellationToken).WaitAndGetResult(cancellationToken);
304
            var symbols = item.NavigationSymbolId.Resolve(compilation, cancellationToken: cancellationToken);
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319

            var symbol = symbols.Symbol;

            if (symbol == null)
            {
                if (item.NavigationSymbolIndex < symbols.CandidateSymbols.Length)
                {
                    symbol = symbols.CandidateSymbols[item.NavigationSymbolIndex.Value];
                }
                else
                {
                    return null;
                }
            }

320 321
            var syntaxTree = document.GetSyntaxTreeSynchronously(cancellationToken);
            var location = symbol.Locations.FirstOrDefault(l => l.SourceTree.Equals(syntaxTree));
322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353

            if (location == null)
            {
                location = symbol.Locations.FirstOrDefault();
            }

            if (location == null)
            {
                return null;
            }

            return new VirtualTreePoint(location.SourceTree, location.SourceTree.GetText(cancellationToken), location.SourceSpan.Start);
        }

        [Conditional("DEBUG")]
        private static void ValidateSpanFromBounds(ITextSnapshot snapshot, int start, int end)
        {
            Contract.Requires(start >= 0 && end <= snapshot.Length && start <= end);
        }

        [Conditional("DEBUG")]
        private static void ValidateSpan(ITextSnapshot snapshot, int start, int length)
        {
            ValidateSpanFromBounds(snapshot, start, start + length);
        }

        public override void NavigateToItem(Document document, NavigationBarItem item, ITextView textView, CancellationToken cancellationToken)
        {
            NavigateToSymbolItem(document, (NavigationBarSymbolItem)item, cancellationToken);
        }
    }
}