SymbolKey.SymbolKeyReader.cs 21.1 KB
Newer Older
J
Jonathon Marolf 已提交
1 2 3
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
C
CyrusNajmabadi 已提交
4 5

using System;
6 7 8 9 10
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Text;
using System.Threading;
T
Tomas Matousek 已提交
11
using Microsoft.CodeAnalysis.PooledObjects;
12
using Microsoft.CodeAnalysis.Shared.Extensions;
13
using Microsoft.CodeAnalysis.Shared.Utilities;
14
using Microsoft.CodeAnalysis.Text;
15 16 17 18
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis
{
19
    internal partial struct SymbolKey
20
    {
21
        private abstract class Reader<TStringResult> : IDisposable
22 23 24 25 26 27 28
        {
            protected const char OpenParenChar = '(';
            protected const char CloseParenChar = ')';
            protected const char SpaceChar = ' ';
            protected const char DoubleQuoteChar = '"';

            private readonly Func<TStringResult> _readString;
29
            private readonly Func<bool> _readBoolean;
30 31 32 33 34 35 36 37 38 39
            private readonly Func<RefKind> _readRefKind;

            protected string Data { get; private set; }
            public CancellationToken CancellationToken { get; private set; }

            public int Position;

            public Reader()
            {
                _readString = ReadString;
40
                _readBoolean = ReadBoolean;
41
                _readRefKind = ReadRefKind;
42 43 44 45 46 47 48 49 50 51 52 53
            }

            protected virtual void Initialize(string data, CancellationToken cancellationToken)
            {
                Data = data;
                CancellationToken = cancellationToken;
                Position = 0;
            }

            public virtual void Dispose()
            {
                Data = null;
C
CyrusNajmabadi 已提交
54
                CancellationToken = default;
55 56 57
            }

            protected char Eat(SymbolKeyType type)
58
                => Eat((char)type);
59 60 61 62 63 64 65 66 67

            protected char Eat(char c)
            {
                Debug.Assert(Data[Position] == c);
                Position++;
                return c;
            }

            protected void EatCloseParen()
68
                => Eat(CloseParenChar);
69 70

            protected void EatOpenParen()
71
                => Eat(OpenParenChar);
72 73 74 75

            public int ReadInteger()
            {
                EatSpace();
76 77 78 79
                return ReadIntegerRaw_DoNotCallDirectly();
            }

            public int ReadFormatVersion()
C
Fixes  
Cyrus Najmabadi 已提交
80
                => ReadIntegerRaw_DoNotCallDirectly();
81 82 83

            private int ReadIntegerRaw_DoNotCallDirectly()
            {
84 85
                Debug.Assert(char.IsNumber(Data[Position]));

C
Use var  
Cyrus Najmabadi 已提交
86
                var value = 0;
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103

                var start = Position;
                while (char.IsNumber(Data[Position]))
                {
                    var digit = Data[Position] - '0';

                    value *= 10;
                    value += digit;

                    Position++;
                }

                Debug.Assert(start != Position);
                return value;
            }

            protected char EatSpace()
104
                => Eat(SpaceChar);
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120

            public bool ReadBoolean()
            {
                var val = ReadInteger();
                Debug.Assert(val == 0 || val == 1);
                return val == 1;
            }

            public TStringResult ReadString()
            {
                EatSpace();
                return ReadStringNoSpace();
            }

            protected TStringResult ReadStringNoSpace()
            {
J
Julien 已提交
121 122 123 124 125 126
                if ((SymbolKeyType)Data[Position] == SymbolKeyType.Null)
                {
                    Eat(SymbolKeyType.Null);
                    return CreateNullForString();
                }

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
                EatDoubleQuote();

                var start = Position;

                var hasEmbeddedQuote = false;
                while (true)
                {
                    if (Data[Position] != DoubleQuoteChar)
                    {
                        Position++;
                        continue;
                    }

                    // We have a quote.  See if it's the final quote, or if it's an escaped
                    // embedded quote.
                    if (Data[Position + 1] == DoubleQuoteChar)
                    {
                        hasEmbeddedQuote = true;
                        Position += 2;
                        continue;
                    }

                    break;
                }

                var end = Position;
                EatDoubleQuote();

                var result = CreateResultForString(start, end, hasEmbeddedQuote);

                return result;
            }

            protected abstract TStringResult CreateResultForString(int start, int end, bool hasEmbeddedQuote);
J
Julien 已提交
161
            protected abstract TStringResult CreateNullForString();
162 163

            private void EatDoubleQuote()
164
                => Eat(DoubleQuoteChar);
165

C
Cyrus Najmabadi 已提交
166
            public PooledArrayBuilder<TStringResult> ReadStringArray()
C
Cyrus Najmabadi 已提交
167
                => ReadArray(_readString);
168

C
Cyrus Najmabadi 已提交
169
            public PooledArrayBuilder<bool> ReadBooleanArray()
C
Cyrus Najmabadi 已提交
170
                => ReadArray(_readBoolean);
171

C
Cyrus Najmabadi 已提交
172
            public PooledArrayBuilder<RefKind> ReadRefKindArray()
C
Cyrus Najmabadi 已提交
173
                => ReadArray(_readRefKind);
174

C
Cyrus Najmabadi 已提交
175
            public PooledArrayBuilder<T> ReadArray<T>(Func<T> readFunction)
176
            {
C
Cyrus Najmabadi 已提交
177
                var builder = PooledArrayBuilder<T>.GetInstance();
178 179
                EatSpace();

180
                Debug.Assert((SymbolKeyType)Data[Position] != SymbolKeyType.Null);
181 182 183 184 185 186 187 188

                EatOpenParen();
                Eat(SymbolKeyType.Array);

                var length = ReadInteger();
                for (var i = 0; i < length; i++)
                {
                    CancellationToken.ThrowIfCancellationRequested();
189
                    builder.Builder.Add(readFunction());
190 191 192
                }

                EatCloseParen();
C
Cyrus Najmabadi 已提交
193
                return builder;
194
            }
195 196 197 198 199

            public RefKind ReadRefKind()
            {
                return (RefKind)ReadInteger();
            }
200 201
        }

202
        private class RemoveAssemblySymbolKeysReader : Reader<object>
203 204 205 206 207 208 209 210 211 212
        {
            private readonly StringBuilder _builder = new StringBuilder();

            private bool _skipString = false;

            public RemoveAssemblySymbolKeysReader()
            {
            }

            public void Initialize(string data)
213
                => base.Initialize(data, CancellationToken.None);
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

            public string RemoveAssemblySymbolKeys()
            {
                while (Position < Data.Length)
                {
                    var ch = Data[Position];
                    if (ch == OpenParenChar)
                    {
                        _builder.Append(Eat(OpenParenChar));

                        var type = (SymbolKeyType)Data[Position];
                        _builder.Append(Eat(type));
                        if (type == SymbolKeyType.Assembly)
                        {
                            Debug.Assert(_skipString == false);
                            _skipString = true;
                            ReadString();

                            Debug.Assert(_skipString == true);
                            _skipString = false;
                        }
                    }
                    else if (Data[Position] == DoubleQuoteChar)
                    {
                        ReadStringNoSpace();
                    }
                    else
                    {
242
                        // All other characters we pass along directly to the string builder.
243 244 245 246 247 248 249 250 251 252
                        _builder.Append(Eat(ch));
                    }
                }

                return _builder.ToString();
            }

            protected override object CreateResultForString(int start, int end, bool hasEmbeddedQuote)
            {
                // 'start' is right after the open quote, and 'end' is right before the close quote.
253
                // However, we want to include both quotes in the result.
254 255 256 257 258 259 260 261 262 263 264
                _builder.Append(DoubleQuoteChar);
                if (!_skipString)
                {
                    for (var i = start; i < end; i++)
                    {
                        _builder.Append(Data[i]);
                    }
                }
                _builder.Append(DoubleQuoteChar);
                return null;
            }
J
Julien 已提交
265 266

            protected override object CreateNullForString()
267
                => null;
268 269
        }

C
CyrusNajmabadi 已提交
270
        private class SymbolKeyReader : Reader<string>
271
        {
C
revert  
Cyrus Najmabadi 已提交
272
            private static readonly ObjectPool<SymbolKeyReader> s_readerPool = SharedPools.Default<SymbolKeyReader>();
273

C
CyrusNajmabadi 已提交
274 275 276 277
            private readonly Dictionary<int, SymbolKeyResolution> _idToResult = new Dictionary<int, SymbolKeyResolution>();
            private readonly Func<SymbolKeyResolution> _readSymbolKey;
            private readonly Func<Location> _readLocation;

278 279 280 281
            public Compilation Compilation { get; private set; }
            public bool IgnoreAssemblyKey { get; private set; }
            public SymbolEquivalenceComparer Comparer { get; private set; }

282
            private readonly List<IMethodSymbol> _methodSymbolStack = new List<IMethodSymbol>();
283

C
Cyrus Najmabadi 已提交
284
            public SymbolKeyReader()
285
            {
C
CyrusNajmabadi 已提交
286 287
                _readSymbolKey = ReadSymbolKey;
                _readLocation = ReadLocation;
288 289 290 291 292
            }

            public override void Dispose()
            {
                base.Dispose();
C
CyrusNajmabadi 已提交
293
                _idToResult.Clear();
294 295 296
                Compilation = null;
                IgnoreAssemblyKey = false;
                Comparer = null;
297
                _methodSymbolStack.Clear();
298 299 300 301 302

                // Place us back in the pool for future use.
                s_readerPool.Free(this);
            }

C
CyrusNajmabadi 已提交
303 304
            public static SymbolKeyReader GetReader(
                string data, Compilation compilation,
C
Cyrus Najmabadi 已提交
305
                bool ignoreAssemblyKey,
306
                CancellationToken cancellationToken)
C
CyrusNajmabadi 已提交
307 308
            {
                var reader = s_readerPool.Allocate();
C
Cyrus Najmabadi 已提交
309
                reader.Initialize(data, compilation, ignoreAssemblyKey, cancellationToken);
C
CyrusNajmabadi 已提交
310 311 312
                return reader;
            }

313 314 315 316 317 318 319 320 321
            private void Initialize(
                string data,
                Compilation compilation,
                bool ignoreAssemblyKey,
                CancellationToken cancellationToken)
            {
                base.Initialize(data, cancellationToken);
                Compilation = compilation;
                IgnoreAssemblyKey = ignoreAssemblyKey;
322

323 324 325 326 327
                Comparer = ignoreAssemblyKey
                    ? SymbolEquivalenceComparer.IgnoreAssembliesInstance
                    : SymbolEquivalenceComparer.Instance;
            }

C
CyrusNajmabadi 已提交
328 329
            internal bool ParameterTypesMatch(
                ImmutableArray<IParameterSymbol> parameters,
330
                PooledArrayBuilder<ITypeSymbol> originalParameterTypes)
331
            {
C
Cyrus Najmabadi 已提交
332
                if (originalParameterTypes.IsDefault || parameters.Length != originalParameterTypes.Count)
C
CyrusNajmabadi 已提交
333 334 335
                {
                    return false;
                }
336

C
CyrusNajmabadi 已提交
337 338 339 340 341 342
                // We are checking parameters for equality, if they refer to method type parameters,
                // then we don't want to recurse through the method (which would then recurse right
                // back into the parameters).  So we use a signature type comparer as it will properly
                // compare method type parameters by ordinal.
                var signatureComparer = Comparer.SignatureTypeEquivalenceComparer;

343
                for (var i = 0; i < originalParameterTypes.Count; i++)
C
CyrusNajmabadi 已提交
344 345 346 347 348 349 350 351
                {
                    if (!signatureComparer.Equals(originalParameterTypes[i], parameters[i].Type))
                    {
                        return false;
                    }
                }

                return true;
J
Julien 已提交
352 353
            }

354 355
            public void PushMethod(IMethodSymbol methodOpt)
                => _methodSymbolStack.Add(methodOpt);
356

357
            public void PopMethod(IMethodSymbol methodOpt)
358
            {
359
                Contract.ThrowIfTrue(_methodSymbolStack.Count == 0);
C
Cyrus Najmabadi 已提交
360
                Contract.ThrowIfFalse(Equals(methodOpt, _methodSymbolStack[_methodSymbolStack.Count - 1]));
361
                _methodSymbolStack.RemoveAt(_methodSymbolStack.Count - 1);
362 363
            }

364 365 366 367
            public IMethodSymbol ResolveMethod(int index)
                => _methodSymbolStack[index];

            internal SyntaxTree GetSyntaxTree(string filePath)
C
Cyrus Najmabadi 已提交
368 369 370 371 372 373 374 375 376 377 378
            {
                foreach (var tree in this.Compilation.SyntaxTrees)
                {
                    if (tree.FilePath == filePath)
                    {
                        return tree;
                    }
                }

                return null;
            }
379

C
CyrusNajmabadi 已提交
380 381 382
            #region Symbols

            public SymbolKeyResolution ReadSymbolKey()
383
            {
C
CyrusNajmabadi 已提交
384
                CancellationToken.ThrowIfCancellationRequested();
385
                EatSpace();
C
CyrusNajmabadi 已提交
386 387 388 389 390

                var type = (SymbolKeyType)Data[Position];
                if (type == SymbolKeyType.Null)
                {
                    Eat(type);
C
CyrusNajmabadi 已提交
391
                    return default;
C
CyrusNajmabadi 已提交
392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414
                }

                EatOpenParen();
                SymbolKeyResolution result;

                type = (SymbolKeyType)Data[Position];
                Eat(type);

                if (type == SymbolKeyType.Reference)
                {
                    var id = ReadInteger();
                    result = _idToResult[id];
                }
                else
                {
                    result = ReadWorker(type);
                    var id = ReadInteger();
                    _idToResult[id] = result;
                }

                EatCloseParen();

                return result;
415 416
            }

C
CyrusNajmabadi 已提交
417
            private SymbolKeyResolution ReadWorker(SymbolKeyType type)
418
                => type switch
419
                {
420 421 422 423 424 425
                    SymbolKeyType.Alias => AliasSymbolKey.Resolve(this),
                    SymbolKeyType.BodyLevel => BodyLevelSymbolKey.Resolve(this),
                    SymbolKeyType.ConstructedMethod => ConstructedMethodSymbolKey.Resolve(this),
                    SymbolKeyType.NamedType => NamedTypeSymbolKey.Resolve(this),
                    SymbolKeyType.ErrorType => ErrorTypeSymbolKey.Resolve(this),
                    SymbolKeyType.Field => FieldSymbolKey.Resolve(this),
426
                    SymbolKeyType.FunctionPointer => FunctionPointerTypeSymbolKey.Resolve(this),
427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444
                    SymbolKeyType.DynamicType => DynamicTypeSymbolKey.Resolve(this),
                    SymbolKeyType.Method => MethodSymbolKey.Resolve(this),
                    SymbolKeyType.Namespace => NamespaceSymbolKey.Resolve(this),
                    SymbolKeyType.PointerType => PointerTypeSymbolKey.Resolve(this),
                    SymbolKeyType.Parameter => ParameterSymbolKey.Resolve(this),
                    SymbolKeyType.Property => PropertySymbolKey.Resolve(this),
                    SymbolKeyType.ArrayType => ArrayTypeSymbolKey.Resolve(this),
                    SymbolKeyType.Assembly => AssemblySymbolKey.Resolve(this),
                    SymbolKeyType.TupleType => TupleTypeSymbolKey.Resolve(this),
                    SymbolKeyType.Module => ModuleSymbolKey.Resolve(this),
                    SymbolKeyType.Event => EventSymbolKey.Resolve(this),
                    SymbolKeyType.ReducedExtensionMethod => ReducedExtensionMethodSymbolKey.Resolve(this),
                    SymbolKeyType.TypeParameter => TypeParameterSymbolKey.Resolve(this),
                    SymbolKeyType.AnonymousType => AnonymousTypeSymbolKey.Resolve(this),
                    SymbolKeyType.AnonymousFunctionOrDelegate => AnonymousFunctionOrDelegateSymbolKey.Resolve(this),
                    SymbolKeyType.TypeParameterOrdinal => TypeParameterOrdinalSymbolKey.Resolve(this),
                    _ => throw new NotImplementedException(),
                };
445

C
temp  
Cyrus Najmabadi 已提交
446 447
            /// <summary>
            /// Reads an array of symbols out from the key.  Note: the number of symbols returned 
C
Cyrus Najmabadi 已提交
448
            /// will either be the same as the original amount written, or <c>default</c> will be 
C
Cyrus Najmabadi 已提交
449 450
            /// returned. It will never be less or more.  <c>default</c> will be returned if any 
            /// elements could not be resolved to the requested <typeparamref name="TSymbol"/> type 
451
            /// in the provided <see cref="SymbolKeyReader.Compilation"/>.
C
Cyrus Najmabadi 已提交
452 453 454
            /// 
            /// Callers should <see cref="IDisposable.Dispose"/> the instance returned.  No check is
            /// necessary if <c>default</c> was returned before calling <see cref="IDisposable.Dispose"/>
C
temp  
Cyrus Najmabadi 已提交
455
            /// </summary>
C
Cyrus Najmabadi 已提交
456
            public PooledArrayBuilder<TSymbol> ReadSymbolKeyArray<TSymbol>() where TSymbol : ISymbol
457
            {
C
Cyrus Najmabadi 已提交
458
                using var resolutions = ReadArray(_readSymbolKey);
459

C
Cyrus Najmabadi 已提交
460
                var result = PooledArrayBuilder<TSymbol>.GetInstance();
461 462 463 464
                foreach (var resolution in resolutions)
                {
                    if (resolution.GetAnySymbol() is TSymbol castedSymbol)
                    {
C
Cyrus Najmabadi 已提交
465
                        result.AddIfNotNull(castedSymbol);
466
                    }
C
temp  
Cyrus Najmabadi 已提交
467 468
                    else
                    {
C
Cyrus Najmabadi 已提交
469
                        result.Dispose();
C
Cyrus Najmabadi 已提交
470
                        return default;
C
temp  
Cyrus Najmabadi 已提交
471
                    }
472
                }
C
Cyrus Najmabadi 已提交
473

C
Cyrus Najmabadi 已提交
474
                return result;
475
            }
C
CyrusNajmabadi 已提交
476 477 478 479 480 481 482 483 484 485 486 487 488 489 490

            #endregion

            #region Strings

            protected override string CreateResultForString(int start, int end, bool hasEmbeddedQuote)
            {
                var substring = Data.Substring(start, end - start);
                var result = hasEmbeddedQuote
                    ? substring.Replace("\"\"", "\"")
                    : substring;
                return result;
            }

            protected override string CreateNullForString()
491
                => null;
C
CyrusNajmabadi 已提交
492 493 494 495 496 497 498 499 500

            #endregion

            #region Locations

            public Location ReadLocation()
            {
                EatSpace();
                if ((SymbolKeyType)Data[Position] == SymbolKeyType.Null)
501
                {
C
CyrusNajmabadi 已提交
502 503
                    Eat(SymbolKeyType.Null);
                    return null;
504 505
                }

C
CyrusNajmabadi 已提交
506
                var kind = (LocationKind)ReadInteger();
507
                if (kind == LocationKind.SourceFile)
C
CyrusNajmabadi 已提交
508 509 510 511
                {
                    var filePath = ReadString();
                    var start = ReadInteger();
                    var length = ReadInteger();
512

C
Cyrus Najmabadi 已提交
513 514 515 516
                    // The syntax tree can be null if we're resolving this location in a compilation
                    // that does not contain this file.  In this case, just map this location to None.
                    var syntaxTree = GetSyntaxTree(filePath);
                    if (syntaxTree != null)
517
                    {
C
Cyrus Najmabadi 已提交
518
                        return Location.Create(syntaxTree, new TextSpan(start, length));
519
                    }
C
CyrusNajmabadi 已提交
520
                }
521
                else if (kind == LocationKind.MetadataFile)
C
CyrusNajmabadi 已提交
522
                {
523
                    var assemblyResolution = ReadSymbolKey();
C
CyrusNajmabadi 已提交
524
                    var moduleName = ReadString();
525

C
Cyrus Najmabadi 已提交
526 527 528
                    // We may be resolving in a compilation where we don't have a module
                    // with this name.  In that case, just map this location to none.
                    if (assemblyResolution.GetAnySymbol() is IAssemblySymbol assembly)
529
                    {
C
Cyrus Najmabadi 已提交
530 531
                        var module = GetModule(assembly.Modules, moduleName);
                        if (module != null)
532
                        {
C
Cyrus Najmabadi 已提交
533 534
                            var location = FirstOrDefault(module.Locations);
                            if (location != null)
535
                            {
C
Cyrus Najmabadi 已提交
536
                                return location;
537
                            }
538 539
                        }
                    }
C
CyrusNajmabadi 已提交
540
                }
541

542
                return Location.None;
543
            }
C
CyrusNajmabadi 已提交
544

545 546 547 548 549 550
            public SymbolKeyResolution? ResolveLocation(Location location)
            {
                if (location.SourceTree != null)
                {
                    var node = location.FindNode(findInsideTrivia: true, getInnermostNodeForTie: true, CancellationToken);
                    var semanticModel = Compilation.GetSemanticModel(location.SourceTree);
C
Fixes  
Cyrus Najmabadi 已提交
551 552 553 554
                    var symbol = semanticModel.GetDeclaredSymbol(node, CancellationToken);
                    if (symbol != null)
                        return new SymbolKeyResolution(symbol);

555 556 557 558 559 560 561 562 563 564 565
                    var info = semanticModel.GetSymbolInfo(node, CancellationToken);
                    if (info.Symbol != null)
                        return new SymbolKeyResolution(info.Symbol);

                    if (info.CandidateSymbols.Length > 0)
                        return new SymbolKeyResolution(info.CandidateSymbols, info.CandidateReason);
                }

                return null;
            }

566
            private static IModuleSymbol GetModule(IEnumerable<IModuleSymbol> modules, string moduleName)
C
Cyrus Najmabadi 已提交
567 568 569 570 571 572 573 574 575 576 577 578
            {
                foreach (var module in modules)
                {
                    if (module.MetadataName == moduleName)
                    {
                        return module;
                    }
                }

                return null;
            }

C
Cyrus Najmabadi 已提交
579
            public PooledArrayBuilder<Location> ReadLocationArray()
C
Cyrus Najmabadi 已提交
580
                => ReadArray(_readLocation);
C
CyrusNajmabadi 已提交
581 582

            #endregion
583 584
        }
    }
T
Tomas Matousek 已提交
585
}