SymbolKey.SymbolKeyReader.cs 20.3 KB
Newer Older
C
CyrusNajmabadi 已提交
1 2 3
// 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;
4 5 6 7 8
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Text;
using System.Threading;
T
Tomas Matousek 已提交
9
using Microsoft.CodeAnalysis.PooledObjects;
10
using Microsoft.CodeAnalysis.Shared.Utilities;
11
using Microsoft.CodeAnalysis.Text;
12 13 14 15
using Roslyn.Utilities;

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

            private readonly Func<TStringResult> _readString;
26
            private readonly Func<bool> _readBoolean;
27 28 29 30 31 32 33 34 35 36
            private readonly Func<RefKind> _readRefKind;

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

            public int Position;

            public Reader()
            {
                _readString = ReadString;
37
                _readBoolean = ReadBoolean;
38 39 40 41 42 43 44 45 46 47 48 49 50
                _readRefKind = () => (RefKind)ReadInteger();
            }

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

            public virtual void Dispose()
            {
                Data = null;
C
CyrusNajmabadi 已提交
51
                CancellationToken = default;
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
            }

            protected char Eat(SymbolKeyType type)
            {
                return Eat((char)type);
            }

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

            protected void EatCloseParen()
            {
                Eat(CloseParenChar);
            }

            protected void EatOpenParen()
            {
                Eat(OpenParenChar);
            }

            public int ReadInteger()
            {
                EatSpace();
79 80 81 82 83 84 85 86 87 88
                return ReadIntegerRaw_DoNotCallDirectly();
            }

            public int ReadFormatVersion()
            {
                return ReadIntegerRaw_DoNotCallDirectly();
            }

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

C
Use var  
Cyrus Najmabadi 已提交
91
                var value = 0;
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127

                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()
            {
                return Eat(SpaceChar);
            }

            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 已提交
128 129 130 131 132 133
                if ((SymbolKeyType)Data[Position] == SymbolKeyType.Null)
                {
                    Eat(SymbolKeyType.Null);
                    return CreateNullForString();
                }

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
                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 已提交
168
            protected abstract TStringResult CreateNullForString();
169 170 171 172 173 174

            private void EatDoubleQuote()
            {
                Eat(DoubleQuoteChar);
            }

C
Cyrus Najmabadi 已提交
175
            public PooledArrayBuilder<TStringResult> ReadStringArray()
C
Cyrus Najmabadi 已提交
176
                => ReadArray(_readString);
177

C
Cyrus Najmabadi 已提交
178
            public PooledArrayBuilder<bool> ReadBooleanArray()
C
Cyrus Najmabadi 已提交
179
                => ReadArray(_readBoolean);
180

C
Cyrus Najmabadi 已提交
181
            public PooledArrayBuilder<RefKind> ReadRefKindArray()
C
Cyrus Najmabadi 已提交
182
                => ReadArray(_readRefKind);
183

C
Cyrus Najmabadi 已提交
184
            public PooledArrayBuilder<T> ReadArray<T>(Func<T> readFunction)
185
            {
C
Cyrus Najmabadi 已提交
186
                var builder = PooledArrayBuilder<T>.GetInstance();
187 188
                EatSpace();

189
                Debug.Assert((SymbolKeyType)Data[Position] != SymbolKeyType.Null);
190 191 192 193 194 195 196 197

                EatOpenParen();
                Eat(SymbolKeyType.Array);

                var length = ReadInteger();
                for (var i = 0; i < length; i++)
                {
                    CancellationToken.ThrowIfCancellationRequested();
198
                    builder.Builder.Add(readFunction());
199 200 201
                }

                EatCloseParen();
C
Cyrus Najmabadi 已提交
202
                return builder;
203 204 205
            }
        }

206
        private class RemoveAssemblySymbolKeysReader : Reader<object>
207 208 209 210 211 212 213 214 215 216
        {
            private readonly StringBuilder _builder = new StringBuilder();

            private bool _skipString = false;

            public RemoveAssemblySymbolKeysReader()
            {
            }

            public void Initialize(string data)
217
                => base.Initialize(data, CancellationToken.None);
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245

            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
                    {
246
                        // All other characters we pass along directly to the string builder.
247 248 249 250 251 252 253 254 255 256
                        _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.
257
                // However, we want to include both quotes in the result.
258 259 260 261 262 263 264 265 266 267 268
                _builder.Append(DoubleQuoteChar);
                if (!_skipString)
                {
                    for (var i = start; i < end; i++)
                    {
                        _builder.Append(Data[i]);
                    }
                }
                _builder.Append(DoubleQuoteChar);
                return null;
            }
J
Julien 已提交
269 270 271 272 273

            protected override object CreateNullForString()
            {
                return null;
            }
274 275
        }

