IDefinitionsAndReferencesFactory.cs 9.9 KB
Newer Older
1 2
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

3
using System.Collections.Immutable;
4
using System.Composition;
C
CyrusNajmabadi 已提交
5
using System.Diagnostics;
6
using System.Threading;
7
using System.Threading.Tasks;
8
using Microsoft.CodeAnalysis.Completion;
9
using Microsoft.CodeAnalysis.Features.RQName;
10
using Microsoft.CodeAnalysis.FindSymbols;
11
using Microsoft.CodeAnalysis.FindUsages;
12 13 14 15
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
using Microsoft.CodeAnalysis.Shared.Extensions;

16
namespace Microsoft.CodeAnalysis.Editor.FindUsages
17 18 19
{
    internal interface IDefinitionsAndReferencesFactory : IWorkspaceService
    {
20
        DefinitionItem GetThirdPartyDefinitionItem(
21
            Solution solution, DefinitionItem definitionItem, CancellationToken cancellationToken);
22 23 24 25 26
    }

    [ExportWorkspaceService(typeof(IDefinitionsAndReferencesFactory)), Shared]
    internal class DefaultDefinitionsAndReferencesFactory : IDefinitionsAndReferencesFactory
    {
C
CyrusNajmabadi 已提交
27 28 29 30
        /// <summary>
        /// Provides an extension point that allows for other workspace layers to add additional
        /// results to the results found by the FindReferences engine.
        /// </summary>
31
        public virtual DefinitionItem GetThirdPartyDefinitionItem(
32
            Solution solution, DefinitionItem definitionItem, CancellationToken cancellationToken)
33 34 35
        {
            return null;
        }
36
    }
37

38 39
    internal static class DefinitionItemExtensions
    {
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
        public static DefinitionItem ToNonClassifiedDefinitionItem(
            this ISymbol definition,
            Solution solution,
            bool includeHiddenLocations)
        {
            // Because we're passing in 'false' for 'includeClassifiedSpans', this won't ever have
            // to actually do async work.  This is because the only asynchrony is when we are trying
            // to compute the classified spans for the locations of the definition.  So it's totally 
            // fine to pass in CancellationToken.None and block on the result.
            return ToDefinitionItemAsync(definition, solution, includeHiddenLocations,
                includeClassifiedSpans: false, cancellationToken: CancellationToken.None).Result;
        }

        public static Task<DefinitionItem> ToClassifiedDefinitionItemAsync(
            this ISymbol definition,
            Solution solution,
            bool includeHiddenLocations,
            CancellationToken cancellationToken)
        {
            return ToDefinitionItemAsync(definition, solution,
                includeHiddenLocations, includeClassifiedSpans: true, cancellationToken: cancellationToken);
        }


        private static async Task<DefinitionItem> ToDefinitionItemAsync(
65
            this ISymbol definition,
66
            Solution solution,
67
            bool includeHiddenLocations,
68
            bool includeClassifiedSpans,
C
CyrusNajmabadi 已提交
69
            CancellationToken cancellationToken)
70
        {
71 72 73 74 75 76 77 78
            // Ensure we're working with the original definition for the symbol. I.e. When we're 
            // creating definition items, we want to create them for types like Dictionary<TKey,TValue>
            // not some random instantiation of that type.  
            //
            // This ensures that the type will both display properly to the user, as well as ensuring
            // that we can accurately resolve the type later on when we try to navigate to it.
            definition = definition.OriginalDefinition;

79
            var displayParts = definition.ToDisplayParts(GetFormat(definition)).ToTaggedText();
80
            var nameDisplayParts = definition.ToDisplayParts(s_namePartsFormat).ToTaggedText();
81

82
            var tags = GlyphTags.GetTags(definition.GetGlyph());
83 84
            var displayIfNoReferences = definition.ShouldShowWithNoReferenceLocations(
                showMetadataSymbolsWithoutReferences: false);
85

86
            var sourceLocations = ArrayBuilder<DocumentSpan>.GetInstance();
87 88

            var properties = GetProperties(definition);
89

90
            // If it's a namespace, don't create any normal location.  Namespaces
C
CyrusNajmabadi 已提交
91 92 93
            // come from many different sources, but we'll only show a single 
            // root definition node for it.  That node won't be navigable.
            if (definition.Kind != SymbolKind.Namespace)
94
            {
C
CyrusNajmabadi 已提交
95
                foreach (var location in definition.Locations)
96
                {
C
CyrusNajmabadi 已提交
97
                    if (location.IsInMetadata)
98
                    {
99
                        return DefinitionItem.CreateMetadataDefinition(
100
                            tags, displayParts, nameDisplayParts, solution, 
101
                            definition, properties, displayIfNoReferences);
102
                    }
103
                    else if (location.IsInSource)
104
                    {
105 106 107 108 109 110
                        if (!location.IsVisibleSourceLocation() &&
                            !includeHiddenLocations)
                        {
                            continue;
                        }

C
CyrusNajmabadi 已提交
111 112
                        var document = solution.GetDocument(location.SourceTree);
                        if (document != null)
113
                        {
114 115 116 117
                            var documentLocation = !includeClassifiedSpans
                                ? new DocumentSpan(document, location.SourceSpan)
                                : await ClassifiedSpansAndHighlightSpan.GetClassifiedDocumentSpanAsync(
                                    document, location.SourceSpan, cancellationToken).ConfigureAwait(false);
C
CyrusNajmabadi 已提交
118 119

                            sourceLocations.Add(documentLocation);
120 121 122 123 124
                        }
                    }
                }
            }

125
            if (sourceLocations.Count == 0)
126 127 128
            {
                // If we got no definition locations, then create a sentinel one
                // that we can display but which will not allow navigation.
129
                return DefinitionItem.CreateNonNavigableItem(
130
                    tags, displayParts,
131
                    DefinitionItem.GetOriginationParts(definition),
132
                    properties, displayIfNoReferences);
133 134
            }

135
            return DefinitionItem.Create(
136
                tags, displayParts, sourceLocations.ToImmutableAndFree(),
137
                nameDisplayParts, properties, displayIfNoReferences);
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
        private static ImmutableDictionary<string, string> GetProperties(ISymbol definition)
        {
            var properties = ImmutableDictionary<string, string>.Empty;

            var rqName = RQNameInternal.From(definition);
            if (rqName != null)
            {
                properties = properties.Add(DefinitionItem.RQNameKey1, rqName);
            }

            if (definition?.IsConstructor() == true)
            {
                // If the symbol being considered is a constructor include the containing type in case
                // a third party wants to navigate to that.
                rqName = RQNameInternal.From(definition.ContainingType);
                if (rqName != null)
                {
                    properties = properties.Add(DefinitionItem.RQNameKey2, rqName);
                }
            }

            return properties;
        }

164
        public static async Task<SourceReferenceItem> TryCreateSourceReferenceItemAsync(
165
            this ReferenceLocation referenceLocation,
166
            DefinitionItem definitionItem,
167 168
            bool includeHiddenLocations,
            CancellationToken cancellationToken)
169
        {
170
            var location = referenceLocation.Location;
171

C
CyrusNajmabadi 已提交
172
            Debug.Assert(location.IsInSource);
173 174
            if (!location.IsVisibleSourceLocation() &&
                !includeHiddenLocations)
175 176
            {
                return null;
177
            }
178

179 180 181 182 183 184 185
            var document = referenceLocation.Document;
            var sourceSpan = location.SourceSpan;

            var documentSpan = await ClassifiedSpansAndHighlightSpan.GetClassifiedDocumentSpanAsync(
                document, sourceSpan, cancellationToken).ConfigureAwait(false);

            return new SourceReferenceItem(definitionItem, documentSpan, referenceLocation.IsWrittenTo);
186
        }
C
CyrusNajmabadi 已提交
187

188 189 190 191 192 193 194
        private static SymbolDisplayFormat GetFormat(ISymbol definition)
        {
            return definition.Kind == SymbolKind.Parameter
                ? s_parameterDefinitionFormat
                : s_definitionFormat;
        }

195 196
        private static readonly SymbolDisplayFormat s_namePartsFormat = new SymbolDisplayFormat(
            memberOptions: SymbolDisplayMemberOptions.IncludeContainingType);
197

198
        private static readonly SymbolDisplayFormat s_definitionFormat =
C
CyrusNajmabadi 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215
            new SymbolDisplayFormat(
                typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameOnly,
                genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
                parameterOptions: SymbolDisplayParameterOptions.IncludeType,
                propertyStyle: SymbolDisplayPropertyStyle.ShowReadWriteDescriptor,
                delegateStyle: SymbolDisplayDelegateStyle.NameAndSignature,
                kindOptions: SymbolDisplayKindOptions.IncludeMemberKeyword | SymbolDisplayKindOptions.IncludeNamespaceKeyword | SymbolDisplayKindOptions.IncludeTypeKeyword,
                localOptions: SymbolDisplayLocalOptions.IncludeType,
                memberOptions:
                    SymbolDisplayMemberOptions.IncludeContainingType |
                    SymbolDisplayMemberOptions.IncludeExplicitInterface |
                    SymbolDisplayMemberOptions.IncludeModifiers |
                    SymbolDisplayMemberOptions.IncludeParameters |
                    SymbolDisplayMemberOptions.IncludeType,
                miscellaneousOptions:
                    SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
                    SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
216 217 218

        private static SymbolDisplayFormat s_parameterDefinitionFormat = s_definitionFormat
            .AddParameterOptions(SymbolDisplayParameterOptions.IncludeName);
219 220
    }
}