IDefinitionsAndReferencesFactory.cs 10.3 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.Classification;
9
using Microsoft.CodeAnalysis.Completion;
10
using Microsoft.CodeAnalysis.Features.RQName;
11
using Microsoft.CodeAnalysis.FindSymbols;
12
using Microsoft.CodeAnalysis.FindUsages;
13 14
using Microsoft.CodeAnalysis.Host;
using Microsoft.CodeAnalysis.Host.Mef;
T
Tomas Matousek 已提交
15
using Microsoft.CodeAnalysis.PooledObjects;
16
using Microsoft.CodeAnalysis.Shared.Extensions;
C
CyrusNajmabadi 已提交
17
using Roslyn.Utilities;
18

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

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

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

        public static Task<DefinitionItem> ToClassifiedDefinitionItemAsync(
            this ISymbol definition,
59
            Project project,
60
            bool includeHiddenLocations,
61
            FindReferencesSearchOptions options,
62 63
            CancellationToken cancellationToken)
        {
64
            return ToDefinitionItemAsync(definition, project,
D
dotnet-bot 已提交
65
                includeHiddenLocations, includeClassifiedSpans: true,
66
                options, cancellationToken);
67 68 69
        }

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

85
            var displayParts = definition.ToDisplayParts(GetFormat(definition)).ToTaggedText();
86
            var nameDisplayParts = definition.ToDisplayParts(s_namePartsFormat).ToTaggedText();
87

88
            var tags = GlyphTags.GetTags(definition.GetGlyph());
89
            var displayIfNoReferences = definition.ShouldShowWithNoReferenceLocations(
90
                options, showMetadataSymbolsWithoutReferences: false);
91

92
            var sourceLocations = ArrayBuilder<DocumentSpan>.GetInstance();
93 94

            var properties = GetProperties(definition);
95

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

117
                        var document = project.Solution.GetDocument(location.SourceTree);
C
CyrusNajmabadi 已提交
118
                        if (document != null)
119
                        {
120 121
                            var documentLocation = !includeClassifiedSpans
                                ? new DocumentSpan(document, location.SourceSpan)
122
                                : await ClassifiedSpansAndHighlightSpanFactory.GetClassifiedDocumentSpanAsync(
123
                                    document, location.SourceSpan, cancellationToken).ConfigureAwait(false);
C
CyrusNajmabadi 已提交
124 125

                            sourceLocations.Add(documentLocation);
126 127 128 129 130
                        }
                    }
                }
            }

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

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

170
        public static async Task<SourceReferenceItem> TryCreateSourceReferenceItemAsync(
171
            this ReferenceLocation referenceLocation,
172
            DefinitionItem definitionItem,
173 174
            bool includeHiddenLocations,
            CancellationToken cancellationToken)
175
        {
176
            var location = referenceLocation.Location;
177

C
CyrusNajmabadi 已提交
178
            Debug.Assert(location.IsInSource);
179 180
            if (!location.IsVisibleSourceLocation() &&
                !includeHiddenLocations)
181 182
            {
                return null;
183
            }
184

185 186 187
            var document = referenceLocation.Document;
            var sourceSpan = location.SourceSpan;

188
            var documentSpan = await ClassifiedSpansAndHighlightSpanFactory.GetClassifiedDocumentSpanAsync(
189 190
                document, sourceSpan, cancellationToken).ConfigureAwait(false);

191
            return new SourceReferenceItem(definitionItem, documentSpan, referenceLocation.SymbolUsageInfo);
192
        }
C
CyrusNajmabadi 已提交
193

194 195 196 197 198 199 200
        private static SymbolDisplayFormat GetFormat(ISymbol definition)
        {
            return definition.Kind == SymbolKind.Parameter
                ? s_parameterDefinitionFormat
                : s_definitionFormat;
        }

201 202
        private static readonly SymbolDisplayFormat s_namePartsFormat = new SymbolDisplayFormat(
            memberOptions: SymbolDisplayMemberOptions.IncludeContainingType);
203

204
        private static readonly SymbolDisplayFormat s_definitionFormat =
C
CyrusNajmabadi 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
            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);
222 223 224

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