AbstractTypeImportCompletionService.cs 15.5 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
// 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;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.FindSymbols;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Shared.Extensions.ContextQuery;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.Completion.Providers.ImportCompletion
{
    internal abstract partial class AbstractTypeImportCompletionService : ITypeImportCompletionService
    {
        private ITypeImportCompletionCacheService CacheService { get; }

        protected abstract string GenericTypeSuffix { get; }

        protected abstract bool IsCaseSensitive { get; }

        internal AbstractTypeImportCompletionService(Workspace workspace)
        {
            CacheService = workspace.Services.GetService<ITypeImportCompletionCacheService>();
        }

        public async Task GetTopLevelTypesAsync(
            Project project,
            SyntaxContext syntaxContext,
33
            Action<CompletionItem, bool> handleItem,
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
            CancellationToken cancellationToken)
        {
            if (!project.SupportsCompilation)
            {
                throw new ArgumentException(nameof(project));
            }

            var compilation = await project.GetCompilationAsync(cancellationToken).ConfigureAwait(false);

            // Since we only need top level types from source, therefore we only care if source symbol checksum changes.
            var checksum = await SymbolTreeInfo.GetSourceSymbolsChecksumAsync(project, cancellationToken).ConfigureAwait(false);

            GetAccessibleTopLevelTypesWorker(
                project.Id,
                compilation.Assembly,
                checksum,
                syntaxContext,
                handleItem,
                CacheService.ProjectItemsCache,
                cancellationToken);
        }

        public void GetTopLevelTypesFromPEReference(
            Solution solution,
            Compilation compilation,
            PortableExecutableReference peReference,
            SyntaxContext syntaxContext,
61
            Action<CompletionItem, bool> handleItem,
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
            CancellationToken cancellationToken)
        {
            var key = GetReferenceKey(peReference);
            if (key == null)
            {
                // Can't cache items for reference with null key. We don't want risk potential perf regression by 
                // making those items repeatedly, so simply not returning anything from this assembly, until 
                // we have a better understanding on this sceanrio.
                // TODO: Add telemetry
                return;
            }

            if (!(compilation.GetAssemblyOrModuleSymbol(peReference) is IAssemblySymbol assemblySymbol))
            {
                return;
            }

            var checksum = SymbolTreeInfo.GetMetadataChecksum(solution, peReference, cancellationToken);
            GetAccessibleTopLevelTypesWorker(
                key,
                assemblySymbol,
                checksum,
                syntaxContext,
                handleItem,
                CacheService.PEItemsCache,
                cancellationToken);

            return;

            static string GetReferenceKey(PortableExecutableReference reference)
                => reference.FilePath ?? reference.Display;
        }

        private void GetAccessibleTopLevelTypesWorker<TKey>(
            TKey key,
            IAssemblySymbol assembly,
            Checksum checksum,
            SyntaxContext syntaxContext,
100
            Action<CompletionItem, bool> handleItem,
101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
            IDictionary<TKey, ReferenceCacheEntry> cache,
            CancellationToken cancellationToken)
        {
            var language = syntaxContext.SemanticModel.Language;

            // Cache miss, create all requested items.
            if (!cache.TryGetValue(key, out var cacheEntry) ||
                cacheEntry.Checksum != checksum)
            {
                var builder = new ReferenceCacheEntry.Builder(checksum, language, GenericTypeSuffix);
                GetCompletionItemsForTopLevelTypeDeclarations(assembly.GlobalNamespace, builder, cancellationToken);
                cacheEntry = builder.ToReferenceCacheEntry();
                cache[key] = cacheEntry;
            }

116
            foreach (var itemInfo in cacheEntry.GetItemsForContext(language, GenericTypeSuffix, syntaxContext.IsAttributeNameContext, IsCaseSensitive))
117
            {
118
                handleItem(itemInfo.Item, itemInfo.IsPublic);
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
            }
        }

        private static void GetCompletionItemsForTopLevelTypeDeclarations(
            INamespaceSymbol rootNamespaceSymbol,
            ReferenceCacheEntry.Builder builder,
            CancellationToken cancellationToken)
        {
            VisitNamespace(rootNamespaceSymbol, containingNamespace: null, builder, cancellationToken);
            return;

            static void VisitNamespace(
                INamespaceSymbol symbol,
                string containingNamespace,
                ReferenceCacheEntry.Builder builder,
                CancellationToken cancellationToken)
            {
                cancellationToken.ThrowIfCancellationRequested();
                containingNamespace = ConcatNamespace(containingNamespace, symbol.Name);

                foreach (var memberNamespace in symbol.GetNamespaceMembers())
                {
                    VisitNamespace(memberNamespace, containingNamespace, builder, cancellationToken);
                }

                var overloads = PooledDictionary<string, TypeOverloadInfo>.GetInstance();
                var types = symbol.GetTypeMembers();

                // Iterate over all top level internal and public types, keep track of "type overloads".
                foreach (var type in types)
                {
                    // No need to check accessibility here, since top level types can only be internal or public.
                    if (type.CanBeReferencedByName)
                    {
                        overloads.TryGetValue(type.Name, out var overloadInfo);
                        overloads[type.Name] = overloadInfo.Aggregate(type);
                    }
                }

                foreach (var pair in overloads)
                {
                    var overloadInfo = pair.Value;

                    // Create CompletionItem for non-generic type overload, if exists.
                    if (overloadInfo.NonGenericOverload != null)
                    {
                        builder.AddItem(
                            overloadInfo.NonGenericOverload,
                            containingNamespace,
                            overloadInfo.NonGenericOverload.DeclaredAccessibility == Accessibility.Public);
                    }

                    // Create one CompletionItem for all generic type overloads, if there's any.
                    // For simplicity, we always show the type symbol with lowest arity in CompletionDescription
                    // and without displaying the total number of overloads.
                    if (overloadInfo.BestGenericOverload != null)
                    {
                        // If any of the generic overloads is public, then the completion item is considered public.
                        builder.AddItem(
                            overloadInfo.BestGenericOverload,
                            containingNamespace,
                            overloadInfo.ContainsPublicGenericOverload);
                    }
                }

                overloads.Free();
            }
        }

        private static string ConcatNamespace(string containingNamespace, string name)
        {
            Debug.Assert(name != null);
            if (string.IsNullOrEmpty(containingNamespace))
            {
                return name;
            }

            return containingNamespace + "." + name;
        }

        private readonly struct TypeOverloadInfo
        {
            public TypeOverloadInfo(INamedTypeSymbol nonGenericOverload, INamedTypeSymbol bestGenericOverload, bool containsPublicGenericOverload)
            {
                NonGenericOverload = nonGenericOverload;
                BestGenericOverload = bestGenericOverload;
                ContainsPublicGenericOverload = containsPublicGenericOverload;
            }

            public INamedTypeSymbol NonGenericOverload { get; }

            // Generic with fewest type parameters is considered best symbol to show in description.
            public INamedTypeSymbol BestGenericOverload { get; }

            public bool ContainsPublicGenericOverload { get; }

            public TypeOverloadInfo Aggregate(INamedTypeSymbol type)
            {
                if (type.Arity == 0)
                {
                    return new TypeOverloadInfo(nonGenericOverload: type, BestGenericOverload, ContainsPublicGenericOverload);
                }

                // We consider generic with fewer type parameters better symbol to show in description
                var newBestGenericOverload = BestGenericOverload == null || type.Arity < BestGenericOverload.Arity
                    ? type
                    : BestGenericOverload;

                var newContainsPublicGenericOverload = type.DeclaredAccessibility >= Accessibility.Public || ContainsPublicGenericOverload;

                return new TypeOverloadInfo(NonGenericOverload, newBestGenericOverload, newContainsPublicGenericOverload);
            }
        }
232

233 234 235 236 237 238 239 240 241 242 243 244 245 246
        private readonly struct ReferenceCacheEntry
        {
            public class Builder
            {
                private readonly string _language;
                private readonly string _genericTypeSuffix;
                private readonly Checksum _checksum;

                public Builder(Checksum checksum, string language, string genericTypeSuffix)
                {
                    _checksum = checksum;
                    _language = language;
                    _genericTypeSuffix = genericTypeSuffix;

247
                    _itemsBuilder = ArrayBuilder<TypeImportCompletionItemInfo>.GetInstance();
248 249
                }

250
                private ArrayBuilder<TypeImportCompletionItemInfo> _itemsBuilder;
251 252 253 254 255 256

                public ReferenceCacheEntry ToReferenceCacheEntry()
                {
                    return new ReferenceCacheEntry(
                        _checksum,
                        _language,
257
                        _itemsBuilder.ToImmutableAndFree());
258 259 260 261
                }

                public void AddItem(INamedTypeSymbol symbol, string containingNamespace, bool isPublic)
                {
262
                    var isGeneric = symbol.Arity > 0;
263

264
                    // Need to determine if a type is an attribute up front since we want to filter out 
265 266 267 268 269 270
                    // non-attribute types when in attribute context. We can't do this lazily since we don't hold 
                    // on to symbols. However, the cost of calling `IsAttribute` on every top-level type symbols 
                    // is prohibitively high, so we opt for the heuristic that would do the simple textual "Attribute" 
                    // suffix check first, then the more expensive symbolic check. As a result, all unimported
                    // attribute types that don't have "Attribute" suffix would be filtered out when in attribute context.
                    var isAttribute = symbol.Name.HasAttributeSuffix(isCaseSensitive: false) && symbol.IsAttribute();
271 272 273 274

                    var item = TypeImportCompletionItem.Create(symbol, containingNamespace, _genericTypeSuffix);
                    item.IsCached = true;

275
                    _itemsBuilder.Add(new TypeImportCompletionItemInfo(item, isPublic, isGeneric, isAttribute));
G
Gen Lu 已提交
276
                    return;
277 278 279 280 281 282
                }
            }

            private ReferenceCacheEntry(
                Checksum checksum,
                string language,
283
                ImmutableArray<TypeImportCompletionItemInfo> items)
284 285 286 287
            {
                Checksum = checksum;
                Language = language;

288
                ItemInfos = items;
289 290 291 292 293 294
            }

            public string Language { get; }

            public Checksum Checksum { get; }

295
            private ImmutableArray<TypeImportCompletionItemInfo> ItemInfos { get; }
296

297
            public ImmutableArray<TypeImportCompletionItemInfo> GetItemsForContext(string language, string genericTypeSuffix, bool isAttributeContext, bool isCaseSensitive)
298
            {
299 300
                var isSameLanguage = Language == language;
                if (isSameLanguage && !isAttributeContext)
301
                {
302
                    return ItemInfos;
303 304
                }

305 306
                var builder = ArrayBuilder<TypeImportCompletionItemInfo>.GetInstance();
                foreach (var info in ItemInfos)
307
                {
308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325
                    CompletionItem item = info.Item;
                    if (isAttributeContext)
                    {
                        if (!info.IsAttribute)
                        {
                            continue;
                        }

                        item = GetAppropriateAttributeItem(info.Item, isCaseSensitive);
                    }

                    if (!isSameLanguage && info.IsGeneric)
                    {
                        // We don't want to cache this item.
                        item = TypeImportCompletionItem.CreateItemWithGenericDisplaySuffix(item, genericTypeSuffix);
                    }

                    builder.Add(info.WithItem(item));
326 327
                }

328
                return builder.ToImmutableAndFree();
329

330
                static CompletionItem GetAppropriateAttributeItem(CompletionItem attributeItem, bool isCaseSensitive)
331
                {
332
                    if (attributeItem.DisplayText.TryGetWithoutAttributeSuffix(isCaseSensitive: isCaseSensitive, out var attributeNameWithoutSuffix))
333 334
                    {
                        // We don't want to cache this item.
335
                        return TypeImportCompletionItem.CreateAttributeItemWithoutSuffix(attributeItem, attributeNameWithoutSuffix);
336 337
                    }

338
                    return attributeItem;
339 340 341
                }
            }
        }
342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378

        private readonly struct TypeImportCompletionItemInfo
        {
            private readonly ItemPropertyKind _properties;

            public TypeImportCompletionItemInfo(CompletionItem item, bool isPublic, bool isGeneric, bool isAttribute)
            {
                Item = item;
                _properties = (isPublic ? ItemPropertyKind.IsPublic : 0)
                            | (isGeneric ? ItemPropertyKind.IsGeneric : 0)
                            | (isAttribute ? ItemPropertyKind.IsAttribute : 0);
            }

            public CompletionItem Item { get; }

            public bool IsPublic
                => (_properties & ItemPropertyKind.IsPublic) != 0;

            public bool IsGeneric
                => (_properties & ItemPropertyKind.IsGeneric) != 0;

            public bool IsAttribute
                => (_properties & ItemPropertyKind.IsAttribute) != 0;

            public TypeImportCompletionItemInfo WithItem(CompletionItem item)
            {
                return new TypeImportCompletionItemInfo(item, IsPublic, IsGeneric, IsAttribute);
            }

            [Flags]
            private enum ItemPropertyKind : byte
            {
                IsPublic = 0x1,
                IsGeneric = 0x2,
                IsAttribute = 0x4,
            }
        }
379 380
    }
}