C
CyrusNajmabadi 已提交
276
        private class SymbolKeyReader : Reader<string>
277 278 279 280
        {
            private static readonly ObjectPool<SymbolKeyReader> s_readerPool =
                new ObjectPool<SymbolKeyReader>(() => new SymbolKeyReader());

C
CyrusNajmabadi 已提交
281 282 283 284
            private readonly Dictionary<int, SymbolKeyResolution> _idToResult = new Dictionary<int, SymbolKeyResolution>();
            private readonly Func<SymbolKeyResolution> _readSymbolKey;
            private readonly Func<Location> _readLocation;

285 286 287 288
            public Compilation Compilation { get; private set; }
            public bool IgnoreAssemblyKey { get; private set; }
            public SymbolEquivalenceComparer Comparer { get; private set; }

289
            private readonly List<IMethodSymbol> _methodSymbolStack = new List<IMethodSymbol>();
290
            private bool _resolveLocations;
291 292 293

            private SymbolKeyReader()
            {
C
CyrusNajmabadi 已提交
294 295
                _readSymbolKey = ReadSymbolKey;
                _readLocation = ReadLocation;
296 297 298 299 300
            }

            public override void Dispose()
            {
                base.Dispose();
C
CyrusNajmabadi 已提交
301
                _idToResult.Clear();
302 303
                Compilation = null;
                IgnoreAssemblyKey = false;
304
                _resolveLocations = false;
305
                Comparer = null;
306
                _methodSymbolStack.Clear();
307 308 309 310 311

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

C
CyrusNajmabadi 已提交
312 313
            public static SymbolKeyReader GetReader(
                string data, Compilation compilation,
314 315
                bool ignoreAssemblyKey, bool resolveLocations,
                CancellationToken cancellationToken)
C
CyrusNajmabadi 已提交
316 317
            {
                var reader = s_readerPool.Allocate();
318
                reader.Initialize(data, compilation, ignoreAssemblyKey, resolveLocations, cancellationToken);
C
CyrusNajmabadi 已提交
319 320 321
                return reader;
            }

322 323 324 325
            private void Initialize(
                string data,
                Compilation compilation,
                bool ignoreAssemblyKey,
326
                bool resolveLocations,
327 328 329 330 331
                CancellationToken cancellationToken)
            {
                base.Initialize(data, cancellationToken);
                Compilation = compilation;
                IgnoreAssemblyKey = ignoreAssemblyKey;
332 333
                _resolveLocations = resolveLocations;

334 335 336 337 338
                Comparer = ignoreAssemblyKey
                    ? SymbolEquivalenceComparer.IgnoreAssembliesInstance
                    : SymbolEquivalenceComparer.Instance;
            }

C
CyrusNajmabadi 已提交
339 340
            internal bool ParameterTypesMatch(
                ImmutableArray<IParameterSymbol> parameters,
341
                PooledArrayBuilder<ITypeSymbol> originalParameterTypes)
342
            {
C
Cyrus Najmabadi 已提交
343
                if (originalParameterTypes.IsDefault || parameters.Length != originalParameterTypes.Count)
C
CyrusNajmabadi 已提交
344 345 346
                {
                    return false;
                }
347

C
CyrusNajmabadi 已提交
348 349 350 351 352 353
                // 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;

354
                for (var i = 0; i < originalParameterTypes.Count; i++)
C
CyrusNajmabadi 已提交
355 356 357 358 359 360 361 362
                {
                    if (!signatureComparer.Equals(originalParameterTypes[i], parameters[i].Type))
                    {
                        return false;
                    }
                }

                return true;
J
Julien 已提交
363 364
            }

365 366
            public void PushMethod(IMethodSymbol methodOpt)
                => _methodSymbolStack.Add(methodOpt);
367

368
            public void PopMethod(IMethodSymbol methodOpt)
369
            {
370
                Contract.ThrowIfTrue(_methodSymbolStack.Count == 0);
C
Cyrus Najmabadi 已提交
371
                Contract.ThrowIfFalse(Equals(methodOpt, _methodSymbolStack[_methodSymbolStack.Count - 1]));
372
                _methodSymbolStack.RemoveAt(_methodSymbolStack.Count - 1);
373 374
            }

375 376 377 378
            public IMethodSymbol ResolveMethod(int index)
                => _methodSymbolStack[index];

            internal SyntaxTree GetSyntaxTree(string filePath)
C
Cyrus Najmabadi 已提交
379 380 381 382 383 384 385 386 387 388 389
            {
                foreach (var tree in this.Compilation.SyntaxTrees)
                {
                    if (tree.FilePath == filePath)
                    {
                        return tree;
                    }
                }

                return null;
            }
390

C
CyrusNajmabadi 已提交
391 392 393
            #region Symbols

            public SymbolKeyResolution ReadSymbolKey()
394
            {
C
CyrusNajmabadi 已提交
395
                CancellationToken.ThrowIfCancellationRequested();
396
                EatSpace();
C
CyrusNajmabadi 已提交
397 398 399 400 401

                var type = (SymbolKeyType)Data[Position];
                if (type == SymbolKeyType.Null)
                {
                    Eat(type);
C
CyrusNajmabadi 已提交
402
                    return default;
C
CyrusNajmabadi 已提交
403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425
                }

                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;
426 427
            }

C
CyrusNajmabadi 已提交
428
            private SymbolKeyResolution ReadWorker(SymbolKeyType type)
429
                => type switch
430
                {
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
                    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),
                    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(),
                };
455

C
temp  
Cyrus Najmabadi 已提交
456 457
            /// <summary>
            /// Reads an array of symbols out from the key.  Note: the number of symbols returned 
C
Cyrus Najmabadi 已提交
458 459 460 461
            /// will either be the same as the original amount writtern, or <c>default</c> will be 
            /// 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 
            /// in the provided <see cref="Compilation"/>.
C
temp  
Cyrus Najmabadi 已提交
462
            /// </summary>
C
Cyrus Najmabadi 已提交
463
            public PooledArrayBuilder<TSymbol> ReadSymbolKeyArray<TSymbol>() where TSymbol : ISymbol
464
            {
C
Cyrus Najmabadi 已提交
465
                using var resolutions = ReadArray(_readSymbolKey);
466

C
Cyrus Najmabadi 已提交
467
                var result = PooledArrayBuilder<TSymbol>.GetInstance();
468 469 470 471
                foreach (var resolution in resolutions)
                {
                    if (resolution.GetAnySymbol() is TSymbol castedSymbol)
                    {
C
Cyrus Najmabadi 已提交
472
                        result.AddIfNotNull(castedSymbol);
473
                    }
C
temp  
Cyrus Najmabadi 已提交
474 475
                    else
                    {
C
Cyrus Najmabadi 已提交
476
                        return default;
C
temp  
Cyrus Najmabadi 已提交
477
                    }
478
                }
C
Cyrus Najmabadi 已提交
479

C
Cyrus Najmabadi 已提交
480
                return result;
481
            }
C
CyrusNajmabadi 已提交
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508

            #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()
            {
                return null;
            }

            #endregion

            #region Locations

            public Location ReadLocation()
            {
                EatSpace();
                if ((SymbolKeyType)Data[Position] == SymbolKeyType.Null)
509
                {
C
CyrusNajmabadi 已提交
510 511
                    Eat(SymbolKeyType.Null);
                    return null;
512 513
                }

C
CyrusNajmabadi 已提交
514
                var kind = (LocationKind)ReadInteger();
515
                if (kind == LocationKind.SourceFile)
C
CyrusNajmabadi 已提交
516 517 518 519
                {
                    var filePath = ReadString();
                    var start = ReadInteger();
                    var length = ReadInteger();
520

521
                    if (_resolveLocations)
522
                    {
523 524 525 526 527 528 529
                        // 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)
                        {
                            return Location.Create(syntaxTree, new TextSpan(start, length));
                        }
530
                    }
C
CyrusNajmabadi 已提交
531
                }
532
                else if (kind == LocationKind.MetadataFile)
C
CyrusNajmabadi 已提交
533
                {
534
                    var assemblyResolution = ReadSymbolKey();
C
CyrusNajmabadi 已提交
535
                    var moduleName = ReadString();
536

537
                    if (_resolveLocations)
538
                    {
539 540 541
                        // 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)
542
                        {
C
Cyrus Najmabadi 已提交
543 544
                            var module = GetModule(assembly.Modules, moduleName);
                            if (module != null)
545
                            {
C
Cyrus Najmabadi 已提交
546 547 548 549 550
                                var location = FirstOrDefault(module.Locations);
                                if (location != null)
                                {
                                    return location;
                                }
551
                            }
552 553
                        }
                    }
C
CyrusNajmabadi 已提交
554
                }
555

556
                return Location.None;
557
            }
C
CyrusNajmabadi 已提交
558

C
Cyrus Najmabadi 已提交
559 560 561 562 563 564 565 566 567 568 569 570 571
            private IModuleSymbol GetModule(IEnumerable<IModuleSymbol> modules, string moduleName)
            {
                foreach (var module in modules)
                {
                    if (module.MetadataName == moduleName)
                    {
                        return module;
                    }
                }

                return null;
            }

C
Cyrus Najmabadi 已提交
572
            public PooledArrayBuilder<Location> ReadLocationArray()
C
Cyrus Najmabadi 已提交
573
                => ReadArray(_readLocation);
C
CyrusNajmabadi 已提交
574 575

            #endregion
576 577
        }
    }
T
Tomas Matousek 已提交
578
}