SymbolKey.SymbolKeyReader.cs 19.5 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
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
7
using System.Linq;
8 9
using System.Text;
using System.Threading;
T
Tomas Matousek 已提交
10
using Microsoft.CodeAnalysis.PooledObjects;
11
using Microsoft.CodeAnalysis.Shared.Utilities;
12
using Microsoft.CodeAnalysis.Text;
13 14 15 16
using Roslyn.Utilities;

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

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

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

            public int Position;

            public Reader()
            {
                _readString = ReadString;
38
                _readBoolean = ReadBoolean;
39 40 41 42 43 44 45 46 47 48 49 50 51
                _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 已提交
52
                CancellationToken = default;
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 79 80 81
            }

            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();
                Debug.Assert(char.IsNumber(Data[Position]));

C
Use var  
Cyrus Najmabadi 已提交
82
                var value = 0;
83 84 85 86 87 88 89 90 91 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

                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 已提交
119 120 121 122 123 124
                if ((SymbolKeyType)Data[Position] == SymbolKeyType.Null)
                {
                    Eat(SymbolKeyType.Null);
                    return CreateNullForString();
                }

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
                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 已提交
159
            protected abstract TStringResult CreateNullForString();
160 161 162 163 164 165 166 167 168 169 170

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

            public ImmutableArray<TStringResult> ReadStringArray()
            {
                return ReadArray(_readString);
            }

171 172 173 174 175
            public ImmutableArray<bool> ReadBooleanArray()
            {
                return ReadArray(_readBoolean);
            }

176 177 178 179 180 181 182 183 184 185 186 187
            public ImmutableArray<RefKind> ReadRefKindArray()
            {
                return ReadArray(_readRefKind);
            }

            public ImmutableArray<T> ReadArray<T>(Func<T> readFunction)
            {
                EatSpace();

                if ((SymbolKeyType)Data[Position] == SymbolKeyType.Null)
                {
                    Eat(SymbolKeyType.Null);
C
CyrusNajmabadi 已提交
188
                    return default;
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208
                }

                EatOpenParen();
                Eat(SymbolKeyType.Array);

                var length = ReadInteger();
                var builder = ImmutableArray.CreateBuilder<T>(length);

                for (var i = 0; i < length; i++)
                {
                    CancellationToken.ThrowIfCancellationRequested();
                    builder.Add(readFunction());
                }

                EatCloseParen();

                return builder.MoveToImmutable();
            }
        }

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

            private bool _skipString = false;

            public RemoveAssemblySymbolKeysReader()
            {
            }

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

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

            protected override object CreateNullForString()
            {
                return null;
            }
277 278
        }

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

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

288 289 290 291
            public Compilation Compilation { get; private set; }
            public bool IgnoreAssemblyKey { get; private set; }
            public SymbolEquivalenceComparer Comparer { get; private set; }

292
            private List<IMethodSymbol> _methodSymbolStack = new List<IMethodSymbol>();
293
            private bool _resolveLocations;
294 295 296

            private SymbolKeyReader()
            {
C
CyrusNajmabadi 已提交
297 298
                _readSymbolKey = ReadSymbolKey;
                _readLocation = ReadLocation;
299 300 301 302 303
            }

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

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

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

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

337 338 339 340 341
                Comparer = ignoreAssemblyKey
                    ? SymbolEquivalenceComparer.IgnoreAssembliesInstance
                    : SymbolEquivalenceComparer.Instance;
            }

C
CyrusNajmabadi 已提交
342 343 344
            internal bool ParameterTypesMatch(
                ImmutableArray<IParameterSymbol> parameters,
                ITypeSymbol[] originalParameterTypes)
345
            {
C
CyrusNajmabadi 已提交
346 347 348 349
                if (parameters.Length != originalParameterTypes.Length)
                {
                    return false;
                }
350

C
CyrusNajmabadi 已提交
351 352 353 354 355 356
                // 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;

C
Use var  
Cyrus Najmabadi 已提交
357
                for (var i = 0; i < originalParameterTypes.Length; i++)
C
CyrusNajmabadi 已提交
358 359 360 361 362 363 364 365
                {
                    if (!signatureComparer.Equals(originalParameterTypes[i], parameters[i].Type))
                    {
                        return false;
                    }
                }

                return true;
J
Julien 已提交
366 367
            }

368 369
            public void PushMethod(IMethodSymbol methodOpt)
                => _methodSymbolStack.Add(methodOpt);
370

371
            public void PopMethod(IMethodSymbol methodOpt)
372
            {
373
                Contract.ThrowIfTrue(_methodSymbolStack.Count == 0);
374
                Contract.ThrowIfFalse(Equals(methodOpt, _methodSymbolStack.Last()));
375
                _methodSymbolStack.RemoveAt(_methodSymbolStack.Count - 1);
376 377
            }

378 379 380 381 382 383
            public IMethodSymbol ResolveMethod(int index)
                => _methodSymbolStack[index];

            internal SyntaxTree GetSyntaxTree(string filePath)
                => this.Compilation.SyntaxTrees.FirstOrDefault(t => t.FilePath == filePath);

C
CyrusNajmabadi 已提交
384 385 386
            #region Symbols

            public SymbolKeyResolution ReadFirstSymbolKey()
387
            {
C
CyrusNajmabadi 已提交
388
                return ReadSymbolKeyWorker(first: true);
389 390
            }

C
CyrusNajmabadi 已提交
391
            public SymbolKeyResolution ReadSymbolKey()
