IDefinitionsAndReferencesFactory.cs 10.1 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
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
T
Tomas Matousek 已提交
14
using Microsoft.CodeAnalysis.PooledObjects;
15
using Microsoft.CodeAnalysis.Shared.Extensions;
C
CyrusNajmabadi 已提交
16
using Roslyn.Utilities;
17

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

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

40 41
    internal static class DefinitionItemExtensions
    {
42 43
        public static DefinitionItem ToNonClassifiedDefinitionItem(
            this ISymbol definition,
44
            Project project,
45 46 47 48 49 50
            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.
51
            return ToDefinitionItemAsync(definition, project, includeHiddenLocations,
C
CyrusNajmabadi 已提交
52
                includeClassifiedSpans: false, cancellationToken: CancellationToken.None).WaitAndGetResult_CanCallOnBackground(CancellationToken.None);
53 54 55 56
        }

        public static Task<DefinitionItem> ToClassifiedDefinitionItemAsync(
            this ISymbol definition,
57
            Project project,
58 59 60
            bool includeHiddenLocations,
            CancellationToken cancellationToken)
        {
61
            return ToDefinitionItemAsync(definition, project,
62 63 64 65
                includeHiddenLocations, includeClassifiedSpans: true, cancellationToken: cancellationToken);
        }

        private static async Task<DefinitionItem> ToDefinitionItemAsync(
66
            this ISymbol definition,
67
            Project project,
68
            bool includeHiddenLocations,
69
            bool includeClassifiedSpans,
C
CyrusNajmabadi 已提交
70
            CancellationToken cancellationToken)
71
        {
72 73 74 75 76 77 78 79
            // 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;

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

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

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

            var properties = GetProperties(definition);
90

91
            // If it's a namespace, don't create any normal location.  Namespaces
C
CyrusNajmabadi 已提交
92 93 94
            // 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)
95
            {
C
CyrusNajmabadi 已提交
96
                foreach (var location in definition.Locations)
97
                {
C
CyrusNajmabadi 已提交
98
                    if (location.IsInMetadata)
99
                    {
100
                        return DefinitionItem.CreateMetadataDefinition(
101
                            tags, displayParts, nameDisplayParts, project, 
102
                            definition, properties, displayIfNoReferences);
103
                    }
104
                    else if (location.IsInSource)
105
                    {
106 107 108 109 110 111
                        if (!location.IsVisibleSourceLocation() &&
                            !includeHiddenLocations)
                        {
                            continue;
                        }

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

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

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

136
            return DefinitionItem.Create(
137
                tags, displayParts, sourceLocations.ToImmutableAndFree(),
138
                nameDisplayParts, properties, displayIfNoReferences);
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
        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;
        }

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

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

180 181 182
            var document = referenceLocation.Document;
            var sourceSpan = location.SourceSpan;

183
            var documentSpan = await ClassifiedSpansAndHighlightSpanFactory.GetClassifiedDocumentSpanAsync(
184 185 186
                document, sourceSpan, cancellationToken).ConfigureAwait(false);

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

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

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

199
        private static readonly SymbolDisplayFormat s_definitionFormat =
C
CyrusNajmabadi 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216
            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);
217 218 219

        private static SymbolDisplayFormat s_parameterDefinitionFormat = s_definitionFormat
            .AddParameterOptions(SymbolDisplayParameterOptions.IncludeName);
220
    }
T
Tomas Matousek 已提交
221
}