SymbolKey.SymbolKeyReader.cs 19.1 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
            }

            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();
80 81 82 83 84 85 86 87 88 89
                return ReadIntegerRaw_DoNotCallDirectly();
            }

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

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

C
Use var  
Cyrus Najmabadi 已提交
92
                var value = 0;
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 128

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

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

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

176 177
            public void FillStringArray(PooledArrayBuilder<TStringResult> builder)
                => FillArray(builder, _readString);
178

179 180
            public void FillBooleanArray(PooledArrayBuilder<bool> builder)
                => FillArray(builder, _readBoolean);
181

182 183
            public void FillRefKindArray(PooledArrayBuilder<RefKind> builder)
                => FillArray(builder, _readRefKind);
184

185 186 187 188 189
            /// <summary>
            /// Returns false if this was an encoded 'null' (as opposed to an empty array).
            /// </summary>
            public void FillArray<T>(
                PooledArrayBuilder<T> builder, Func<T> readFunction)
190 191 192
            {
                EatSpace();

193
                Debug.Assert((SymbolKeyType)Data[Position] != SymbolKeyType.Null);
194 195 196 197 198 199 200 201

                EatOpenParen();
                Eat(SymbolKeyType.Array);

                var length = ReadInteger();
                for (var i = 0; i < length; i++)
                {
                    CancellationToken.ThrowIfCancellationRequested();
202
                    builder.Builder.Add(readFunction());
203 204 205 206 207 208
                }

                EatCloseParen();
            }
        }

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 readonly 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
            internal bool ParameterTypesMatch(
                ImmutableArray<IParameterSymbol> parameters,
344
                PooledArrayBuilder<ITypeSymbol> originalParameterTypes)
345
            {
346
                if (parameters.Length != originalParameterTypes.Count)
C
CyrusNajmabadi 已提交
347 348 349
                {
                    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;

357
                for (var i = 0; i < originalParameterTypes.Count; 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 ReadSymbolKey()
387
            {
C
CyrusNajmabadi 已提交
388
                CancellationToken.ThrowIfCancellationRequested();
389
                EatSpace();
C
CyrusNajmabadi 已提交
390 391 392 393 394

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

                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;
419 420
            }

C
CyrusNajmabadi 已提交
421
            private SymbolKeyResolution ReadWorker(SymbolKeyType type)
422
                => type switch
423
                {
424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447
                    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(),
                };
448

449 450 451 452 453 454 455 456 457 458 459 460 461
            public void FillSymbolArray<TSymbol>(PooledArrayBuilder<TSymbol> builder) where TSymbol : ISymbol
            {
                using var resolutions = PooledArrayBuilder<SymbolKeyResolution>.GetInstance();
                FillArray(resolutions, _readSymbolKey);

                foreach (var resolution in resolutions)
                {
                    if (resolution.GetAnySymbol() is TSymbol castedSymbol)
                    {
                        builder.AddIfNotNull(castedSymbol);
                    }
                }
            }
C
CyrusNajmabadi 已提交
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488

            #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)
489
                {
C
CyrusNajmabadi 已提交
490 491
                    Eat(SymbolKeyType.Null);
                    return null;
492 493
                }

C
CyrusNajmabadi 已提交
494
                var kind = (LocationKind)ReadInteger();
495
                if (kind == LocationKind.SourceFile)
C
CyrusNajmabadi 已提交
496 497 498 499
                {
                    var filePath = ReadString();
                    var start = ReadInteger();
                    var length = ReadInteger();
500

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

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

533
                return Location.None;
534
            }
C
CyrusNajmabadi 已提交
535

536 537
            public void FillLocationArray(PooledArrayBuilder<Location> builder)
                => FillArray(builder, _readLocation);
C
CyrusNajmabadi 已提交
538 539

            #endregion
540 541
        }
    }
T
Tomas Matousek 已提交
542
}