392
            {
C
CyrusNajmabadi 已提交
393
                return ReadSymbolKeyWorker(first: false);
394 395
            }

C
CyrusNajmabadi 已提交
396
            private SymbolKeyResolution ReadSymbolKeyWorker(bool first)
397
            {
C
CyrusNajmabadi 已提交
398 399 400 401 402 403 404 405 406 407
                CancellationToken.ThrowIfCancellationRequested();
                if (!first)
                {
                    EatSpace();
                }

                var type = (SymbolKeyType)Data[Position];
                if (type == SymbolKeyType.Null)
                {
                    Eat(type);
C
CyrusNajmabadi 已提交
408
                    return default;
C
CyrusNajmabadi 已提交
409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431
                }

                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;
432 433
            }

C
CyrusNajmabadi 已提交
434
            private SymbolKeyResolution ReadWorker(SymbolKeyType type)
435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
            {
                switch (type)
                {
                    case SymbolKeyType.Alias: return AliasSymbolKey.Resolve(this);
                    case SymbolKeyType.BodyLevel: return BodyLevelSymbolKey.Resolve(this);
                    case SymbolKeyType.ConstructedMethod: return ConstructedMethodSymbolKey.Resolve(this);
                    case SymbolKeyType.NamedType: return NamedTypeSymbolKey.Resolve(this);
                    case SymbolKeyType.ErrorType: return ErrorTypeSymbolKey.Resolve(this);
                    case SymbolKeyType.Field: return FieldSymbolKey.Resolve(this);
                    case SymbolKeyType.DynamicType: return DynamicTypeSymbolKey.Resolve(this);
                    case SymbolKeyType.Method: return MethodSymbolKey.Resolve(this);
                    case SymbolKeyType.Namespace: return NamespaceSymbolKey.Resolve(this);
                    case SymbolKeyType.PointerType: return PointerTypeSymbolKey.Resolve(this);
                    case SymbolKeyType.Parameter: return ParameterSymbolKey.Resolve(this);
                    case SymbolKeyType.Property: return PropertySymbolKey.Resolve(this);
                    case SymbolKeyType.ArrayType: return ArrayTypeSymbolKey.Resolve(this);
                    case SymbolKeyType.Assembly: return AssemblySymbolKey.Resolve(this);
                    case SymbolKeyType.TupleType: return TupleTypeSymbolKey.Resolve(this);
                    case SymbolKeyType.Module: return ModuleSymbolKey.Resolve(this);
                    case SymbolKeyType.Event: return EventSymbolKey.Resolve(this);
                    case SymbolKeyType.ReducedExtensionMethod: return ReducedExtensionMethodSymbolKey.Resolve(this);
                    case SymbolKeyType.TypeParameter: return TypeParameterSymbolKey.Resolve(this);
457
                    case SymbolKeyType.AnonymousType: return AnonymousTypeSymbolKey.Resolve(this);
458
                    case SymbolKeyType.AnonymousFunctionOrDelegate: return AnonymousFunctionOrDelegateSymbolKey.Resolve(this);
459 460 461 462 463 464
                    case SymbolKeyType.TypeParameterOrdinal: return TypeParameterOrdinalSymbolKey.Resolve(this);
                }

                throw new NotImplementedException();
            }

C
CyrusNajmabadi 已提交
465
            public ImmutableArray<SymbolKeyResolution> ReadSymbolKeyArray()
466
                => ReadArray(_readSymbolKey);
C
CyrusNajmabadi 已提交
467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493

            #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)
494
                {
C
CyrusNajmabadi 已提交
495 496
                    Eat(SymbolKeyType.Null);
                    return null;
497 498
                }

C
CyrusNajmabadi 已提交
499
                var kind = (LocationKind)ReadInteger();
500
                if (kind == LocationKind.SourceFile)
C
CyrusNajmabadi 已提交
501 502 503 504
                {
                    var filePath = ReadString();
                    var start = ReadInteger();
                    var length = ReadInteger();
505

506
                    if (_resolveLocations)
507
                    {
508 509 510 511 512 513 514
                        // 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));
                        }
515
                    }
C
CyrusNajmabadi 已提交
516
                }
517
                else if (kind == LocationKind.MetadataFile)
C
CyrusNajmabadi 已提交
518
                {
519
                    var assemblyResolution = ReadSymbolKey();
C
CyrusNajmabadi 已提交
520
                    var moduleName = ReadString();
521

522
                    if (_resolveLocations)
523
                    {
524 525 526
                        // 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)
527
                        {
528 529 530 531 532 533
                            var module = assembly.Modules.FirstOrDefault(m => m.MetadataName == moduleName);
                            var location = module?.Locations.FirstOrDefault();
                            if (location != null)
                            {
                                return location;
                            }
534 535
                        }
                    }
C
CyrusNajmabadi 已提交
536
                }
537

538
                return Location.None;
539
            }
C
CyrusNajmabadi 已提交
540 541 542 543 544 545 546 547 548 549 550

            private Location CreateModuleLocation(
                SymbolKeyResolution assembly, string moduleName)
            {
                var symbol = assembly.GetAnySymbol() as IAssemblySymbol;
                Debug.Assert(symbol != null);
                var module = symbol.Modules.FirstOrDefault(m => m.MetadataName == moduleName);
                return module.Locations.FirstOrDefault();
            }

            public ImmutableArray<Location> ReadLocationArray()
C
CyrusNajmabadi 已提交
551
                => ReadArray(_readLocation);
C
CyrusNajmabadi 已提交
552 553

            #endregion
554 555
        }
    }
T
Tomas Matousek 已提交
556
}