CSharpCompilation.cs 133.5 KB
Newer Older
1
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.
P
Pilchie 已提交
2 3 4 5 6 7 8 9 10

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
11
using System.Reflection.Metadata;
P
Pilchie 已提交
12 13
using System.Threading;
using System.Threading.Tasks;
14 15 16 17 18 19 20
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Emit;
T
Tomas Matousek 已提交
21
using Microsoft.CodeAnalysis.PooledObjects;
22
using Microsoft.CodeAnalysis.Symbols;
23
using static Microsoft.CodeAnalysis.CSharp.Binder;
24 25
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
P
Pilchie 已提交
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44

namespace Microsoft.CodeAnalysis.CSharp
{
    /// <summary>
    /// The compilation object is an immutable representation of a single invocation of the
    /// compiler. Although immutable, a compilation is also on-demand, and will realize and cache
    /// data as necessary. A compilation can produce a new compilation from existing compilation
    /// with the application of small deltas. In many cases, it is more efficient than creating a
    /// new compilation from scratch, as the new compilation can reuse information from the old
    /// compilation.
    /// </summary>
    public sealed partial class CSharpCompilation : Compilation
    {
        // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
        //
        // Changes to the public interface of this class should remain synchronized with the VB
        // version. Do not make any changes to the public interface without making the corresponding
        // change to the VB version.
        //
45
        // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
P
Pilchie 已提交
46

T
TomasMatousek 已提交
47 48
        internal static readonly ParallelOptions DefaultParallelOptions = new ParallelOptions();

49 50
        private readonly CSharpCompilationOptions _options;
        private readonly Lazy<Imports> _globalImports;
A
Andrew Casey 已提交
51
        private readonly Lazy<Imports> _previousSubmissionImports;
52 53
        private readonly Lazy<AliasSymbol> _globalNamespaceAlias;  // alias symbol used to resolve "global::".
        private readonly Lazy<ImplicitNamedTypeSymbol> _scriptClass;
P
Pilchie 已提交
54 55 56 57

        // All imports (using directives and extern aliases) in syntax trees in this compilation.
        // NOTE: We need to de-dup since the Imports objects that populate the list may be GC'd
        // and re-created.
58
        private ConcurrentSet<ImportInfo> _lazyImportInfos;
P
Pilchie 已提交
59 60 61

        // Cache the CLS diagnostics for the whole compilation so they aren't computed repeatedly.
        // NOTE: Presently, we do not cache the per-tree diagnostics.
62
        private ImmutableArray<Diagnostic> _lazyClsComplianceDiagnostics;
P
Pilchie 已提交
63

64
        private Conversions _conversions;
P
Pilchie 已提交
65 66 67 68
        internal Conversions Conversions
        {
            get
            {
69
                if (_conversions == null)
P
Pilchie 已提交
70
                {
71
                    Interlocked.CompareExchange(ref _conversions, new BuckStopsHereBinder(this).Conversions, null);
P
Pilchie 已提交
72 73
                }

74
                return _conversions;
P
Pilchie 已提交
75 76 77 78 79 80
            }
        }

        /// <summary>
        /// Manages anonymous types declared in this compilation. Unifies types that are structurally equivalent.
        /// </summary>
81
        private readonly AnonymousTypeManager _anonymousTypeManager;
P
Pilchie 已提交
82

83
        private NamespaceSymbol _lazyGlobalNamespace;
P
Pilchie 已提交
84 85 86 87 88 89 90 91 92

        internal readonly BuiltInOperators builtInOperators;

        /// <summary>
        /// The <see cref="SourceAssemblySymbol"/> for this compilation. Do not access directly, use Assembly property
        /// instead. This field is lazily initialized by ReferenceManager, ReferenceManager.CacheLockObject must be locked
        /// while ReferenceManager "calculates" the value and assigns it, several threads must not perform duplicate
        /// "calculation" simultaneously.
        /// </summary>
93
        private SourceAssemblySymbol _lazyAssemblySymbol;
P
Pilchie 已提交
94 95 96 97

        /// <summary>
        /// Holds onto data related to reference binding.
        /// The manager is shared among multiple compilations that we expect to have the same result of reference binding.
98
        /// In most cases this can be determined without performing the binding. If the compilation however contains a circular
P
Pilchie 已提交
99
        /// metadata reference (a metadata reference that refers back to the compilation) we need to avoid sharing of the binding results.
100
        /// We do so by creating a new reference manager for such compilation.
P
Pilchie 已提交
101
        /// </summary>
102
        private ReferenceManager _referenceManager;
P
Pilchie 已提交
103

104 105
        private readonly SyntaxAndDeclarationManager _syntaxAndDeclarations;

P
Pilchie 已提交
106 107 108
        /// <summary>
        /// Contains the main method of this assembly, if there is one.
        /// </summary>
109
        private EntryPoint _lazyEntryPoint;
P
Pilchie 已提交
110

111
        /// <summary>
112
        /// The set of trees for which a <see cref="CompilationUnitCompletedEvent"/> has been added to the queue.
113
        /// </summary>
114
        private HashSet<SyntaxTree> _lazyCompilationUnitCompletedTrees;
115

P
Pilchie 已提交
116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
        public override string Language
        {
            get
            {
                return LanguageNames.CSharp;
            }
        }

        public override bool IsCaseSensitive
        {
            get
            {
                return true;
            }
        }

        /// <summary>
133
        /// The options the compilation was created with.
P
Pilchie 已提交
134 135 136 137 138
        /// </summary>
        public new CSharpCompilationOptions Options
        {
            get
            {
139
                return _options;
P
Pilchie 已提交
140 141 142 143 144 145 146
            }
        }

        internal AnonymousTypeManager AnonymousTypeManager
        {
            get
            {
147
                return _anonymousTypeManager;
P
Pilchie 已提交
148 149 150
            }
        }

151 152 153 154 155 156 157 158
        internal override CommonAnonymousTypeManager CommonAnonymousTypeManager
        {
            get
            {
                return AnonymousTypeManager;
            }
        }

159 160 161 162 163 164 165
        /// <summary>
        /// True when the compiler is run in "strict" mode, in which it enforces the language specification
        /// in some cases even at the expense of full compatibility. Such differences typically arise when
        /// earlier versions of the compiler failed to enforce the full language specification.
        /// </summary>
        internal bool FeatureStrictEnabled => Feature("strict") != null;

V
vsadov 已提交
166 167 168 169 170 171
        /// <summary>
        /// True when "peverify-compat" is set
        /// With this flag we will avoid certain patterns known not be compatible with PEVerify.
        /// The code may be less efficient and may deviate from spec in corner cases.
        /// The flag is only to be used if PEVerify pass is extremely important.
        /// </summary>
V
vsadov 已提交
172 173
        internal bool FeaturePEVerifyCompatEnabled => Feature("peverify-compat") != null;

174 175 176 177 178
        /// <summary>
        /// The language version that was used to parse the syntax trees of this compilation.
        /// </summary>
        public LanguageVersion LanguageVersion
        {
C
Cyrus Najmabadi 已提交
179
            get;
180 181
        }

182
        protected override INamedTypeSymbol CommonCreateErrorTypeSymbol(INamespaceOrTypeSymbol container, string name, int arity)
P
Pilchie 已提交
183
        {
184
            return new ExtendedErrorTypeSymbol(
185
                       container.EnsureCSharpSymbolOrNull<INamespaceOrTypeSymbol, NamespaceOrTypeSymbol>(nameof(container)),
186 187 188 189 190 191
                       name, arity, errorInfo: null);
        }

        protected override INamespaceSymbol CommonCreateErrorNamespaceSymbol(INamespaceSymbol container, string name)
        {
            return new MissingNamespaceSymbol(
192
                       container.EnsureCSharpSymbolOrNull<INamespaceSymbol, NamespaceSymbol>(nameof(container)),
193
                       name);
P
Pilchie 已提交
194 195 196 197
        }

        #region Constructors and Factories

198
        private static readonly CSharpCompilationOptions s_defaultOptions = new CSharpCompilationOptions(OutputKind.ConsoleApplication);
199
        private static readonly CSharpCompilationOptions s_defaultSubmissionOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithReferencesSupersedeLowerVersions(true);
P
Pilchie 已提交
200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216

        /// <summary>
        /// Creates a new compilation from scratch. Methods such as AddSyntaxTrees or AddReferences
        /// on the returned object will allow to continue building up the Compilation incrementally.
        /// </summary>
        /// <param name="assemblyName">Simple assembly name.</param>
        /// <param name="syntaxTrees">The syntax trees with the source code for the new compilation.</param>
        /// <param name="references">The references for the new compilation.</param>
        /// <param name="options">The compiler options to use.</param>
        /// <returns>A new compilation.</returns>
        public static CSharpCompilation Create(
            string assemblyName,
            IEnumerable<SyntaxTree> syntaxTrees = null,
            IEnumerable<MetadataReference> references = null,
            CSharpCompilationOptions options = null)
        {
            return Create(
217
                assemblyName,
218
                options ?? s_defaultOptions,
219
                syntaxTrees,
220 221 222 223
                references,
                previousSubmission: null,
                returnType: null,
                hostObjectType: null,
P
Pilchie 已提交
224 225 226 227 228 229
                isSubmission: false);
        }

        /// <summary>
        /// Creates a new compilation that can be used in scripting.
        /// </summary>
230
        public static CSharpCompilation CreateScriptCompilation(
P
Pilchie 已提交
231 232 233 234
            string assemblyName,
            SyntaxTree syntaxTree = null,
            IEnumerable<MetadataReference> references = null,
            CSharpCompilationOptions options = null,
235
            CSharpCompilation previousScriptCompilation = null,
P
Pilchie 已提交
236
            Type returnType = null,
237
            Type globalsType = null)
P
Pilchie 已提交
238 239
        {
            CheckSubmissionOptions(options);
240
            ValidateScriptCompilationParameters(previousScriptCompilation, returnType, ref globalsType);
P
Pilchie 已提交
241 242 243

            return Create(
                assemblyName,
244
                options?.WithReferencesSupersedeLowerVersions(true) ?? s_defaultSubmissionOptions,
P
Pilchie 已提交
245 246
                (syntaxTree != null) ? new[] { syntaxTree } : SpecializedCollections.EmptyEnumerable<SyntaxTree>(),
                references,
C
CyrusNajmabadi 已提交
247 248
                previousScriptCompilation,
                returnType,
249
                globalsType,
P
Pilchie 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263
                isSubmission: true);
        }

        private static CSharpCompilation Create(
            string assemblyName,
            CSharpCompilationOptions options,
            IEnumerable<SyntaxTree> syntaxTrees,
            IEnumerable<MetadataReference> references,
            CSharpCompilation previousSubmission,
            Type returnType,
            Type hostObjectType,
            bool isSubmission)
        {
            Debug.Assert(options != null);
264
            Debug.Assert(!isSubmission || options.ReferencesSupersedeLowerVersions);
P
Pilchie 已提交
265 266 267 268 269 270 271 272 273 274 275 276

            var validatedReferences = ValidateReferences<CSharpCompilationReference>(references);

            var compilation = new CSharpCompilation(
                assemblyName,
                options,
                validatedReferences,
                previousSubmission,
                returnType,
                hostObjectType,
                isSubmission,
                referenceManager: null,
277 278 279 280 281 282 283 284
                reuseReferenceManager: false,
                syntaxAndDeclarations: new SyntaxAndDeclarationManager(
                    ImmutableArray<SyntaxTree>.Empty,
                    options.ScriptClassName,
                    options.SourceReferenceResolver,
                    CSharp.MessageProvider.Instance,
                    isSubmission,
                    state: null));
P
Pilchie 已提交
285 286 287 288 289 290

            if (syntaxTrees != null)
            {
                compilation = compilation.AddSyntaxTrees(syntaxTrees);
            }

291
            Debug.Assert((object)compilation._lazyAssemblySymbol == null);
P
Pilchie 已提交
292 293 294 295 296 297 298 299 300 301 302 303
            return compilation;
        }

        private CSharpCompilation(
            string assemblyName,
            CSharpCompilationOptions options,
            ImmutableArray<MetadataReference> references,
            CSharpCompilation previousSubmission,
            Type submissionReturnType,
            Type hostObjectType,
            bool isSubmission,
            ReferenceManager referenceManager,
304
            bool reuseReferenceManager,
305
            SyntaxAndDeclarationManager syntaxAndDeclarations,
306
            AsyncQueue<CompilationEvent> eventQueue = null)
307
            : base(assemblyName, references, SyntaxTreeCommonFeatures(syntaxAndDeclarations.ExternalSyntaxTrees), isSubmission, eventQueue)
P
Pilchie 已提交
308
        {
309
            WellKnownMemberSignatureComparer = new WellKnownMembersSignatureComparer(this);
310
            _options = options;
P
Pilchie 已提交
311

312 313
            this.builtInOperators = new BuiltInOperators(this);
            _scriptClass = new Lazy<ImplicitNamedTypeSymbol>(BindScriptClass);
A
Andrew Casey 已提交
314 315
            _globalImports = new Lazy<Imports>(BindGlobalImports);
            _previousSubmissionImports = new Lazy<Imports>(ExpandPreviousSubmissionImports);
316 317
            _globalNamespaceAlias = new Lazy<AliasSymbol>(CreateGlobalNamespaceAlias);
            _anonymousTypeManager = new AnonymousTypeManager(this);
318
            this.LanguageVersion = CommonLanguageVersion(syntaxAndDeclarations.ExternalSyntaxTrees);
P
Pilchie 已提交
319

320 321 322
            if (isSubmission)
            {
                Debug.Assert(previousSubmission == null || previousSubmission.HostObjectType == hostObjectType);
323
                this.ScriptCompilationInfo = new CSharpScriptCompilationInfo(previousSubmission, submissionReturnType, hostObjectType);
324 325 326 327 328
            }
            else
            {
                Debug.Assert(previousSubmission == null && submissionReturnType == null && hostObjectType == null);
            }
P
Pilchie 已提交
329

330 331 332 333
            if (reuseReferenceManager)
            {
                referenceManager.AssertCanReuseForCompilation(this);
                _referenceManager = referenceManager;
P
Pilchie 已提交
334
            }
335 336 337 338
            else
            {
                _referenceManager = new ReferenceManager(
                    MakeSourceAssemblySimpleName(),
339 340
                    this.Options.AssemblyIdentityComparer,
                    observedMetadata: referenceManager?.ObservedMetadata);
341 342
            }

343 344
            _syntaxAndDeclarations = syntaxAndDeclarations;

345
            Debug.Assert((object)_lazyAssemblySymbol == null);
346
            if (EventQueue != null) EventQueue.TryEnqueue(new CompilationStartedEvent(this));
P
Pilchie 已提交
347 348
        }

349 350 351 352 353 354 355 356 357 358 359 360
        internal override void ValidateDebugEntryPoint(IMethodSymbol debugEntryPoint, DiagnosticBag diagnostics)
        {
            Debug.Assert(debugEntryPoint != null);

            // Debug entry point has to be a method definition from this compilation.
            var methodSymbol = debugEntryPoint as MethodSymbol;
            if (methodSymbol?.DeclaringCompilation != this || !methodSymbol.IsDefinition)
            {
                diagnostics.Add(ErrorCode.ERR_DebugEntryPointNotSourceMethodDefinition, Location.None);
            }
        }

361 362 363 364 365 366 367 368 369 370 371 372
        private static LanguageVersion CommonLanguageVersion(ImmutableArray<SyntaxTree> syntaxTrees)
        {
            LanguageVersion? result = null;
            foreach (var tree in syntaxTrees)
            {
                var version = ((CSharpParseOptions)tree.Options).LanguageVersion;
                if (result == null)
                {
                    result = version;
                }
                else if (result != version)
                {
373
                    throw new ArgumentException(CodeAnalysisResources.InconsistentLanguageVersions, nameof(syntaxTrees));
374 375 376
                }
            }

G
gafter 已提交
377
            return result ?? LanguageVersion.Default.MapSpecifiedToEffectiveVersion();
378 379
        }

P
Pilchie 已提交
380 381 382 383 384 385 386
        /// <summary>
        /// Create a duplicate of this compilation with different symbol instances.
        /// </summary>
        public new CSharpCompilation Clone()
        {
            return new CSharpCompilation(
                this.AssemblyName,
387
                _options,
P
Pilchie 已提交
388
                this.ExternalReferences,
389
                this.PreviousSubmission,
P
Pilchie 已提交
390 391 392
                this.SubmissionReturnType,
                this.HostObjectType,
                this.IsSubmission,
393
                _referenceManager,
394 395
                reuseReferenceManager: true,
                syntaxAndDeclarations: _syntaxAndDeclarations);
P
Pilchie 已提交
396 397
        }

398 399 400 401
        private CSharpCompilation Update(
            ReferenceManager referenceManager,
            bool reuseReferenceManager,
            SyntaxAndDeclarationManager syntaxAndDeclarations)
P
Pilchie 已提交
402 403 404
        {
            return new CSharpCompilation(
                this.AssemblyName,
405
                _options,
P
Pilchie 已提交
406
                this.ExternalReferences,
407
                this.PreviousSubmission,
P
Pilchie 已提交
408 409 410
                this.SubmissionReturnType,
                this.HostObjectType,
                this.IsSubmission,
411 412 413
                referenceManager,
                reuseReferenceManager,
                syntaxAndDeclarations);
P
Pilchie 已提交
414 415 416 417 418 419 420
        }

        /// <summary>
        /// Creates a new compilation with the specified name.
        /// </summary>
        public new CSharpCompilation WithAssemblyName(string assemblyName)
        {
421 422
            // Can't reuse references since the source assembly name changed and the referenced symbols might
            // have internals-visible-to relationship with this compilation or they might had a circular reference
P
Pilchie 已提交
423 424 425 426
            // to this compilation.

            return new CSharpCompilation(
                assemblyName,
427
                _options,
P
Pilchie 已提交
428
                this.ExternalReferences,
429
                this.PreviousSubmission,
P
Pilchie 已提交
430 431 432
                this.SubmissionReturnType,
                this.HostObjectType,
                this.IsSubmission,
433
                _referenceManager,
434 435
                reuseReferenceManager: assemblyName == this.AssemblyName,
                syntaxAndDeclarations: _syntaxAndDeclarations);
P
Pilchie 已提交
436 437 438 439 440 441
        }

        /// <summary>
        /// Creates a new compilation with the specified references.
        /// </summary>
        /// <remarks>
442 443 444
        /// The new <see cref="CSharpCompilation"/> will query the given <see cref="MetadataReference"/> for the underlying
        /// metadata as soon as the are needed.
        ///
P
Pilchie 已提交
445 446 447 448 449 450 451 452 453 454 455
        /// The new compilation uses whatever metadata is currently being provided by the <see cref="MetadataReference"/>.
        /// E.g. if the current compilation references a metadata file that has changed since the creation of the compilation
        /// the new compilation is going to use the updated version, while the current compilation will be using the previous (it doesn't change).
        /// </remarks>
        public new CSharpCompilation WithReferences(IEnumerable<MetadataReference> references)
        {
            // References might have changed, don't reuse reference manager.
            // Don't even reuse observed metadata - let the manager query for the metadata again.

            return new CSharpCompilation(
                this.AssemblyName,
456
                _options,
P
Pilchie 已提交
457
                ValidateReferences<CSharpCompilationReference>(references),
458
                this.PreviousSubmission,
P
Pilchie 已提交
459 460 461 462
                this.SubmissionReturnType,
                this.HostObjectType,
                this.IsSubmission,
                referenceManager: null,
463 464
                reuseReferenceManager: false,
                syntaxAndDeclarations: _syntaxAndDeclarations);
P
Pilchie 已提交
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479
        }

        /// <summary>
        /// Creates a new compilation with the specified references.
        /// </summary>
        public new CSharpCompilation WithReferences(params MetadataReference[] references)
        {
            return this.WithReferences((IEnumerable<MetadataReference>)references);
        }

        /// <summary>
        /// Creates a new compilation with the specified compilation options.
        /// </summary>
        public CSharpCompilation WithOptions(CSharpCompilationOptions options)
        {
480 481 482 483
            var oldOptions = this.Options;
            bool reuseReferenceManager = oldOptions.CanReuseCompilationReferenceManager(options);
            bool reuseSyntaxAndDeclarationManager = oldOptions.ScriptClassName == options.ScriptClassName &&
                oldOptions.SourceReferenceResolver == options.SourceReferenceResolver;
P
Pilchie 已提交
484 485 486 487 488

            return new CSharpCompilation(
                this.AssemblyName,
                options,
                this.ExternalReferences,
489
                this.PreviousSubmission,
P
Pilchie 已提交
490 491 492
                this.SubmissionReturnType,
                this.HostObjectType,
                this.IsSubmission,
493
                _referenceManager,
494 495 496 497 498 499 500 501 502 503
                reuseReferenceManager,
                reuseSyntaxAndDeclarationManager ?
                    _syntaxAndDeclarations :
                    new SyntaxAndDeclarationManager(
                        _syntaxAndDeclarations.ExternalSyntaxTrees,
                        options.ScriptClassName,
                        options.SourceReferenceResolver,
                        _syntaxAndDeclarations.MessageProvider,
                        _syntaxAndDeclarations.IsSubmission,
                        state: null));
P
Pilchie 已提交
504 505 506 507 508
        }

        /// <summary>
        /// Returns a new compilation with the given compilation set as the previous submission.
        /// </summary>
509
        public CSharpCompilation WithScriptCompilationInfo(CSharpScriptCompilationInfo info)
P
Pilchie 已提交
510
        {
511
            if (info == ScriptCompilationInfo)
P
Pilchie 已提交
512
            {
513
                return this;
P
Pilchie 已提交
514
            }
C
CyrusNajmabadi 已提交
515

P
Pilchie 已提交
516 517 518 519
            // Reference binding doesn't depend on previous submission so we can reuse it.

            return new CSharpCompilation(
                this.AssemblyName,
520
                _options,
P
Pilchie 已提交
521
                this.ExternalReferences,
522
                info?.PreviousScriptCompilation,
523
                info?.ReturnTypeOpt,
524 525
                info?.GlobalsType,
                info != null,
526
                _referenceManager,
527 528
                reuseReferenceManager: true,
                syntaxAndDeclarations: _syntaxAndDeclarations);
P
Pilchie 已提交
529 530
        }

531 532 533
        /// <summary>
        /// Returns a new compilation with a given event queue.
        /// </summary>
534
        internal override Compilation WithEventQueue(AsyncQueue<CompilationEvent> eventQueue)
535 536 537
        {
            return new CSharpCompilation(
                this.AssemblyName,
538
                _options,
539
                this.ExternalReferences,
540
                this.PreviousSubmission,
541 542 543
                this.SubmissionReturnType,
                this.HostObjectType,
                this.IsSubmission,
544
                _referenceManager,
545
                reuseReferenceManager: true,
546
                syntaxAndDeclarations: _syntaxAndDeclarations,
547 548 549
                eventQueue: eventQueue);
        }

P
Pilchie 已提交
550 551 552 553
        #endregion

        #region Submission

554 555 556 557
        public new CSharpScriptCompilationInfo ScriptCompilationInfo { get; }
        internal override ScriptCompilationInfo CommonScriptCompilationInfo => ScriptCompilationInfo;

        internal CSharpCompilation PreviousSubmission => ScriptCompilationInfo?.PreviousScriptCompilation;
P
Pilchie 已提交
558

559
        internal override bool HasSubmissionResult()
P
Pilchie 已提交
560
        {
561
            Debug.Assert(IsSubmission);
P
Pilchie 已提交
562

563 564
            // A submission may be empty or comprised of a single script file.
            var tree = _syntaxAndDeclarations.ExternalSyntaxTrees.SingleOrDefault();
T
Tomas Matousek 已提交
565
            if (tree == null)
P
Pilchie 已提交
566
            {
567
                return false;
P
Pilchie 已提交
568 569
            }

570 571 572 573 574
            var root = tree.GetCompilationUnitRoot();
            if (root.HasErrors)
            {
                return false;
            }
T
Tomas Matousek 已提交
575

C
Charles Stoner 已提交
576
            // Are there any top-level return statements?
577
            if (root.DescendantNodes(n => n is GlobalStatementSyntax || n is StatementSyntax || n is CompilationUnitSyntax).Any(n => n.IsKind(SyntaxKind.ReturnStatement)))
P
Pilchie 已提交
578
            {
579
                return true;
P
Pilchie 已提交
580 581
            }

582 583 584
            // Is there a trailing expression?
            var lastGlobalStatement = (GlobalStatementSyntax)root.Members.LastOrDefault(m => m.IsKind(SyntaxKind.GlobalStatement));
            if (lastGlobalStatement != null)
P
Pilchie 已提交
585
            {
586 587 588 589 590 591 592 593 594 595 596 597
                var statement = lastGlobalStatement.Statement;
                if (statement.IsKind(SyntaxKind.ExpressionStatement))
                {
                    var expressionStatement = (ExpressionStatementSyntax)statement;
                    if (expressionStatement.SemicolonToken.IsMissing)
                    {
                        var model = GetSemanticModel(tree);
                        var expression = expressionStatement.Expression;
                        var info = model.GetTypeInfo(expression);
                        return info.ConvertedType?.SpecialType != SpecialType.System_Void;
                    }
                }
P
Pilchie 已提交
598 599
            }

600
            return false;
P
Pilchie 已提交
601 602 603 604 605 606 607 608 609 610 611
        }

        #endregion

        #region Syntax Trees (maintain an ordered list)

        /// <summary>
        /// The syntax trees (parsed from source code) that this compilation was created with.
        /// </summary>
        public new ImmutableArray<SyntaxTree> SyntaxTrees
        {
612
            get { return _syntaxAndDeclarations.GetLazyState().SyntaxTrees; }
P
Pilchie 已提交
613 614 615 616 617 618 619 620
        }

        /// <summary>
        /// Returns true if this compilation contains the specified tree.  False otherwise.
        /// </summary>
        public new bool ContainsSyntaxTree(SyntaxTree syntaxTree)
        {
            var cstree = syntaxTree as SyntaxTree;
621
            return cstree != null && _syntaxAndDeclarations.GetLazyState().RootNamespaces.ContainsKey(cstree);
P
Pilchie 已提交
622 623 624 625 626 627 628 629 630 631 632 633 634 635 636
        }

        /// <summary>
        /// Creates a new compilation with additional syntax trees.
        /// </summary>
        public new CSharpCompilation AddSyntaxTrees(params SyntaxTree[] trees)
        {
            return AddSyntaxTrees((IEnumerable<SyntaxTree>)trees);
        }

        /// <summary>
        /// Creates a new compilation with additional syntax trees.
        /// </summary>
        public new CSharpCompilation AddSyntaxTrees(IEnumerable<SyntaxTree> trees)
        {
637
            if (trees == null)
P
Pilchie 已提交
638
            {
639
                throw new ArgumentNullException(nameof(trees));
640
            }
P
Pilchie 已提交
641

642 643 644 645
            if (trees.IsEmpty())
            {
                return this;
            }
P
Pilchie 已提交
646

647 648 649 650 651 652 653 654 655 656
            // This HashSet is needed so that we don't allow adding the same tree twice
            // with a single call to AddSyntaxTrees.  Rather than using a separate HashSet,
            // ReplaceSyntaxTrees can just check against ExternalSyntaxTrees, because we
            // only allow replacing a single tree at a time.
            var externalSyntaxTrees = PooledHashSet<SyntaxTree>.GetInstance();
            var syntaxAndDeclarations = _syntaxAndDeclarations;
            externalSyntaxTrees.AddAll(syntaxAndDeclarations.ExternalSyntaxTrees);
            bool reuseReferenceManager = true;
            int i = 0;
            foreach (var tree in trees.Cast<CSharpSyntaxTree>())
657
            {
658
                if (tree == null)
P
Pilchie 已提交
659
                {
660 661
                    throw new ArgumentNullException($"{nameof(trees)}[{i}]");
                }
P
Pilchie 已提交
662

663 664 665 666
                if (!tree.HasCompilationUnitRoot)
                {
                    throw new ArgumentException(CSharpResources.TreeMustHaveARootNodeWith, $"{nameof(trees)}[{i}]");
                }
667

668 669 670
                if (externalSyntaxTrees.Contains(tree))
                {
                    throw new ArgumentException(CSharpResources.SyntaxTreeAlreadyPresent, $"{nameof(trees)}[{i}]");
P
Pilchie 已提交
671
                }
672

673
                if (this.IsSubmission && tree.Options.Kind == SourceCodeKind.Regular)
P
Pilchie 已提交
674
                {
675
                    throw new ArgumentException(CSharpResources.SubmissionCanOnlyInclude, $"{nameof(trees)}[{i}]");
P
Pilchie 已提交
676
                }
677

678 679 680 681
                externalSyntaxTrees.Add(tree);
                reuseReferenceManager &= !tree.HasReferenceOrLoadDirectives;

                i++;
682
            }
683 684 685
            externalSyntaxTrees.Free();

            if (this.IsSubmission && i > 1)
686
            {
687
                throw new ArgumentException(CSharpResources.SubmissionCanHaveAtMostOne, nameof(trees));
P
Pilchie 已提交
688 689
            }

690 691 692
            syntaxAndDeclarations = syntaxAndDeclarations.AddSyntaxTrees(trees);

            return Update(_referenceManager, reuseReferenceManager, syntaxAndDeclarations);
P
Pilchie 已提交
693 694 695 696
        }

        /// <summary>
        /// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees
697
        /// added later.
P
Pilchie 已提交
698 699 700 701 702 703 704 705
        /// </summary>
        public new CSharpCompilation RemoveSyntaxTrees(params SyntaxTree[] trees)
        {
            return RemoveSyntaxTrees((IEnumerable<SyntaxTree>)trees);
        }

        /// <summary>
        /// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees
706
        /// added later.
P
Pilchie 已提交
707 708 709
        /// </summary>
        public new CSharpCompilation RemoveSyntaxTrees(IEnumerable<SyntaxTree> trees)
        {
710
            if (trees == null)
P
Pilchie 已提交
711
            {
712
                throw new ArgumentNullException(nameof(trees));
713
            }
P
Pilchie 已提交
714

715 716 717 718
            if (trees.IsEmpty())
            {
                return this;
            }
P
Pilchie 已提交
719

720 721 722 723 724 725 726 727 728
            var removeSet = PooledHashSet<SyntaxTree>.GetInstance();
            // This HashSet is needed so that we don't allow adding the same tree twice
            // with a single call to AddSyntaxTrees.  Rather than using a separate HashSet,
            // ReplaceSyntaxTrees can just check against ExternalSyntaxTrees, because we
            // only allow replacing a single tree at a time.
            var externalSyntaxTrees = PooledHashSet<SyntaxTree>.GetInstance();
            var syntaxAndDeclarations = _syntaxAndDeclarations;
            externalSyntaxTrees.AddAll(syntaxAndDeclarations.ExternalSyntaxTrees);
            bool reuseReferenceManager = true;
729
            int i = 0;
730
            foreach (var tree in trees.Cast<CSharpSyntaxTree>())
731
            {
732
                if (!externalSyntaxTrees.Contains(tree))
P
Pilchie 已提交
733
                {
734 735 736 737 738 739 740 741
                    // Check to make sure this is not a #load'ed tree.
                    var loadedSyntaxTreeMap = syntaxAndDeclarations.GetLazyState().LoadedSyntaxTreeMap;
                    if (SyntaxAndDeclarationManager.IsLoadedSyntaxTree(tree, loadedSyntaxTreeMap))
                    {
                        throw new ArgumentException(string.Format(CSharpResources.SyntaxTreeFromLoadNoRemoveReplace, tree), $"{nameof(trees)}[{i}]");
                    }

                    throw new ArgumentException(string.Format(CSharpResources.SyntaxTreeNotFoundTo, tree), $"{nameof(trees)}[{i}]");
P
Pilchie 已提交
742
                }
743

744 745
                removeSet.Add(tree);
                reuseReferenceManager &= !tree.HasReferenceOrLoadDirectives;
P
Pilchie 已提交
746

747
                i++;
P
Pilchie 已提交
748
            }
749
            externalSyntaxTrees.Free();
P
Pilchie 已提交
750

751 752 753 754
            syntaxAndDeclarations = syntaxAndDeclarations.RemoveSyntaxTrees(removeSet);
            removeSet.Free();

            return Update(_referenceManager, reuseReferenceManager, syntaxAndDeclarations);
P
Pilchie 已提交
755 756 757 758
        }

        /// <summary>
        /// Creates a new compilation without any syntax trees. Preserves metadata info
759
        /// from this compilation for use with trees added later.
P
Pilchie 已提交
760 761 762
        /// </summary>
        public new CSharpCompilation RemoveAllSyntaxTrees()
        {
763 764 765 766 767
            var syntaxAndDeclarations = _syntaxAndDeclarations;
            return Update(
                _referenceManager,
                reuseReferenceManager: !syntaxAndDeclarations.MayHaveReferenceDirectives(),
                syntaxAndDeclarations: syntaxAndDeclarations.WithExternalSyntaxTrees(ImmutableArray<SyntaxTree>.Empty));
P
Pilchie 已提交
768 769 770 771 772 773 774
        }

        /// <summary>
        /// Creates a new compilation without the old tree but with the new tree.
        /// </summary>
        public new CSharpCompilation ReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree newTree)
        {
775 776 777
            // this is just to force a cast exception
            oldTree = (CSharpSyntaxTree)oldTree;
            newTree = (CSharpSyntaxTree)newTree;
P
Pilchie 已提交
778

779 780
            if (oldTree == null)
            {
781
                throw new ArgumentNullException(nameof(oldTree));
782
            }
P
Pilchie 已提交
783

784 785 786 787 788 789 790 791
            if (newTree == null)
            {
                return this.RemoveSyntaxTrees(oldTree);
            }
            else if (newTree == oldTree)
            {
                return this;
            }
P
Pilchie 已提交
792

793 794
            if (!newTree.HasCompilationUnitRoot)
            {
795
                throw new ArgumentException(CSharpResources.TreeMustHaveARootNodeWith, nameof(newTree));
796
            }
P
Pilchie 已提交
797

798 799 800 801 802 803 804 805 806 807 808 809 810
            var syntaxAndDeclarations = _syntaxAndDeclarations;
            var externalSyntaxTrees = syntaxAndDeclarations.ExternalSyntaxTrees;
            if (!externalSyntaxTrees.Contains(oldTree))
            {
                // Check to see if this is a #load'ed tree.
                var loadedSyntaxTreeMap = syntaxAndDeclarations.GetLazyState().LoadedSyntaxTreeMap;
                if (SyntaxAndDeclarationManager.IsLoadedSyntaxTree(oldTree, loadedSyntaxTreeMap))
                {
                    throw new ArgumentException(string.Format(CSharpResources.SyntaxTreeFromLoadNoRemoveReplace, oldTree), nameof(oldTree));
                }

                throw new ArgumentException(string.Format(CSharpResources.SyntaxTreeNotFoundTo, oldTree), nameof(oldTree));
            }
811

812
            if (externalSyntaxTrees.Contains(newTree))
813 814 815 816
            {
                throw new ArgumentException(CSharpResources.SyntaxTreeAlreadyPresent, nameof(newTree));
            }

817
            // TODO(tomat): Consider comparing #r's of the old and the new tree. If they are exactly the same we could still reuse.
818
            // This could be a perf win when editing a script file in the IDE. The services create a new compilation every keystroke
819
            // that replaces the tree with a new one.
820 821
            var reuseReferenceManager = !oldTree.HasReferenceOrLoadDirectives() && !newTree.HasReferenceOrLoadDirectives();
            syntaxAndDeclarations = syntaxAndDeclarations.ReplaceSyntaxTree(oldTree, newTree);
P
Pilchie 已提交
822

823 824
            return Update(_referenceManager, reuseReferenceManager, syntaxAndDeclarations);
        }
P
Pilchie 已提交
825

826 827 828 829
        internal override int GetSyntaxTreeOrdinal(SyntaxTree tree)
        {
            Debug.Assert(this.ContainsSyntaxTree(tree));
            return _syntaxAndDeclarations.GetLazyState().OrdinalMap[tree];
P
Pilchie 已提交
830 831 832 833 834 835 836 837 838 839 840 841 842
        }

        #endregion

        #region References

        internal override CommonReferenceManager CommonGetBoundReferenceManager()
        {
            return GetBoundReferenceManager();
        }

        internal new ReferenceManager GetBoundReferenceManager()
        {
843
            if ((object)_lazyAssemblySymbol == null)
P
Pilchie 已提交
844
            {
845 846
                _referenceManager.CreateSourceAssemblyForCompilation(this);
                Debug.Assert((object)_lazyAssemblySymbol != null);
P
Pilchie 已提交
847 848 849 850
            }

            // referenceManager can only be accessed after we initialized the lazyAssemblySymbol.
            // In fact, initialization of the assembly symbol might change the reference manager.
851
            return _referenceManager;
P
Pilchie 已提交
852 853 854 855 856
        }

        // for testing only:
        internal bool ReferenceManagerEquals(CSharpCompilation other)
        {
857
            return ReferenceEquals(_referenceManager, other._referenceManager);
P
Pilchie 已提交
858 859 860 861 862 863 864 865 866 867
        }

        public override ImmutableArray<MetadataReference> DirectiveReferences
        {
            get
            {
                return GetBoundReferenceManager().DirectiveReferences;
            }
        }

A
Andy Gocke 已提交
868 869
        internal override IDictionary<(string path, string content), MetadataReference> ReferenceDirectiveMap
            => GetBoundReferenceManager().ReferenceDirectiveMap;
P
Pilchie 已提交
870 871 872 873 874 875 876 877 878 879 880 881 882 883 884

        // for testing purposes
        internal IEnumerable<string> ExternAliases
        {
            get
            {
                return GetBoundReferenceManager().ExternAliases;
            }
        }

        /// <summary>
        /// Gets the <see cref="AssemblySymbol"/> or <see cref="ModuleSymbol"/> for a metadata reference used to create this compilation.
        /// </summary>
        /// <returns><see cref="AssemblySymbol"/> or <see cref="ModuleSymbol"/> corresponding to the given reference or null if there is none.</returns>
        /// <remarks>
885
        /// Uses object identity when comparing two references.
P
Pilchie 已提交
886 887 888 889 890
        /// </remarks>
        internal new Symbol GetAssemblyOrModuleSymbol(MetadataReference reference)
        {
            if (reference == null)
            {
891
                throw new ArgumentNullException(nameof(reference));
P
Pilchie 已提交
892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918
            }

            if (reference.Properties.Kind == MetadataImageKind.Assembly)
            {
                return GetBoundReferenceManager().GetReferencedAssemblySymbol(reference);
            }
            else
            {
                Debug.Assert(reference.Properties.Kind == MetadataImageKind.Module);
                int index = GetBoundReferenceManager().GetReferencedModuleIndex(reference);
                return index < 0 ? null : this.Assembly.Modules[index];
            }
        }

        public override IEnumerable<AssemblyIdentity> ReferencedAssemblyNames
        {
            get
            {
                return Assembly.Modules.SelectMany(module => module.GetReferencedAssemblies());
            }
        }

        /// <summary>
        /// All reference directives used in this compilation.
        /// </summary>
        internal override IEnumerable<ReferenceDirective> ReferenceDirectives
        {
919
            get { return this.Declarations.ReferenceDirectives; }
P
Pilchie 已提交
920 921 922 923 924 925
        }

        /// <summary>
        /// Returns a metadata reference that a given #r resolves to.
        /// </summary>
        /// <param name="directive">#r directive.</param>
926
        /// <returns>Metadata reference the specified directive resolves to, or null if the <paramref name="directive"/> doesn't match any #r directive in the compilation.</returns>
P
Pilchie 已提交
927 928
        public MetadataReference GetDirectiveReference(ReferenceDirectiveTriviaSyntax directive)
        {
929
            MetadataReference reference;
A
Andy Gocke 已提交
930
            return ReferenceDirectiveMap.TryGetValue((directive.SyntaxTree.FilePath, directive.File.ValueText), out reference) ? reference : null;
P
Pilchie 已提交
931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980
        }

        /// <summary>
        /// Creates a new compilation with additional metadata references.
        /// </summary>
        public new CSharpCompilation AddReferences(params MetadataReference[] references)
        {
            return (CSharpCompilation)base.AddReferences(references);
        }

        /// <summary>
        /// Creates a new compilation with additional metadata references.
        /// </summary>
        public new CSharpCompilation AddReferences(IEnumerable<MetadataReference> references)
        {
            return (CSharpCompilation)base.AddReferences(references);
        }

        /// <summary>
        /// Creates a new compilation without the specified metadata references.
        /// </summary>
        public new CSharpCompilation RemoveReferences(params MetadataReference[] references)
        {
            return (CSharpCompilation)base.RemoveReferences(references);
        }

        /// <summary>
        /// Creates a new compilation without the specified metadata references.
        /// </summary>
        public new CSharpCompilation RemoveReferences(IEnumerable<MetadataReference> references)
        {
            return (CSharpCompilation)base.RemoveReferences(references);
        }

        /// <summary>
        /// Creates a new compilation without any metadata references
        /// </summary>
        public new CSharpCompilation RemoveAllReferences()
        {
            return (CSharpCompilation)base.RemoveAllReferences();
        }

        /// <summary>
        /// Creates a new compilation with an old metadata reference replaced with a new metadata reference.
        /// </summary>
        public new CSharpCompilation ReplaceReference(MetadataReference oldReference, MetadataReference newReference)
        {
            return (CSharpCompilation)base.ReplaceReference(oldReference, newReference);
        }

981
        public override CompilationReference ToMetadataReference(ImmutableArray<string> aliases = default(ImmutableArray<string>), bool embedInteropTypes = false)
P
Pilchie 已提交
982
        {
983
            return new CSharpCompilationReference(this, aliases, embedInteropTypes);
P
Pilchie 已提交
984 985
        }

986 987 988
        /// <summary>
        /// Get all modules in this compilation, including the source module, added modules, and all
        /// modules of referenced assemblies that do not come from an assembly with an extern alias.
989
        /// Metadata imported from aliased assemblies is not visible at the source level except through
990 991 992 993
        /// the use of an extern alias directive. So exclude them from this list which is used to construct
        /// the global namespace.
        /// </summary>
        private void GetAllUnaliasedModules(ArrayBuilder<ModuleSymbol> modules)
P
Pilchie 已提交
994 995
        {
            // NOTE: This includes referenced modules - they count as modules of the compilation assembly.
996 997 998
            modules.AddRange(Assembly.Modules);

            var referenceManager = GetBoundReferenceManager();
P
Pilchie 已提交
999

1000
            for (int i = 0; i < referenceManager.ReferencedAssemblies.Length; i++)
P
Pilchie 已提交
1001
            {
1002
                if (referenceManager.DeclarationsAccessibleWithoutAlias(i))
P
Pilchie 已提交
1003
                {
1004
                    modules.AddRange(referenceManager.ReferencedAssemblies[i].Modules);
P
Pilchie 已提交
1005 1006
                }
            }
1007
        }
P
Pilchie 已提交
1008

1009 1010 1011 1012
        /// <summary>
        /// Return a list of assembly symbols than can be accessed without using an alias.
        /// For example:
        ///   1) /r:A.dll /r:B.dll -> A, B
1013 1014
        ///   2) /r:Goo=A.dll /r:B.dll -> B
        ///   3) /r:Goo=A.dll /r:A.dll -> A
1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026
        /// </summary>
        internal void GetUnaliasedReferencedAssemblies(ArrayBuilder<AssemblySymbol> assemblies)
        {
            var referenceManager = GetBoundReferenceManager();

            for (int i = 0; i < referenceManager.ReferencedAssemblies.Length; i++)
            {
                if (referenceManager.DeclarationsAccessibleWithoutAlias(i))
                {
                    assemblies.Add(referenceManager.ReferencedAssemblies[i]);
                }
            }
P
Pilchie 已提交
1027 1028 1029
        }

        /// <summary>
1030
        /// Gets the <see cref="MetadataReference"/> that corresponds to the assembly symbol.
P
Pilchie 已提交
1031 1032 1033
        /// </summary>
        public new MetadataReference GetMetadataReference(IAssemblySymbol assemblySymbol)
        {
1034
            return base.GetMetadataReference(assemblySymbol);
P
Pilchie 已提交
1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048
        }

        #endregion

        #region Symbols

        /// <summary>
        /// The AssemblySymbol that represents the assembly being created.
        /// </summary>
        internal SourceAssemblySymbol SourceAssembly
        {
            get
            {
                GetBoundReferenceManager();
1049
                return _lazyAssemblySymbol;
P
Pilchie 已提交
1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077
            }
        }

        /// <summary>
        /// The AssemblySymbol that represents the assembly being created.
        /// </summary>
        internal new AssemblySymbol Assembly
        {
            get
            {
                return SourceAssembly;
            }
        }

        /// <summary>
        /// Get a ModuleSymbol that refers to the module being created by compiling all of the code.
        /// By getting the GlobalNamespace property of that module, all of the namespaces and types
        /// defined in source code can be obtained.
        /// </summary>
        internal new ModuleSymbol SourceModule
        {
            get
            {
                return Assembly.Modules[0];
            }
        }

        /// <summary>
1078
        /// Gets the root namespace that contains all namespaces and types defined in source code or in
P
Pilchie 已提交
1079 1080 1081 1082 1083 1084
        /// referenced metadata, merged into a single namespace hierarchy.
        /// </summary>
        internal new NamespaceSymbol GlobalNamespace
        {
            get
            {
1085
                if ((object)_lazyGlobalNamespace == null)
P
Pilchie 已提交
1086
                {
1087
                    // Get the root namespace from each module, and merge them all together
1088
                    // Get all modules in this compilation, ones referenced directly by the compilation
1089
                    // as well as those referenced by all referenced assemblies.
1090

1091 1092 1093 1094 1095
                    var modules = ArrayBuilder<ModuleSymbol>.GetInstance();
                    GetAllUnaliasedModules(modules);

                    var result = MergedNamespaceSymbol.Create(
                        new NamespaceExtent(this),
1096
                        null,
1097 1098 1099 1100
                        modules.SelectDistinct(m => m.GlobalNamespace));

                    modules.Free();

1101
                    Interlocked.CompareExchange(ref _lazyGlobalNamespace, result, null);
P
Pilchie 已提交
1102 1103
                }

1104
                return _lazyGlobalNamespace;
P
Pilchie 已提交
1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
            }
        }

        /// <summary>
        /// Given for the specified module or assembly namespace, gets the corresponding compilation
        /// namespace (merged namespace representation for all namespace declarations and references
        /// with contributions for the namespaceSymbol).  Can return null if no corresponding
        /// namespace can be bound in this compilation with the same name.
        /// </summary>
        internal new NamespaceSymbol GetCompilationNamespace(INamespaceSymbol namespaceSymbol)
        {
            if (namespaceSymbol is NamespaceSymbol &&
                namespaceSymbol.NamespaceKind == NamespaceKind.Compilation &&
                namespaceSymbol.ContainingCompilation == this)
            {
                return (NamespaceSymbol)namespaceSymbol;
            }

            var containingNamespace = namespaceSymbol.ContainingNamespace;
            if (containingNamespace == null)
            {
                return this.GlobalNamespace;
            }

            var current = GetCompilationNamespace(containingNamespace);
            if ((object)current != null)
            {
                return current.GetNestedNamespace(namespaceSymbol.Name);
            }

            return null;
        }

1138
        private ConcurrentDictionary<string, NamespaceSymbol> _externAliasTargets;
P
Pilchie 已提交
1139 1140 1141

        internal bool GetExternAliasTarget(string aliasName, out NamespaceSymbol @namespace)
        {
1142
            if (_externAliasTargets == null)
P
Pilchie 已提交
1143
            {
1144
                Interlocked.CompareExchange(ref _externAliasTargets, new ConcurrentDictionary<string, NamespaceSymbol>(), null);
P
Pilchie 已提交
1145
            }
1146
            else if (_externAliasTargets.TryGetValue(aliasName, out @namespace))
P
Pilchie 已提交
1147 1148 1149 1150 1151
            {
                return !(@namespace is MissingNamespaceSymbol);
            }

            ArrayBuilder<NamespaceSymbol> builder = null;
1152 1153
            var referenceManager = GetBoundReferenceManager();
            for (int i = 0; i < referenceManager.ReferencedAssemblies.Length; i++)
P
Pilchie 已提交
1154
            {
1155
                if (referenceManager.AliasesOfReferencedAssemblies[i].Contains(aliasName))
P
Pilchie 已提交
1156 1157
                {
                    builder = builder ?? ArrayBuilder<NamespaceSymbol>.GetInstance();
1158
                    builder.Add(referenceManager.ReferencedAssemblies[i].GlobalNamespace);
P
Pilchie 已提交
1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170
                }
            }

            bool foundNamespace = builder != null;

            // We want to cache failures as well as successes so that subsequent incorrect extern aliases with the
            // same alias will have the same target.
            @namespace = foundNamespace
                ? MergedNamespaceSymbol.Create(new NamespaceExtent(this), namespacesToMerge: builder.ToImmutableAndFree(), containingNamespace: null, nameOpt: null)
                : new MissingNamespaceSymbol(new MissingModuleSymbol(new MissingAssemblySymbol(new AssemblyIdentity(System.Guid.NewGuid().ToString())), ordinal: -1));

            // Use GetOrAdd in case another thread beat us to the punch (i.e. should return the same object for the same alias, every time).
1171
            @namespace = _externAliasTargets.GetOrAdd(aliasName, @namespace);
P
Pilchie 已提交
1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183

            Debug.Assert(foundNamespace == !(@namespace is MissingNamespaceSymbol));

            return foundNamespace;
        }

        /// <summary>
        /// A symbol representing the implicit Script class. This is null if the class is not
        /// defined in the compilation.
        /// </summary>
        internal new NamedTypeSymbol ScriptClass
        {
1184
            get { return _scriptClass.Value; }
P
Pilchie 已提交
1185 1186 1187 1188
        }

        /// <summary>
        /// Resolves a symbol that represents script container (Script class). Uses the
1189
        /// full name of the container class stored in <see cref="CompilationOptions.ScriptClassName"/> to find the symbol.
P
Pilchie 已提交
1190 1191 1192 1193
        /// </summary>
        /// <returns>The Script class symbol or null if it is not defined.</returns>
        private ImplicitNamedTypeSymbol BindScriptClass()
        {
1194
            return (ImplicitNamedTypeSymbol)CommonBindScriptClass();
P
Pilchie 已提交
1195 1196
        }

1197 1198 1199 1200 1201 1202 1203
        internal bool IsSubmissionSyntaxTree(SyntaxTree tree)
        {
            Debug.Assert(tree != null);
            Debug.Assert(!this.IsSubmission || _syntaxAndDeclarations.ExternalSyntaxTrees.Length <= 1);
            return this.IsSubmission && tree == _syntaxAndDeclarations.ExternalSyntaxTrees.SingleOrDefault();
        }

A
Andrew Casey 已提交
1204 1205 1206 1207 1208 1209 1210 1211 1212 1213
        /// <summary>
        /// Global imports (including those from previous submissions, if there are any).
        /// </summary>
        internal Imports GlobalImports => _globalImports.Value;

        private Imports BindGlobalImports() => Imports.FromGlobalUsings(this);

        /// <summary>
        /// Imports declared by this submission (null if this isn't one).
        /// </summary>
A
Andrew Casey 已提交
1214
        internal Imports GetSubmissionImports()
1215
        {
A
Andrew Casey 已提交
1216 1217
            Debug.Assert(this.IsSubmission);
            Debug.Assert(_syntaxAndDeclarations.ExternalSyntaxTrees.Length <= 1);
A
Andrew Casey 已提交
1218

A
Andrew Casey 已提交
1219 1220 1221 1222 1223
            // A submission may be empty or comprised of a single script file.
            var tree = _syntaxAndDeclarations.ExternalSyntaxTrees.SingleOrDefault();
            if (tree == null)
            {
                return Imports.Empty;
A
Andrew Casey 已提交
1224
            }
A
Andrew Casey 已提交
1225 1226

            var binder = GetBinderFactory(tree).GetImportsBinder((CSharpSyntaxNode)tree.GetRoot());
1227
            return binder.GetImports(basesBeingResolved: null);
1228
        }
1229

A
Andrew Casey 已提交
1230 1231 1232
        /// <summary>
        /// Imports from all previous submissions.
        /// </summary>
A
Andrew Casey 已提交
1233
        internal Imports GetPreviousSubmissionImports() => _previousSubmissionImports.Value;
A
Andrew Casey 已提交
1234 1235

        private Imports ExpandPreviousSubmissionImports()
P
Pilchie 已提交
1236
        {
A
Andrew Casey 已提交
1237
            Debug.Assert(this.IsSubmission);
1238
            var previous = this.PreviousSubmission;
A
Andrew Casey 已提交
1239

1240
            if (previous == null)
P
Pilchie 已提交
1241
            {
A
Andrew Casey 已提交
1242
                return Imports.Empty;
P
Pilchie 已提交
1243
            }
A
Andrew Casey 已提交
1244

1245 1246
            return Imports.ExpandPreviousSubmissionImports(previous.GetPreviousSubmissionImports(), this).Concat(
                Imports.ExpandPreviousSubmissionImports(previous.GetSubmissionImports(), this));
P
Pilchie 已提交
1247 1248 1249 1250 1251 1252
        }

        internal AliasSymbol GlobalNamespaceAlias
        {
            get
            {
1253
                return _globalNamespaceAlias.Value;
P
Pilchie 已提交
1254 1255 1256 1257 1258 1259 1260 1261 1262 1263
            }
        }

        /// <summary>
        /// Get the symbol for the predefined type from the COR Library referenced by this compilation.
        /// </summary>
        internal new NamedTypeSymbol GetSpecialType(SpecialType specialType)
        {
            if (specialType <= SpecialType.None || specialType > SpecialType.Count)
            {
1264
                throw new ArgumentOutOfRangeException(nameof(specialType), $"Unexpected SpecialType: '{(int)specialType}'.");
P
Pilchie 已提交
1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277
            }

            var result = Assembly.GetSpecialType(specialType);
            Debug.Assert(result.SpecialType == specialType);
            return result;
        }

        /// <summary>
        /// Get the symbol for the predefined type member from the COR Library referenced by this compilation.
        /// </summary>
        internal Symbol GetSpecialTypeMember(SpecialMember specialMember)
        {
            return Assembly.GetSpecialTypeMember(specialMember);
1278 1279 1280 1281 1282
        }

        internal override ISymbol CommonGetSpecialTypeMember(SpecialMember specialMember)
        {
            return GetSpecialTypeMember(specialMember);
P
Pilchie 已提交
1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309
        }

        internal TypeSymbol GetTypeByReflectionType(Type type, DiagnosticBag diagnostics)
        {
            var result = Assembly.GetTypeByReflectionType(type, includeReferences: true);
            if ((object)result == null)
            {
                var errorType = new ExtendedErrorTypeSymbol(this, type.Name, 0, CreateReflectionTypeNotFoundError(type));
                diagnostics.Add(errorType.ErrorInfo, NoLocation.Singleton);
                result = errorType;
            }

            return result;
        }

        private static CSDiagnosticInfo CreateReflectionTypeNotFoundError(Type type)
        {
            // The type or namespace name '{0}' could not be found in the global namespace (are you missing an assembly reference?)
            return new CSDiagnosticInfo(
                ErrorCode.ERR_GlobalSingleTypeNameNotFound,
                new object[] { type.AssemblyQualifiedName },
                ImmutableArray<Symbol>.Empty,
                ImmutableArray<Location>.Empty
            );
        }

        // The type of host object model if available.
1310
        private TypeSymbol _lazyHostObjectTypeSymbol;
P
Pilchie 已提交
1311 1312 1313

        internal TypeSymbol GetHostObjectTypeSymbol()
        {
1314
            if (HostObjectType != null && (object)_lazyHostObjectTypeSymbol == null)
P
Pilchie 已提交
1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330
            {
                TypeSymbol symbol = Assembly.GetTypeByReflectionType(HostObjectType, includeReferences: true);

                if ((object)symbol == null)
                {
                    MetadataTypeName mdName = MetadataTypeName.FromNamespaceAndTypeName(HostObjectType.Namespace ?? String.Empty,
                                                                                        HostObjectType.Name,
                                                                                        useCLSCompliantNameArityEncoding: true);

                    symbol = new MissingMetadataTypeSymbol.TopLevelWithCustomErrorInfo(
                        new MissingAssemblySymbol(AssemblyIdentity.FromAssemblyDefinition(HostObjectType.GetTypeInfo().Assembly)).Modules[0],
                        ref mdName,
                        CreateReflectionTypeNotFoundError(HostObjectType),
                        SpecialType.None);
                }

1331
                Interlocked.CompareExchange(ref _lazyHostObjectTypeSymbol, symbol, null);
P
Pilchie 已提交
1332 1333
            }

1334
            return _lazyHostObjectTypeSymbol;
P
Pilchie 已提交
1335 1336
        }

1337
        internal SynthesizedInteractiveInitializerMethod GetSubmissionInitializer()
P
Pilchie 已提交
1338
        {
1339 1340 1341
            return (IsSubmission && (object)ScriptClass != null) ?
                ScriptClass.GetScriptInitializer() :
                null;
P
Pilchie 已提交
1342 1343 1344 1345 1346 1347 1348 1349
        }

        /// <summary>
        /// Gets the type within the compilation's assembly and all referenced assemblies (other than
        /// those that can only be referenced via an extern alias) using its canonical CLR metadata name.
        /// </summary>
        internal new NamedTypeSymbol GetTypeByMetadataName(string fullyQualifiedMetadataName)
        {
1350
            return this.Assembly.GetTypeByMetadataName(fullyQualifiedMetadataName, includeReferences: true, isWellKnownType: false, conflicts: out var _);
P
Pilchie 已提交
1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386
        }

        /// <summary>
        /// The TypeSymbol for the type 'dynamic' in this Compilation.
        /// </summary>
        internal new TypeSymbol DynamicType
        {
            get
            {
                return AssemblySymbol.DynamicType;
            }
        }

        /// <summary>
        /// The NamedTypeSymbol for the .NET System.Object type, which could have a TypeKind of
        /// Error if there was no COR Library in this Compilation.
        /// </summary>
        internal new NamedTypeSymbol ObjectType
        {
            get
            {
                return this.Assembly.ObjectType;
            }
        }

        internal bool DeclaresTheObjectClass
        {
            get
            {
                return SourceAssembly.DeclaresTheObjectClass;
            }
        }

        internal new MethodSymbol GetEntryPoint(CancellationToken cancellationToken)
        {
            EntryPoint entryPoint = GetEntryPointAndDiagnostics(cancellationToken);
1387
            return entryPoint?.MethodSymbol;
P
Pilchie 已提交
1388 1389 1390 1391
        }

        internal EntryPoint GetEntryPointAndDiagnostics(CancellationToken cancellationToken)
        {
C
Charles Stoner 已提交
1392
            if (!this.Options.OutputKind.IsApplication() && ((object)this.ScriptClass == null))
P
Pilchie 已提交
1393 1394 1395 1396 1397 1398 1399 1400 1401 1402
            {
                return null;
            }

            if (this.Options.MainTypeName != null && !this.Options.MainTypeName.IsValidClrTypeName())
            {
                Debug.Assert(!this.Options.Errors.IsDefaultOrEmpty);
                return new EntryPoint(null, ImmutableArray<Diagnostic>.Empty);
            }

1403
            if (_lazyEntryPoint == null)
P
Pilchie 已提交
1404 1405
            {
                ImmutableArray<Diagnostic> diagnostics;
C
Charles Stoner 已提交
1406
                var entryPoint = FindEntryPoint(cancellationToken, out diagnostics);
1407
                Interlocked.CompareExchange(ref _lazyEntryPoint, new EntryPoint(entryPoint, diagnostics), null);
P
Pilchie 已提交
1408 1409
            }

1410
            return _lazyEntryPoint;
P
Pilchie 已提交
1411 1412
        }

C
Charles Stoner 已提交
1413
        private MethodSymbol FindEntryPoint(CancellationToken cancellationToken, out ImmutableArray<Diagnostic> sealedDiagnostics)
P
Pilchie 已提交
1414
        {
C
Charles Stoner 已提交
1415 1416
            var diagnostics = DiagnosticBag.GetInstance();
            var entryPointCandidates = ArrayBuilder<MethodSymbol>.GetInstance();
P
Pilchie 已提交
1417

1418 1419 1420
            try
            {
                NamedTypeSymbol mainType;
P
Pilchie 已提交
1421

1422 1423
                string mainTypeName = this.Options.MainTypeName;
                NamespaceSymbol globalNamespace = this.SourceModule.GlobalNamespace;
P
Pilchie 已提交
1424

1425 1426 1427
                if (mainTypeName != null)
                {
                    // Global code is the entry point, ignore all other Mains.
C
Charles Stoner 已提交
1428 1429
                    var scriptClass = this.ScriptClass;
                    if (scriptClass != null)
P
Pilchie 已提交
1430
                    {
1431 1432
                        // CONSIDER: we could use the symbol instead of just the name.
                        diagnostics.Add(ErrorCode.WRN_MainIgnored, NoLocation.Singleton, mainTypeName);
C
Charles Stoner 已提交
1433
                        return scriptClass.GetScriptEntryPoint();
1434
                    }
P
Pilchie 已提交
1435

1436 1437 1438 1439
                    var mainTypeOrNamespace = globalNamespace.GetNamespaceOrTypeByQualifiedName(mainTypeName.Split('.')).OfMinimalArity();
                    if ((object)mainTypeOrNamespace == null)
                    {
                        diagnostics.Add(ErrorCode.ERR_MainClassNotFound, NoLocation.Singleton, mainTypeName);
C
Charles Stoner 已提交
1440
                        return null;
P
Pilchie 已提交
1441
                    }
1442 1443 1444

                    mainType = mainTypeOrNamespace as NamedTypeSymbol;
                    if ((object)mainType == null || mainType.IsGenericType || (mainType.TypeKind != TypeKind.Class && mainType.TypeKind != TypeKind.Struct))
P
Pilchie 已提交
1445
                    {
1446
                        diagnostics.Add(ErrorCode.ERR_MainClassNotClass, mainTypeOrNamespace.Locations.First(), mainTypeOrNamespace);
C
Charles Stoner 已提交
1447
                        return null;
1448
                    }
P
Pilchie 已提交
1449

1450 1451 1452 1453 1454
                    EntryPointCandidateFinder.FindCandidatesInSingleType(mainType, entryPointCandidates, cancellationToken);
                }
                else
                {
                    mainType = null;
P
Pilchie 已提交
1455

1456
                    EntryPointCandidateFinder.FindCandidatesInNamespace(globalNamespace, entryPointCandidates, cancellationToken);
P
Pilchie 已提交
1457

C
Charles Stoner 已提交
1458 1459 1460
                    // Global code is the entry point, ignore all other Mains.
                    var scriptClass = this.ScriptClass;
                    if (scriptClass != null)
P
Pilchie 已提交
1461
                    {
1462
                        foreach (var main in entryPointCandidates)
P
Pilchie 已提交
1463
                        {
1464
                            diagnostics.Add(ErrorCode.WRN_MainIgnored, main.Locations.First(), main);
P
Pilchie 已提交
1465
                        }
C
Charles Stoner 已提交
1466
                        return scriptClass.GetScriptEntryPoint();
P
Pilchie 已提交
1467
                    }
1468
                }
P
Pilchie 已提交
1469

T
Ty Overby 已提交
1470 1471 1472 1473 1474 1475 1476 1477 1478
                // Validity and diagnostics are also tracked because they must be conditionally handled
                // if there are not any "traditional" entrypoints found.
                var taskEntryPoints = ArrayBuilder<(bool IsValid, MethodSymbol Candidate, DiagnosticBag SpecificDiagnostics)>.GetInstance();

                // These diagnostics (warning only) are added to the compilation only if
                // there were not any main methods found.
                DiagnosticBag noMainFoundDiagnostics = DiagnosticBag.GetInstance();

                bool CheckValid(MethodSymbol candidate, bool isCandidate, DiagnosticBag specificDiagnostics)
1479
                {
T
Ty Overby 已提交
1480
                    if (!isCandidate)
P
Pilchie 已提交
1481
                    {
T
Ty Overby 已提交
1482 1483 1484
                        noMainFoundDiagnostics.Add(ErrorCode.WRN_InvalidMainSig, candidate.Locations.First(), candidate);
                        noMainFoundDiagnostics.AddRange(specificDiagnostics);
                        return false;
P
Pilchie 已提交
1485 1486
                    }

1487 1488 1489
                    if (candidate.IsGenericMethod || candidate.ContainingType.IsGenericType)
                    {
                        // a single error for partial methods:
T
Ty Overby 已提交
1490 1491
                        noMainFoundDiagnostics.Add(ErrorCode.WRN_MainCantBeGeneric, candidate.Locations.First(), candidate);
                        return false;
1492
                    }
T
Ty Overby 已提交
1493 1494
                    return true;
                }
P
Pilchie 已提交
1495

T
Ty Overby 已提交
1496 1497 1498 1499 1500 1501 1502 1503
                var viableEntryPoints = ArrayBuilder<MethodSymbol>.GetInstance();

                foreach (var candidate in entryPointCandidates)
                {
                    var perCandidateBag = DiagnosticBag.GetInstance();
                    var (IsCandidate, IsTaskLike) = HasEntryPointSignature(candidate, perCandidateBag);

                    if (IsTaskLike)
P
Pilchie 已提交
1504
                    {
T
Ty Overby 已提交
1505
                        taskEntryPoints.Add((IsCandidate, candidate, perCandidateBag));
P
Pilchie 已提交
1506
                    }
T
Ty Overby 已提交
1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523
                    else
                    {
                        if (CheckValid(candidate, IsCandidate, perCandidateBag))
                        {
                            if (candidate.IsAsync)
                            {
                                diagnostics.Add(ErrorCode.ERR_NonTaskMainCantBeAsync, candidate.Locations.First(), candidate);
                            }
                            else
                            {
                                diagnostics.AddRange(perCandidateBag);
                                viableEntryPoints.Add(candidate);
                            }
                        }
                        perCandidateBag.Free();
                    }
                }
1524

T
Ty Overby 已提交
1525 1526 1527 1528 1529
                if (viableEntryPoints.Count == 0)
                {
                    foreach (var (IsValid, Candidate, SpecificDiagnostics) in taskEntryPoints)
                    {
                        if (CheckValid(Candidate, IsValid, SpecificDiagnostics) &&
1530
                            CheckFeatureAvailability(Candidate.ExtractReturnTypeSyntax(), MessageID.IDS_FeatureAsyncMain, diagnostics))
T
Ty Overby 已提交
1531 1532 1533 1534 1535
                        {
                            diagnostics.AddRange(SpecificDiagnostics);
                            viableEntryPoints.Add(Candidate);
                        }
                    }
1536 1537
                }

T
Ty Overby 已提交
1538
                foreach (var (_, _, SpecificDiagnostics) in taskEntryPoints)
1539
                {
T
Ty Overby 已提交
1540
                    SpecificDiagnostics.Free();
1541 1542
                }

T
Ty Overby 已提交
1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563
                if (viableEntryPoints.Count == 0)
                {
                    diagnostics.AddRange(noMainFoundDiagnostics);
                }
                else if ((object)mainType == null)
                {
                    // Filters out diagnostics so that only InvalidMainSig and MainCant'BeGeneric are left.
                    // The reason that Error diagnostics can end up in `noMainFoundDiagnostics` is when
                    // HasEntryPointSignature yields some Error Diagnostics when people implement Task or Task<T> incorrectly.
                    //
                    // We can't add those Errors to the general diagnostics bag because it would break previously-working programs.
                    // The fact that these warnings are not added when csc is invoked with /main is possibly a bug, and is tracked at
                    // https://github.com/dotnet/roslyn/issues/18964
                    foreach (var diagnostic in noMainFoundDiagnostics.AsEnumerable())
                    {
                        if (diagnostic.Code == (int)ErrorCode.WRN_InvalidMainSig || diagnostic.Code == (int)ErrorCode.WRN_MainCantBeGeneric)
                        {
                            diagnostics.Add(diagnostic);
                        }
                    }
                }
1564

C
Charles Stoner 已提交
1565
                MethodSymbol entryPoint = null;
1566 1567 1568
                if (viableEntryPoints.Count == 0)
                {
                    if ((object)mainType == null)
P
Pilchie 已提交
1569
                    {
1570
                        diagnostics.Add(ErrorCode.ERR_NoEntryPoint, NoLocation.Singleton);
P
Pilchie 已提交
1571 1572 1573
                    }
                    else
                    {
1574
                        diagnostics.Add(ErrorCode.ERR_NoMainInClass, mainType.Locations.First(), mainType);
P
Pilchie 已提交
1575 1576
                    }
                }
1577 1578 1579 1580 1581
                else if (viableEntryPoints.Count > 1)
                {
                    viableEntryPoints.Sort(LexicalOrderSymbolComparer.Instance);
                    var info = new CSDiagnosticInfo(
                         ErrorCode.ERR_MultipleEntryPoints,
1582
                         args: Array.Empty<object>(),
1583 1584 1585 1586 1587 1588
                         symbols: viableEntryPoints.OfType<Symbol>().AsImmutable(),
                         additionalLocations: viableEntryPoints.Select(m => m.Locations.First()).OfType<Location>().AsImmutable());

                    diagnostics.Add(new CSDiagnostic(info, viableEntryPoints.First().Locations.First()));
                }
                else
P
Pilchie 已提交
1589
                {
1590
                    entryPoint = viableEntryPoints[0];
P
Pilchie 已提交
1591
                }
1592

T
Ty Overby 已提交
1593
                taskEntryPoints.Free();
1594
                viableEntryPoints.Free();
T
Ty Overby 已提交
1595
                noMainFoundDiagnostics.Free();
C
Charles Stoner 已提交
1596
                return entryPoint;
1597 1598 1599
            }
            finally
            {
C
Charles Stoner 已提交
1600
                entryPointCandidates.Free();
1601
                sealedDiagnostics = diagnostics.ToReadOnlyAndFree();
P
Pilchie 已提交
1602 1603 1604
            }
        }

T
Ty Overby 已提交
1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636
        internal bool ReturnsAwaitableToVoidOrInt(MethodSymbol method, DiagnosticBag diagnostics)
        {
            // Common case optimization
            if (method.ReturnType.SpecialType == SpecialType.System_Void || method.ReturnType.SpecialType == SpecialType.System_Int32)
            {
                return false;
            }

            if (!(method.ReturnType is NamedTypeSymbol namedType))
            {
                return false;
            }

            // Early bail so we only even check things that are System.Threading.Tasks.Task(<T>)
            if (!(namedType.ConstructedFrom == GetWellKnownType(WellKnownType.System_Threading_Tasks_Task) ||
                  namedType.ConstructedFrom == GetWellKnownType(WellKnownType.System_Threading_Tasks_Task_T)))
            {
                return false;
            }

            var syntax = method.ExtractReturnTypeSyntax();
            var dumbInstance = new BoundLiteral(syntax, ConstantValue.Null, method.ReturnType);
            var binder = GetBinder(syntax);
            BoundExpression result;
            var success = binder.GetAwaitableExpressionInfo(dumbInstance, out _, out _, out _, out result, syntax, diagnostics);

            return success &&
                (result.Type.SpecialType == SpecialType.System_Void || result.Type.SpecialType == SpecialType.System_Int32);
        }

        /// <summary>
        /// Checks if the method has an entry point compatible signature, i.e.
T
Ty Overby 已提交
1637 1638 1639
        /// - the return type is either void, int, or returns a <see cref="System.Threading.Tasks.Task" />,
        /// or <see cref="System.Threading.Tasks.Task{T}" /> where the return type of GetAwaiter().GetResult()
        /// is either void or int.
T
Ty Overby 已提交
1640 1641
        /// - has either no parameter or a single parameter of type string[]
        /// </summary>
T
Ty Overby 已提交
1642
        private (bool IsCandidate, bool IsTaskLike) HasEntryPointSignature(MethodSymbol method, DiagnosticBag bag)
T
Ty Overby 已提交
1643 1644 1645
        {
            if (method.IsVararg)
            {
T
Ty Overby 已提交
1646
                return (false, false);
T
Ty Overby 已提交
1647 1648 1649 1650 1651 1652 1653 1654 1655 1656
            }

            TypeSymbol returnType = method.ReturnType;
            bool returnsTaskOrTaskOfInt = false;
            if (returnType.SpecialType != SpecialType.System_Int32 && returnType.SpecialType != SpecialType.System_Void)
            {
                // Never look for ReturnsAwaitableToVoidOrInt on int32 or void
                returnsTaskOrTaskOfInt = ReturnsAwaitableToVoidOrInt(method, bag);
                if (!returnsTaskOrTaskOfInt)
                {
T
Ty Overby 已提交
1657
                    return (false, false);
T
Ty Overby 已提交
1658 1659 1660 1661 1662
                }
            }

            if (method.RefKind != RefKind.None)
            {
T
Ty Overby 已提交
1663
                return (false, returnsTaskOrTaskOfInt);
T
Ty Overby 已提交
1664 1665 1666 1667
            }

            if (method.Parameters.Length == 0)
            {
T
Ty Overby 已提交
1668
                return (true, returnsTaskOrTaskOfInt);
T
Ty Overby 已提交
1669 1670 1671 1672
            }

            if (method.Parameters.Length > 1)
            {
T
Ty Overby 已提交
1673
                return (false, returnsTaskOrTaskOfInt);
T
Ty Overby 已提交
1674 1675 1676 1677
            }

            if (!method.ParameterRefKinds.IsDefault)
            {
T
Ty Overby 已提交
1678
                return (false, returnsTaskOrTaskOfInt);
T
Ty Overby 已提交
1679 1680 1681 1682 1683
            }

            var firstType = method.Parameters[0].Type;
            if (firstType.TypeKind != TypeKind.Array)
            {
T
Ty Overby 已提交
1684
                return (false, returnsTaskOrTaskOfInt);
T
Ty Overby 已提交
1685 1686 1687
            }

            var array = (ArrayTypeSymbol)firstType;
T
Ty Overby 已提交
1688
            return (array.IsSZArray && array.ElementType.SpecialType == SpecialType.System_String, returnsTaskOrTaskOfInt);
T
Ty Overby 已提交
1689 1690
        }

1691 1692
        internal override bool IsUnreferencedAssemblyIdentityDiagnosticCode(int code)
            => code == (int)ErrorCode.ERR_NoTypeDef;
1693

P
Pilchie 已提交
1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718
        internal class EntryPoint
        {
            public readonly MethodSymbol MethodSymbol;
            public readonly ImmutableArray<Diagnostic> Diagnostics;

            public EntryPoint(MethodSymbol methodSymbol, ImmutableArray<Diagnostic> diagnostics)
            {
                this.MethodSymbol = methodSymbol;
                this.Diagnostics = diagnostics;
            }
        }

        internal bool MightContainNoPiaLocalTypes()
        {
            return SourceAssembly.MightContainNoPiaLocalTypes();
        }

        // NOTE(cyrusn): There is a bit of a discoverability problem with this method and the same
        // named method in SyntaxTreeSemanticModel.  Technically, i believe these are the appropriate
        // locations for these methods.  This method has no dependencies on anything but the
        // compilation, while the other method needs a bindings object to determine what bound node
        // an expression syntax binds to.  Perhaps when we document these methods we should explain
        // where a user can find the other.
        public Conversion ClassifyConversion(ITypeSymbol source, ITypeSymbol destination)
        {
1719 1720 1721
            // Note that it is possible for there to be both an implicit user-defined conversion
            // and an explicit built-in conversion from source to destination. In that scenario
            // this method returns the implicit conversion.
P
Pilchie 已提交
1722

1723 1724
            if ((object)source == null)
            {
1725
                throw new ArgumentNullException(nameof(source));
1726
            }
P
Pilchie 已提交
1727

1728 1729
            if ((object)destination == null)
            {
1730
                throw new ArgumentNullException(nameof(destination));
1731
            }
P
Pilchie 已提交
1732

1733 1734
            var cssource = source.EnsureCSharpSymbolOrNull<ITypeSymbol, TypeSymbol>(nameof(source));
            var csdest = destination.EnsureCSharpSymbolOrNull<ITypeSymbol, TypeSymbol>(nameof(destination));
P
Pilchie 已提交
1735

1736
            HashSet<DiagnosticInfo> useSiteDiagnostics = null;
1737
            return Conversions.ClassifyConversionFromType(cssource, csdest, ref useSiteDiagnostics);
P
Pilchie 已提交
1738 1739 1740 1741 1742 1743 1744 1745 1746 1747
        }

        /// <summary>
        /// Returns a new ArrayTypeSymbol representing an array type tied to the base types of the
        /// COR Library in this Compilation.
        /// </summary>
        internal ArrayTypeSymbol CreateArrayTypeSymbol(TypeSymbol elementType, int rank = 1)
        {
            if ((object)elementType == null)
            {
1748
                throw new ArgumentNullException(nameof(elementType));
P
Pilchie 已提交
1749 1750
            }

1751
            return ArrayTypeSymbol.CreateCSharpArray(this.Assembly, elementType, ImmutableArray<CustomModifier>.Empty, rank);
P
Pilchie 已提交
1752 1753 1754 1755 1756 1757 1758 1759 1760
        }

        /// <summary>
        /// Returns a new PointerTypeSymbol representing a pointer type tied to a type in this Compilation.
        /// </summary>
        internal PointerTypeSymbol CreatePointerTypeSymbol(TypeSymbol elementType)
        {
            if ((object)elementType == null)
            {
1761
                throw new ArgumentNullException(nameof(elementType));
P
Pilchie 已提交
1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773
            }

            return new PointerTypeSymbol(elementType);
        }

        #endregion

        #region Binding

        /// <summary>
        /// Gets a new SyntaxTreeSemanticModel for the specified syntax tree.
        /// </summary>
1774
        public new SemanticModel GetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility)
P
Pilchie 已提交
1775 1776 1777
        {
            if (syntaxTree == null)
            {
1778
                throw new ArgumentNullException(nameof(syntaxTree));
P
Pilchie 已提交
1779 1780
            }

1781
            if (!_syntaxAndDeclarations.GetLazyState().RootNamespaces.ContainsKey(syntaxTree))
P
Pilchie 已提交
1782
            {
1783
                throw new ArgumentException(string.Format(CSharpResources.SyntaxTreeNotFoundTo, syntaxTree), nameof(syntaxTree));
P
Pilchie 已提交
1784 1785
            }

1786
            return new SyntaxTreeSemanticModel(this, (SyntaxTree)syntaxTree, ignoreAccessibility);
P
Pilchie 已提交
1787 1788 1789 1790 1791 1792 1793 1794 1795
        }

        // When building symbols from the declaration table (lazily), or inside a type, or when
        // compiling a method body, we may not have a BinderContext in hand for the enclosing
        // scopes.  Therefore, we build them when needed (and cache them) using a ContextBuilder.
        // Since a ContextBuilder is only a cache, and the identity of the ContextBuilders and
        // BinderContexts have no semantic meaning, we can reuse them or rebuild them, whichever is
        // most convenient.  We store them using weak references so that GC pressure will cause them
        // to be recycled.
1796
        private WeakReference<BinderFactory>[] _binderFactories;
P
Pilchie 已提交
1797 1798 1799 1800

        internal BinderFactory GetBinderFactory(SyntaxTree syntaxTree)
        {
            var treeNum = GetSyntaxTreeOrdinal(syntaxTree);
1801
            var binderFactories = _binderFactories;
P
Pilchie 已提交
1802 1803
            if (binderFactories == null)
            {
1804
                binderFactories = new WeakReference<BinderFactory>[this.SyntaxTrees.Length];
1805
                binderFactories = Interlocked.CompareExchange(ref _binderFactories, binderFactories, null) ?? binderFactories;
P
Pilchie 已提交
1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848
            }

            BinderFactory previousFactory;
            var previousWeakReference = binderFactories[treeNum];
            if (previousWeakReference != null && previousWeakReference.TryGetTarget(out previousFactory))
            {
                return previousFactory;
            }

            return AddNewFactory(syntaxTree, ref binderFactories[treeNum]);
        }

        private BinderFactory AddNewFactory(SyntaxTree syntaxTree, ref WeakReference<BinderFactory> slot)
        {
            var newFactory = new BinderFactory(this, syntaxTree);
            var newWeakReference = new WeakReference<BinderFactory>(newFactory);

            while (true)
            {
                BinderFactory previousFactory;
                WeakReference<BinderFactory> previousWeakReference = slot;
                if (previousWeakReference != null && previousWeakReference.TryGetTarget(out previousFactory))
                {
                    return previousFactory;
                }

                if (Interlocked.CompareExchange(ref slot, newWeakReference, previousWeakReference) == previousWeakReference)
                {
                    return newFactory;
                }
            }
        }

        internal Binder GetBinder(CSharpSyntaxNode syntax)
        {
            return GetBinderFactory(syntax.SyntaxTree).GetBinder(syntax);
        }

        /// <summary>
        /// Returns imported symbols for the given declaration.
        /// </summary>
        internal Imports GetImports(SingleNamespaceDeclaration declaration)
        {
1849
            return GetBinderFactory(declaration.SyntaxReference.SyntaxTree).GetImportsBinder((CSharpSyntaxNode)declaration.SyntaxReference.GetSyntax()).GetImports(basesBeingResolved: null);
P
Pilchie 已提交
1850 1851 1852 1853 1854 1855 1856
        }

        private AliasSymbol CreateGlobalNamespaceAlias()
        {
            return AliasSymbol.CreateGlobalNamespaceAlias(this.GlobalNamespace, new InContainerBinder(this.GlobalNamespace, new BuckStopsHereBinder(this)));
        }

1857
        private void CompleteTree(SyntaxTree tree)
P
Pilchie 已提交
1858
        {
1859 1860
            if (_lazyCompilationUnitCompletedTrees == null) Interlocked.CompareExchange(ref _lazyCompilationUnitCompletedTrees, new HashSet<SyntaxTree>(), null);
            lock (_lazyCompilationUnitCompletedTrees)
P
Pilchie 已提交
1861
            {
1862
                if (_lazyCompilationUnitCompletedTrees.Add(tree))
1863
                {
1864 1865 1866
                    // signal the end of the compilation unit
                    EventQueue.TryEnqueue(new CompilationUnitCompletedEvent(this, tree));

1867
                    if (_lazyCompilationUnitCompletedTrees.Count == this.SyntaxTrees.Length)
1868
                    {
1869
                        // if that was the last tree, signal the end of compilation
M
Manish Vasani 已提交
1870
                        CompleteCompilationEventQueue_NoLock();
1871 1872 1873 1874 1875
                    }
                }
            }
        }

C
Charles Stoner 已提交
1876
        internal override void ReportUnusedImports(SyntaxTree filterTree, DiagnosticBag diagnostics, CancellationToken cancellationToken)
1877
        {
1878
            if (_lazyImportInfos != null)
1879
            {
1880
                foreach (ImportInfo info in _lazyImportInfos)
P
Pilchie 已提交
1881
                {
1882 1883 1884 1885
                    cancellationToken.ThrowIfCancellationRequested();

                    SyntaxTree infoTree = info.Tree;
                    if (filterTree == null || filterTree == infoTree)
P
Pilchie 已提交
1886
                    {
1887 1888 1889 1890
                        TextSpan infoSpan = info.Span;
                        if (!this.IsImportDirectiveUsed(infoTree, infoSpan.Start))
                        {
                            ErrorCode code = info.Kind == SyntaxKind.ExternAliasDirective
1891 1892
                                ? ErrorCode.HDN_UnusedExternAlias
                                : ErrorCode.HDN_UnusedUsingDirective;
1893 1894 1895 1896 1897 1898
                            diagnostics.Add(code, infoTree.GetLocation(infoSpan));
                        }
                    }
                }
            }

1899 1900 1901 1902 1903
            CompleteTrees(filterTree);
        }

        internal override void CompleteTrees(SyntaxTree filterTree)
        {
1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914
            // By definition, a tree is complete when all of its compiler diagnostics have been reported.
            // Since unused imports are the last thing we compute and report, a tree is complete when
            // the unused imports have been reported.
            if (EventQueue != null)
            {
                if (filterTree != null)
                {
                    CompleteTree(filterTree);
                }
                else
                {
1915
                    foreach (var tree in this.SyntaxTrees)
1916 1917
                    {
                        CompleteTree(tree);
P
Pilchie 已提交
1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934
                    }
                }
            }
        }

        internal void RecordImport(UsingDirectiveSyntax syntax)
        {
            RecordImportInternal(syntax);
        }

        internal void RecordImport(ExternAliasDirectiveSyntax syntax)
        {
            RecordImportInternal(syntax);
        }

        private void RecordImportInternal(CSharpSyntaxNode syntax)
        {
1935
            LazyInitializer.EnsureInitialized(ref _lazyImportInfos).
1936
                Add(new ImportInfo(syntax.SyntaxTree, syntax.Kind(), syntax.Span));
P
Pilchie 已提交
1937 1938
        }

1939
        private struct ImportInfo : IEquatable<ImportInfo>
P
Pilchie 已提交
1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953
        {
            public readonly SyntaxTree Tree;
            public readonly SyntaxKind Kind;
            public readonly TextSpan Span;

            public ImportInfo(SyntaxTree tree, SyntaxKind kind, TextSpan span)
            {
                this.Tree = tree;
                this.Kind = kind;
                this.Span = span;
            }

            public override bool Equals(object obj)
            {
1954 1955
                return (obj is ImportInfo) && Equals((ImportInfo)obj);
            }
1956

1957 1958 1959 1960 1961 1962
            public bool Equals(ImportInfo other)
            {
                return
                    other.Kind == this.Kind &&
                    other.Tree == this.Tree &&
                    other.Span == this.Span;
P
Pilchie 已提交
1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976
            }

            public override int GetHashCode()
            {
                return Hash.Combine(Tree, Span.Start);
            }
        }

        #endregion

        #region Diagnostics

        internal override CommonMessageProvider MessageProvider
        {
1977
            get { return _syntaxAndDeclarations.MessageProvider; }
P
Pilchie 已提交
1978 1979 1980 1981 1982
        }

        /// <summary>
        /// The bag in which semantic analysis should deposit its diagnostics.
        /// </summary>
1983
        internal DiagnosticBag DeclarationDiagnostics
P
Pilchie 已提交
1984 1985 1986
        {
            get
            {
1987 1988 1989 1990
                // We should only be placing diagnostics in this bag until
                // we are done gathering declaration diagnostics. Assert that is
                // the case. But since we have bugs (see https://github.com/dotnet/roslyn/issues/846)
                // we disable the assertion until they are fixed.
1991
                Debug.Assert(!_declarationDiagnosticsFrozen || true);
1992
                if (_lazyDeclarationDiagnostics == null)
P
Pilchie 已提交
1993 1994
                {
                    var diagnostics = new DiagnosticBag();
1995
                    Interlocked.CompareExchange(ref _lazyDeclarationDiagnostics, diagnostics, null);
P
Pilchie 已提交
1996 1997
                }

1998
                return _lazyDeclarationDiagnostics;
P
Pilchie 已提交
1999 2000 2001
            }
        }

2002
        private DiagnosticBag _lazyDeclarationDiagnostics;
2003
        private bool _declarationDiagnosticsFrozen;
P
Pilchie 已提交
2004 2005 2006 2007 2008 2009 2010 2011

        /// <summary>
        /// A bag in which diagnostics that should be reported after code gen can be deposited.
        /// </summary>
        internal DiagnosticBag AdditionalCodegenWarnings
        {
            get
            {
2012
                return _additionalCodegenWarnings;
P
Pilchie 已提交
2013 2014 2015
            }
        }

2016
        private readonly DiagnosticBag _additionalCodegenWarnings = new DiagnosticBag();
P
Pilchie 已提交
2017 2018 2019 2020 2021

        internal DeclarationTable Declarations
        {
            get
            {
2022
                return _syntaxAndDeclarations.GetLazyState().DeclarationTable;
P
Pilchie 已提交
2023 2024 2025
            }
        }

2026 2027 2028 2029 2030 2031 2032 2033
        internal MergedNamespaceDeclaration MergedRootDeclaration
        {
            get
            {
                return Declarations.GetMergedRoot(this);
            }
        }

P
Pilchie 已提交
2034 2035 2036 2037 2038 2039
        /// <summary>
        /// Gets the diagnostics produced during the parsing stage of a compilation. There are no diagnostics for declarations or accessor or
        /// method bodies, for example.
        /// </summary>
        public override ImmutableArray<Diagnostic> GetParseDiagnostics(CancellationToken cancellationToken = default(CancellationToken))
        {
2040
            return GetDiagnostics(CompilationStage.Parse, false, cancellationToken);
P
Pilchie 已提交
2041 2042 2043 2044 2045 2046 2047 2048
        }

        /// <summary>
        /// Gets the diagnostics produced during symbol declaration headers.  There are no diagnostics for accessor or
        /// method bodies, for example.
        /// </summary>
        public override ImmutableArray<Diagnostic> GetDeclarationDiagnostics(CancellationToken cancellationToken = default(CancellationToken))
        {
2049
            return GetDiagnostics(CompilationStage.Declare, false, cancellationToken);
P
Pilchie 已提交
2050 2051 2052 2053 2054 2055 2056
        }

        /// <summary>
        /// Gets the diagnostics produced during the analysis of method bodies and field initializers.
        /// </summary>
        public override ImmutableArray<Diagnostic> GetMethodBodyDiagnostics(CancellationToken cancellationToken = default(CancellationToken))
        {
2057
            return GetDiagnostics(CompilationStage.Compile, false, cancellationToken);
P
Pilchie 已提交
2058 2059 2060 2061 2062 2063 2064 2065
        }

        /// <summary>
        /// Gets the all the diagnostics for the compilation, including syntax, declaration, and binding. Does not
        /// include any diagnostics that might be produced during emit.
        /// </summary>
        public override ImmutableArray<Diagnostic> GetDiagnostics(CancellationToken cancellationToken = default(CancellationToken))
        {
2066
            return GetDiagnostics(DefaultDiagnosticsStage, true, cancellationToken);
P
Pilchie 已提交
2067 2068
        }

2069
        internal ImmutableArray<Diagnostic> GetDiagnostics(CompilationStage stage, bool includeEarlierStages, CancellationToken cancellationToken)
2070 2071 2072 2073 2074 2075 2076
        {
            var diagnostics = DiagnosticBag.GetInstance();
            GetDiagnostics(stage, includeEarlierStages, diagnostics, cancellationToken);
            return diagnostics.ToReadOnlyAndFree();
        }

        internal override void GetDiagnostics(CompilationStage stage, bool includeEarlierStages, DiagnosticBag diagnostics, CancellationToken cancellationToken = default)
P
Pilchie 已提交
2077
        {
2078 2079 2080
            var builder = DiagnosticBag.GetInstance();

            if (stage == CompilationStage.Parse || (stage > CompilationStage.Parse && includeEarlierStages))
P
Pilchie 已提交
2081
            {
2082
                var syntaxTrees = this.SyntaxTrees;
2083 2084 2085 2086 2087
                if (this.Options.ConcurrentBuild)
                {
                    var parallelOptions = cancellationToken.CanBeCanceled
                                        ? new ParallelOptions() { CancellationToken = cancellationToken }
                                        : DefaultParallelOptions;
P
Pilchie 已提交
2088

2089 2090 2091 2092 2093 2094 2095
                    Parallel.For(0, syntaxTrees.Length, parallelOptions,
                        UICultureUtilities.WithCurrentUICulture<int>(i =>
                        {
                            var syntaxTree = syntaxTrees[i];
                            AppendLoadDirectiveDiagnostics(builder, _syntaxAndDeclarations, syntaxTree);
                            builder.AddRange(syntaxTree.GetDiagnostics(cancellationToken));
                        }));
2096 2097
                }
                else
P
Pilchie 已提交
2098
                {
2099
                    foreach (var syntaxTree in syntaxTrees)
P
Pilchie 已提交
2100
                    {
2101 2102 2103
                        cancellationToken.ThrowIfCancellationRequested();
                        AppendLoadDirectiveDiagnostics(builder, _syntaxAndDeclarations, syntaxTree);

2104 2105
                        cancellationToken.ThrowIfCancellationRequested();
                        builder.AddRange(syntaxTree.GetDiagnostics(cancellationToken));
O
Omar Tawfik 已提交
2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116
                    }
                }

                var parseOptionsReported = new HashSet<ParseOptions>();
                foreach (var syntaxTree in syntaxTrees)
                {
                    cancellationToken.ThrowIfCancellationRequested();
                    if (!syntaxTree.Options.Errors.IsDefaultOrEmpty && parseOptionsReported.Add(syntaxTree.Options))
                    {
                        var location = syntaxTree.GetLocation(TextSpan.FromBounds(0, 0));
                        foreach (var error in syntaxTree.Options.Errors)
O
Omar Tawfik 已提交
2117
                        {
O
Omar Tawfik 已提交
2118
                            builder.Add(error.WithLocation(location));
O
Omar Tawfik 已提交
2119
                        }
P
Pilchie 已提交
2120 2121
                    }
                }
2122
            }
P
Pilchie 已提交
2123

2124 2125
            if (stage == CompilationStage.Declare || stage > CompilationStage.Declare && includeEarlierStages)
            {
2126
                CheckAssemblyName(builder);
2127
                builder.AddRange(Options.Errors);
P
Pilchie 已提交
2128

2129
                cancellationToken.ThrowIfCancellationRequested();
P
Pilchie 已提交
2130

2131 2132
                // the set of diagnostics related to establishing references.
                builder.AddRange(GetBoundReferenceManager().Diagnostics);
P
Pilchie 已提交
2133 2134 2135

                cancellationToken.ThrowIfCancellationRequested();

2136
                builder.AddRange(GetSourceDeclarationDiagnostics(cancellationToken: cancellationToken));
2137

M
Manish Vasani 已提交
2138
                if (EventQueue != null && SyntaxTrees.Length == 0)
2139
                {
M
Manish Vasani 已提交
2140
                    EnsureCompilationEventQueueCompleted();
2141
                }
2142 2143 2144
            }

            cancellationToken.ThrowIfCancellationRequested();
P
Pilchie 已提交
2145

2146 2147 2148 2149 2150
            if (stage == CompilationStage.Compile || stage > CompilationStage.Compile && includeEarlierStages)
            {
                var methodBodyDiagnostics = DiagnosticBag.GetInstance();
                GetDiagnosticsForAllMethodBodies(methodBodyDiagnostics, cancellationToken);
                builder.AddRangeAndFree(methodBodyDiagnostics);
P
Pilchie 已提交
2151
            }
2152 2153 2154

            // Before returning diagnostics, we filter warnings
            // to honor the compiler options (e.g., /nowarn, /warnaserror and /warn) and the pragmas.
2155
            FilterAndAppendAndFreeDiagnostics(diagnostics, ref builder);
P
Pilchie 已提交
2156 2157
        }

2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175
        private static void AppendLoadDirectiveDiagnostics(DiagnosticBag builder, SyntaxAndDeclarationManager syntaxAndDeclarations, SyntaxTree syntaxTree, Func<IEnumerable<Diagnostic>, IEnumerable<Diagnostic>> locationFilterOpt = null)
        {
            ImmutableArray<LoadDirective> loadDirectives;
            if (syntaxAndDeclarations.GetLazyState().LoadDirectiveMap.TryGetValue(syntaxTree, out loadDirectives))
            {
                Debug.Assert(!loadDirectives.IsEmpty);
                foreach (var directive in loadDirectives)
                {
                    IEnumerable<Diagnostic> diagnostics = directive.Diagnostics;
                    if (locationFilterOpt != null)
                    {
                        diagnostics = locationFilterOpt(diagnostics);
                    }
                    builder.AddRange(diagnostics);
                }
            }
        }

T
TomasMatousek 已提交
2176 2177
        // Do the steps in compilation to get the method body diagnostics, but don't actually generate
        // IL or emit an assembly.
2178
        private void GetDiagnosticsForAllMethodBodies(DiagnosticBag diagnostics, CancellationToken cancellationToken)
T
TomasMatousek 已提交
2179 2180 2181 2182
        {
            MethodCompiler.CompileMethodBodies(
                compilation: this,
                moduleBeingBuiltOpt: null,
2183 2184
                emittingPdb: false,
                emitTestCoverageData: false,
T
TomasMatousek 已提交
2185 2186 2187 2188 2189 2190
                hasDeclarationErrors: false,
                diagnostics: diagnostics,
                filterOpt: null,
                cancellationToken: cancellationToken);

            DocumentationCommentCompiler.WriteDocumentationCommentXml(this, null, null, diagnostics, cancellationToken);
C
Charles Stoner 已提交
2191
            this.ReportUnusedImports(null, diagnostics, cancellationToken);
T
TomasMatousek 已提交
2192 2193
        }

2194 2195 2196 2197 2198 2199 2200
        private static bool IsDefinedOrImplementedInSourceTree(Symbol symbol, SyntaxTree tree, TextSpan? span)
        {
            if (symbol.IsDefinedInSourceTree(tree, span))
            {
                return true;
            }

2201 2202 2203 2204 2205 2206
            if (symbol.Kind == SymbolKind.Method && symbol.IsImplicitlyDeclared && ((MethodSymbol)symbol).MethodKind == MethodKind.Constructor)
            {
                // Include implicitly declared constructor if containing type is included
                return IsDefinedOrImplementedInSourceTree(symbol.ContainingType, tree, span);
            }

2207 2208 2209
            return false;
        }

T
TomasMatousek 已提交
2210 2211 2212 2213 2214 2215 2216
        private ImmutableArray<Diagnostic> GetDiagnosticsForMethodBodiesInTree(SyntaxTree tree, TextSpan? span, CancellationToken cancellationToken)
        {
            DiagnosticBag diagnostics = DiagnosticBag.GetInstance();

            MethodCompiler.CompileMethodBodies(
                compilation: this,
                moduleBeingBuiltOpt: null,
2217 2218
                emittingPdb: false,
                emitTestCoverageData: false,
T
TomasMatousek 已提交
2219 2220
                hasDeclarationErrors: false,
                diagnostics: diagnostics,
2221
                filterOpt: s => IsDefinedOrImplementedInSourceTree(s, tree, span),
T
TomasMatousek 已提交
2222 2223 2224 2225 2226 2227 2228 2229
                cancellationToken: cancellationToken);

            DocumentationCommentCompiler.WriteDocumentationCommentXml(this, null, null, diagnostics, cancellationToken, tree, span);

            // Report unused directives only if computing diagnostics for the entire tree.
            // Otherwise we cannot determine if a particular directive is used outside of the given sub-span within the tree.
            if (!span.HasValue || span.Value == tree.GetRoot(cancellationToken).FullSpan)
            {
C
Charles Stoner 已提交
2230
                ReportUnusedImports(tree, diagnostics, cancellationToken);
T
TomasMatousek 已提交
2231 2232 2233 2234 2235
            }

            return diagnostics.ToReadOnlyAndFree();
        }

P
Pilchie 已提交
2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250
        private ImmutableArray<Diagnostic> GetSourceDeclarationDiagnostics(SyntaxTree syntaxTree = null, TextSpan? filterSpanWithinTree = null, Func<IEnumerable<Diagnostic>, SyntaxTree, TextSpan?, IEnumerable<Diagnostic>> locationFilterOpt = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            GlobalImports.Complete(cancellationToken);

            SourceLocation location = null;
            if (syntaxTree != null)
            {
                var root = syntaxTree.GetRoot(cancellationToken);
                location = filterSpanWithinTree.HasValue ?
                    new SourceLocation(syntaxTree, filterSpanWithinTree.Value) :
                    new SourceLocation(root);
            }

            Assembly.ForceComplete(location, cancellationToken);

2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263
            if (syntaxTree is null)
            {
                // Don't freeze the compilation if we're getting
                // diagnositcs for a single tree
                _declarationDiagnosticsFrozen = true;

                // Also freeze generated attribute flags.
                // Symbols bound after getting the declaration
                // diagnostics shouldn't need to modify the flags.
                _needsGeneratedAttributes_IsFrozen = true;
            }

            var result = _lazyDeclarationDiagnostics?.AsEnumerable() ?? Enumerable.Empty<Diagnostic>();
P
Pilchie 已提交
2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285

            if (locationFilterOpt != null)
            {
                Debug.Assert(syntaxTree != null);
                result = locationFilterOpt(result, syntaxTree, filterSpanWithinTree);
            }

            // NOTE: Concatenate the CLS diagnostics *after* filtering by tree/span, because they're already filtered.
            ImmutableArray<Diagnostic> clsDiagnostics = GetClsComplianceDiagnostics(syntaxTree, filterSpanWithinTree, cancellationToken);

            return result.AsImmutable().Concat(clsDiagnostics);
        }

        private ImmutableArray<Diagnostic> GetClsComplianceDiagnostics(SyntaxTree syntaxTree, TextSpan? filterSpanWithinTree, CancellationToken cancellationToken)
        {
            if (syntaxTree != null)
            {
                var builder = DiagnosticBag.GetInstance();
                ClsComplianceChecker.CheckCompliance(this, builder, cancellationToken, syntaxTree, filterSpanWithinTree);
                return builder.ToReadOnlyAndFree();
            }

2286
            if (_lazyClsComplianceDiagnostics.IsDefault)
P
Pilchie 已提交
2287 2288 2289
            {
                var builder = DiagnosticBag.GetInstance();
                ClsComplianceChecker.CheckCompliance(this, builder, cancellationToken);
2290
                ImmutableInterlocked.InterlockedInitialize(ref _lazyClsComplianceDiagnostics, builder.ToReadOnlyAndFree());
P
Pilchie 已提交
2291 2292
            }

2293 2294
            Debug.Assert(!_lazyClsComplianceDiagnostics.IsDefault);
            return _lazyClsComplianceDiagnostics;
P
Pilchie 已提交
2295 2296 2297 2298 2299 2300
        }

        private static IEnumerable<Diagnostic> FilterDiagnosticsByLocation(IEnumerable<Diagnostic> diagnostics, SyntaxTree tree, TextSpan? filterSpanWithinTree)
        {
            foreach (var diagnostic in diagnostics)
            {
2301
                if (diagnostic.HasIntersectingLocation(tree, filterSpanWithinTree))
P
Pilchie 已提交
2302 2303 2304 2305 2306 2307
                {
                    yield return diagnostic;
                }
            }
        }

2308
        internal ImmutableArray<Diagnostic> GetDiagnosticsForSyntaxTree(
P
Pilchie 已提交
2309 2310 2311 2312
            CompilationStage stage,
            SyntaxTree syntaxTree,
            TextSpan? filterSpanWithinTree,
            bool includeEarlierStages,
2313
            CancellationToken cancellationToken = default(CancellationToken))
P
Pilchie 已提交
2314 2315 2316 2317 2318 2319
        {
            cancellationToken.ThrowIfCancellationRequested();

            var builder = DiagnosticBag.GetInstance();
            if (stage == CompilationStage.Parse || (stage > CompilationStage.Parse && includeEarlierStages))
            {
2320 2321 2322
                AppendLoadDirectiveDiagnostics(builder, _syntaxAndDeclarations, syntaxTree,
                    diagnostics => FilterDiagnosticsByLocation(diagnostics, syntaxTree, filterSpanWithinTree));

P
Pilchie 已提交
2323 2324 2325 2326 2327 2328 2329 2330 2331
                var syntaxDiagnostics = syntaxTree.GetDiagnostics();
                syntaxDiagnostics = FilterDiagnosticsByLocation(syntaxDiagnostics, syntaxTree, filterSpanWithinTree);
                builder.AddRange(syntaxDiagnostics);
            }

            cancellationToken.ThrowIfCancellationRequested();
            if (stage == CompilationStage.Declare || (stage > CompilationStage.Declare && includeEarlierStages))
            {
                var declarationDiagnostics = GetSourceDeclarationDiagnostics(syntaxTree, filterSpanWithinTree, FilterDiagnosticsByLocation, cancellationToken);
2332
                // re-enabling/fixing the below assert is tracked by https://github.com/dotnet/roslyn/issues/21020
H
Heejae Chang 已提交
2333
                // Debug.Assert(declarationDiagnostics.All(d => d.HasIntersectingLocation(syntaxTree, filterSpanWithinTree)));
P
Pilchie 已提交
2334 2335 2336 2337 2338 2339 2340 2341 2342
                builder.AddRange(declarationDiagnostics);
            }

            cancellationToken.ThrowIfCancellationRequested();

            if (stage == CompilationStage.Compile || (stage > CompilationStage.Compile && includeEarlierStages))
            {
                //remove some errors that don't have locations in the tree, like "no suitable main method."
                //Members in trees other than the one being examined are not compiled. This includes field
2343 2344
                //initializers which can result in 'field is never initialized' warnings for fields in partial
                //types when the field is in a different source file than the one for which we're getting diagnostics.
P
Pilchie 已提交
2345
                //For that reason the bag must be also filtered by tree.
T
TomasMatousek 已提交
2346
                IEnumerable<Diagnostic> methodBodyDiagnostics = GetDiagnosticsForMethodBodiesInTree(syntaxTree, filterSpanWithinTree, cancellationToken);
P
Pilchie 已提交
2347 2348

                // TODO: Enable the below commented assert and remove the filtering code in the next line.
T
TomasMatousek 已提交
2349
                //       GetDiagnosticsForMethodBodiesInTree seems to be returning diagnostics with locations that don't satisfy the filter tree/span, this must be fixed.
P
Pilchie 已提交
2350 2351 2352 2353 2354 2355 2356 2357 2358
                // Debug.Assert(methodBodyDiagnostics.All(d => DiagnosticContainsLocation(d, syntaxTree, filterSpanWithinTree)));
                methodBodyDiagnostics = FilterDiagnosticsByLocation(methodBodyDiagnostics, syntaxTree, filterSpanWithinTree);

                builder.AddRange(methodBodyDiagnostics);
            }

            // Before returning diagnostics, we filter warnings
            // to honor the compiler options (/nowarn, /warnaserror and /warn) and the pragmas.
            var result = DiagnosticBag.GetInstance();
2359
            FilterAndAppendAndFreeDiagnostics(result, ref builder);
P
Pilchie 已提交
2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390
            return result.ToReadOnlyAndFree<Diagnostic>();
        }

        #endregion

        #region Resources

        protected override void AppendDefaultVersionResource(Stream resourceStream)
        {
            var sourceAssembly = SourceAssembly;
            string fileVersion = sourceAssembly.FileVersion ?? sourceAssembly.Identity.Version.ToString();

            Win32ResourceConversions.AppendVersionToResourceStream(resourceStream,
                !this.Options.OutputKind.IsApplication(),
                fileVersion: fileVersion,
                originalFileName: this.SourceModule.Name,
                internalName: this.SourceModule.Name,
                productVersion: sourceAssembly.InformationalVersion ?? fileVersion,
                fileDescription: sourceAssembly.Title ?? " ", //alink would give this a blank if nothing was supplied.
                assemblyVersion: sourceAssembly.Identity.Version,
                legalCopyright: sourceAssembly.Copyright ?? " ", //alink would give this a blank if nothing was supplied.
                legalTrademarks: sourceAssembly.Trademark,
                productName: sourceAssembly.Product,
                comments: sourceAssembly.Description,
                companyName: sourceAssembly.Company);
        }

        #endregion

        #region Emit

2391
        internal override byte LinkerMajorVersion => 0x30;
2392

2393
        internal override bool IsDelaySigned
P
Pilchie 已提交
2394
        {
2395
            get { return SourceAssembly.IsDelaySigned; }
P
Pilchie 已提交
2396 2397 2398 2399 2400 2401 2402 2403
        }

        internal override StrongNameKeys StrongNameKeys
        {
            get { return SourceAssembly.StrongNameKeys; }
        }

        internal override CommonPEModuleBuilder CreateModuleBuilder(
2404
            EmitOptions emitOptions,
2405
            IMethodSymbol debugEntryPoint,
2406
            Stream sourceLinkStream,
2407
            IEnumerable<EmbeddedText> embeddedTexts,
P
Pilchie 已提交
2408 2409
            IEnumerable<ResourceDescription> manifestResources,
            CompilationTestData testData,
2410 2411
            DiagnosticBag diagnostics,
            CancellationToken cancellationToken)
P
Pilchie 已提交
2412
        {
2413
            Debug.Assert(!IsSubmission || HasCodeToEmit());
P
Pilchie 已提交
2414

2415
            string runtimeMDVersion = GetRuntimeMetadataVersion(emitOptions, diagnostics);
P
Pilchie 已提交
2416 2417
            if (runtimeMDVersion == null)
            {
2418
                return null;
P
Pilchie 已提交
2419 2420
            }

2421
            var moduleProps = ConstructModuleSerializationProperties(emitOptions, runtimeMDVersion);
P
Pilchie 已提交
2422 2423 2424 2425 2426 2427 2428

            if (manifestResources == null)
            {
                manifestResources = SpecializedCollections.EmptyEnumerable<ResourceDescription>();
            }

            PEModuleBuilder moduleBeingBuilt;
2429
            if (_options.OutputKind.IsNetModule())
P
Pilchie 已提交
2430 2431 2432
            {
                moduleBeingBuilt = new PENetModuleBuilder(
                    (SourceModuleSymbol)SourceModule,
2433
                    emitOptions,
P
Pilchie 已提交
2434
                    moduleProps,
2435
                    manifestResources);
P
Pilchie 已提交
2436 2437 2438
            }
            else
            {
2439
                var kind = _options.OutputKind.IsValid() ? _options.OutputKind : OutputKind.DynamicallyLinkedLibrary;
2440 2441
                moduleBeingBuilt = new PEAssemblyBuilder(
                    SourceAssembly,
2442
                    emitOptions,
2443 2444
                    kind,
                    moduleProps,
2445
                    manifestResources);
P
Pilchie 已提交
2446 2447
            }

2448 2449 2450 2451 2452
            if (debugEntryPoint != null)
            {
                moduleBeingBuilt.SetDebugEntryPoint((MethodSymbol)debugEntryPoint, diagnostics);
            }

2453 2454
            moduleBeingBuilt.SourceLinkStreamOpt = sourceLinkStream;

2455 2456 2457 2458 2459
            if (embeddedTexts != null)
            {
                moduleBeingBuilt.EmbeddedTexts = embeddedTexts;
            }

P
Pilchie 已提交
2460 2461 2462 2463 2464 2465 2466 2467 2468 2469
            // testData is only passed when running tests.
            if (testData != null)
            {
                moduleBeingBuilt.SetMethodTestData(testData.Methods);
                testData.Module = moduleBeingBuilt;
            }

            return moduleBeingBuilt;
        }

C
Charles Stoner 已提交
2470
        internal override bool CompileMethods(
P
Pilchie 已提交
2471
            CommonPEModuleBuilder moduleBuilder,
2472
            bool emittingPdb,
2473 2474
            bool emitMetadataOnly,
            bool emitTestCoverageData,
2475
            DiagnosticBag diagnostics,
2476 2477
            Predicate<ISymbol> filterOpt,
            CancellationToken cancellationToken)
P
Pilchie 已提交
2478
        {
2479 2480
            // The diagnostics should include syntax and declaration errors. We insert these before calling Emitter.Emit, so that the emitter
            // does not attempt to emit if there are declaration errors (but we do insert all errors from method body binding...)
2481 2482 2483 2484 2485 2486 2487 2488
            PooledHashSet<int> excludeDiagnostics = null;
            if (emitMetadataOnly)
            {
                excludeDiagnostics = PooledHashSet<int>.GetInstance();
                excludeDiagnostics.Add((int)ErrorCode.ERR_ConcreteMissingBody);
            }
            bool hasDeclarationErrors = !FilterAndAppendDiagnostics(diagnostics, GetDiagnostics(CompilationStage.Declare, true, cancellationToken), excludeDiagnostics);
            excludeDiagnostics?.Free();
2489

P
Pilchie 已提交
2490 2491 2492 2493 2494
            // TODO (tomat): NoPIA:
            // EmbeddedSymbolManager.MarkAllDeferredSymbolsAsReferenced(this)

            var moduleBeingBuilt = (PEModuleBuilder)moduleBuilder;

2495
            if (emitMetadataOnly)
P
Pilchie 已提交
2496 2497 2498 2499 2500 2501
            {
                if (hasDeclarationErrors)
                {
                    return false;
                }

2502 2503 2504 2505 2506 2507 2508
                if (moduleBeingBuilt.SourceModule.HasBadAttributes)
                {
                    // If there were errors but no declaration diagnostics, explicitly add a "Failed to emit module" error.
                    diagnostics.Add(ErrorCode.ERR_ModuleEmitFailure, NoLocation.Singleton, ((Cci.INamedEntity)moduleBeingBuilt).Name);
                    return false;
                }

T
TomasMatousek 已提交
2509
                SynthesizedMetadataCompiler.ProcessSynthesizedMembers(this, moduleBeingBuilt, cancellationToken);
P
Pilchie 已提交
2510 2511 2512
            }
            else
            {
2513
                if ((emittingPdb || emitTestCoverageData) &&
2514
                    !CreateDebugDocuments(moduleBeingBuilt.DebugDocumentsBuilder, moduleBeingBuilt.EmbeddedTexts, diagnostics))
P
Pilchie 已提交
2515
                {
2516
                    return false;
P
Pilchie 已提交
2517 2518
                }

2519
                // Perform initial bind of method bodies in spite of earlier errors. This is the same
P
Pilchie 已提交
2520 2521 2522 2523 2524
                // behavior as when calling GetDiagnostics()

                // Use a temporary bag so we don't have to refilter pre-existing diagnostics.
                DiagnosticBag methodBodyDiagnosticBag = DiagnosticBag.GetInstance();

T
TomasMatousek 已提交
2525
                MethodCompiler.CompileMethodBodies(
P
Pilchie 已提交
2526 2527
                    this,
                    moduleBeingBuilt,
2528
                    emittingPdb,
2529
                    emitTestCoverageData,
P
Pilchie 已提交
2530 2531
                    hasDeclarationErrors,
                    diagnostics: methodBodyDiagnosticBag,
2532
                    filterOpt: filterOpt,
P
Pilchie 已提交
2533
                    cancellationToken: cancellationToken);
T
TomasMatousek 已提交
2534

2535
                bool hasMethodBodyErrorOrWarningAsError = !FilterAndAppendAndFreeDiagnostics(diagnostics, ref methodBodyDiagnosticBag);
P
Pilchie 已提交
2536 2537 2538 2539 2540 2541 2542

                if (hasDeclarationErrors || hasMethodBodyErrorOrWarningAsError)
                {
                    return false;
                }
            }

C
Charles Stoner 已提交
2543 2544 2545 2546 2547 2548 2549
            return true;
        }

        internal override bool GenerateResourcesAndDocumentationComments(
            CommonPEModuleBuilder moduleBuilder,
            Stream xmlDocStream,
            Stream win32Resources,
2550
            string outputNameOverride,
C
Charles Stoner 已提交
2551 2552 2553
            DiagnosticBag diagnostics,
            CancellationToken cancellationToken)
        {
P
Pilchie 已提交
2554
            // Use a temporary bag so we don't have to refilter pre-existing diagnostics.
2555
            var resourceDiagnostics = DiagnosticBag.GetInstance();
C
Charles Stoner 已提交
2556

2557
            SetupWin32Resources(moduleBuilder, win32Resources, resourceDiagnostics);
P
Pilchie 已提交
2558

C
Charles Stoner 已提交
2559
            ReportManifestResourceDuplicates(
2560 2561 2562 2563
                moduleBuilder.ManifestResources,
                SourceAssembly.Modules.Skip(1).Select(m => m.Name),   //all modules except the first one
                AddedModulesResourceNames(resourceDiagnostics),
                resourceDiagnostics);
C
Charles Stoner 已提交
2564

2565
            if (!FilterAndAppendAndFreeDiagnostics(diagnostics, ref resourceDiagnostics))
P
Pilchie 已提交
2566 2567 2568 2569 2570
            {
                return false;
            }

            cancellationToken.ThrowIfCancellationRequested();
2571

P
Pilchie 已提交
2572
            // Use a temporary bag so we don't have to refilter pre-existing diagnostics.
2573
            var xmlDiagnostics = DiagnosticBag.GetInstance();
P
Pilchie 已提交
2574

2575
            string assemblyName = FileNameUtilities.ChangeExtension(outputNameOverride, extension: null);
2576
            DocumentationCommentCompiler.WriteDocumentationCommentXml(this, assemblyName, xmlDocStream, xmlDiagnostics, cancellationToken);
P
Pilchie 已提交
2577

C
Charles Stoner 已提交
2578
            return FilterAndAppendAndFreeDiagnostics(diagnostics, ref xmlDiagnostics);
P
Pilchie 已提交
2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606
        }

        private IEnumerable<string> AddedModulesResourceNames(DiagnosticBag diagnostics)
        {
            ImmutableArray<ModuleSymbol> modules = SourceAssembly.Modules;

            for (int i = 1; i < modules.Length; i++)
            {
                var m = (Symbols.Metadata.PE.PEModuleSymbol)modules[i];
                ImmutableArray<EmbeddedResource> resources;

                try
                {
                    resources = m.Module.GetEmbeddedResourcesOrThrow();
                }
                catch (BadImageFormatException)
                {
                    diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_BindToBogus, m), NoLocation.Singleton);
                    continue;
                }

                foreach (var resource in resources)
                {
                    yield return resource.Name;
                }
            }
        }

2607 2608 2609
        internal override EmitDifferenceResult EmitDifference(
            EmitBaseline baseline,
            IEnumerable<SemanticEdit> edits,
2610
            Func<ISymbol, bool> isAddedSymbol,
2611 2612 2613
            Stream metadataStream,
            Stream ilStream,
            Stream pdbStream,
A
angocke 已提交
2614
            ICollection<MethodDefinitionHandle> updatedMethods,
2615 2616
            CompilationTestData testData,
            CancellationToken cancellationToken)
P
Pilchie 已提交
2617
        {
2618 2619 2620 2621
            return EmitHelpers.EmitDifference(
                this,
                baseline,
                edits,
2622
                isAddedSymbol,
2623 2624 2625
                metadataStream,
                ilStream,
                pdbStream,
2626
                updatedMethods,
2627 2628 2629
                testData,
                cancellationToken);
        }
P
Pilchie 已提交
2630

2631
        internal string GetRuntimeMetadataVersion(EmitOptions emitOptions, DiagnosticBag diagnostics)
2632
        {
2633
            string runtimeMDVersion = GetRuntimeMetadataVersion(emitOptions);
2634
            if (runtimeMDVersion != null)
P
Pilchie 已提交
2635
            {
2636
                return runtimeMDVersion;
P
Pilchie 已提交
2637 2638
            }

2639 2640 2641
            DiagnosticBag runtimeMDVersionDiagnostics = DiagnosticBag.GetInstance();
            runtimeMDVersionDiagnostics.Add(ErrorCode.WRN_NoRuntimeMetadataVersion, NoLocation.Singleton);
            if (!FilterAndAppendAndFreeDiagnostics(diagnostics, ref runtimeMDVersionDiagnostics))
P
Pilchie 已提交
2642
            {
2643
                return null;
P
Pilchie 已提交
2644 2645
            }

2646
            return string.Empty; //prevent emitter from crashing.
P
Pilchie 已提交
2647 2648
        }

2649
        private string GetRuntimeMetadataVersion(EmitOptions emitOptions)
P
Pilchie 已提交
2650 2651 2652 2653 2654 2655 2656 2657
        {
            var corAssembly = Assembly.CorLibrary as Symbols.Metadata.PE.PEAssemblySymbol;

            if ((object)corAssembly != null)
            {
                return corAssembly.Assembly.ManifestModule.MetadataVersion;
            }

2658
            return emitOptions.RuntimeMetadataVersion;
P
Pilchie 已提交
2659 2660
        }

2661 2662
        internal override void AddDebugSourceDocumentsForChecksumDirectives(
            DebugDocumentsBuilder documentsBuilder,
2663
            SyntaxTree tree,
2664
            DiagnosticBag diagnostics)
P
Pilchie 已提交
2665
        {
2666
            var checksumDirectives = tree.GetRoot().GetDirectives(d => d.Kind() == SyntaxKind.PragmaChecksumDirectiveTrivia &&
P
Pilchie 已提交
2667 2668 2669 2670
                                                                 !d.ContainsDiagnostics);

            foreach (var directive in checksumDirectives)
            {
2671 2672
                var checksumDirective = (PragmaChecksumDirectiveTriviaSyntax)directive;
                var path = checksumDirective.File.ValueText;
P
Pilchie 已提交
2673

2674
                var checksumText = checksumDirective.Bytes.ValueText;
2675 2676
                var normalizedPath = documentsBuilder.NormalizeDebugDocumentPath(path, basePath: tree.FilePath);
                var existingDoc = documentsBuilder.TryGetDebugDocumentForNormalizedPath(normalizedPath);
P
Pilchie 已提交
2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688

                // duplicate checksum pragmas are valid as long as values match
                // if we have seen this document already, check for matching values.
                if (existingDoc != null)
                {
                    // pragma matches a file path on an actual tree.
                    // Dev12 compiler just ignores the pragma in this case which means that
                    // checksum of the actual tree always wins and no warning is given.
                    // We will continue doing the same.
                    if (existingDoc.IsComputedChecksum)
                    {
                        continue;
2689
                    }
P
Pilchie 已提交
2690

2691 2692
                    var sourceInfo = existingDoc.GetSourceInfo();
                    if (ChecksumMatches(checksumText, sourceInfo.Checksum))
P
Pilchie 已提交
2693
                    {
2694
                        var guid = Guid.Parse(checksumDirective.Guid.ValueText);
2695
                        if (guid == sourceInfo.ChecksumAlgorithmId)
P
Pilchie 已提交
2696 2697 2698 2699 2700 2701 2702 2703
                        {
                            // all parts match, nothing to do
                            continue;
                        }
                    }

                    // did not match to an existing document
                    // produce a warning and ignore the pragma
2704
                    diagnostics.Add(ErrorCode.WRN_ConflictingChecksum, new SourceLocation(checksumDirective), path);
P
Pilchie 已提交
2705 2706 2707 2708 2709 2710
                }
                else
                {
                    var newDocument = new Cci.DebugSourceDocument(
                        normalizedPath,
                        Cci.DebugSourceDocument.CorSymLanguageTypeCSharp,
2711 2712
                        MakeChecksumBytes(checksumDirective.Bytes.ValueText),
                        Guid.Parse(checksumDirective.Guid.ValueText));
P
Pilchie 已提交
2713

2714
                    documentsBuilder.AddDebugDocument(newDocument);
P
Pilchie 已提交
2715 2716 2717 2718
                }
            }
        }

2719
        private static bool ChecksumMatches(string bytesText, ImmutableArray<byte> bytes)
P
Pilchie 已提交
2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740
        {
            if (bytesText.Length != bytes.Length * 2)
            {
                return false;
            }

            for (int i = 0, len = bytesText.Length / 2; i < len; i++)
            {
                // 1A  in text becomes   0x1A
                var b = SyntaxFacts.HexValue(bytesText[i * 2]) * 16 +
                        SyntaxFacts.HexValue(bytesText[i * 2 + 1]);

                if (b != bytes[i])
                {
                    return false;
                }
            }

            return true;
        }

2741
        private static ImmutableArray<byte> MakeChecksumBytes(string bytesText)
P
Pilchie 已提交
2742
        {
2743 2744
            int length = bytesText.Length / 2;
            var builder = ArrayBuilder<byte>.GetInstance(length);
P
Pilchie 已提交
2745

2746
            for (int i = 0; i < length; i++)
P
Pilchie 已提交
2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757
            {
                // 1A  in text becomes   0x1A
                var b = SyntaxFacts.HexValue(bytesText[i * 2]) * 16 +
                        SyntaxFacts.HexValue(bytesText[i * 2 + 1]);

                builder.Add((byte)b);
            }

            return builder.ToImmutableAndFree();
        }

2758
        internal override Guid DebugSourceDocumentLanguageId => Cci.DebugSourceDocument.CorSymLanguageTypeCSharp;
P
Pilchie 已提交
2759

2760
        internal override bool HasCodeToEmit()
P
Pilchie 已提交
2761
        {
2762
            foreach (var syntaxTree in this.SyntaxTrees)
P
Pilchie 已提交
2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799
            {
                var unit = syntaxTree.GetCompilationUnitRoot();
                if (unit.Members.Count > 0)
                {
                    return true;
                }
            }

            return false;
        }

        #endregion

        #region Common Members

        protected override Compilation CommonWithReferences(IEnumerable<MetadataReference> newReferences)
        {
            return WithReferences(newReferences);
        }

        protected override Compilation CommonWithAssemblyName(string assemblyName)
        {
            return WithAssemblyName(assemblyName);
        }

        protected override IAssemblySymbol CommonAssembly
        {
            get { return this.Assembly; }
        }

        protected override INamespaceSymbol CommonGlobalNamespace
        {
            get { return this.GlobalNamespace; }
        }

        protected override CompilationOptions CommonOptions
        {
2800
            get { return _options; }
P
Pilchie 已提交
2801 2802
        }

2803
        protected override SemanticModel CommonGetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility)
P
Pilchie 已提交
2804
        {
2805
            return this.GetSemanticModel((SyntaxTree)syntaxTree, ignoreAccessibility);
P
Pilchie 已提交
2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817
        }

        protected override IEnumerable<SyntaxTree> CommonSyntaxTrees
        {
            get
            {
                return this.SyntaxTrees;
            }
        }

        protected override Compilation CommonAddSyntaxTrees(IEnumerable<SyntaxTree> trees)
        {
2818
            return this.AddSyntaxTrees(trees);
P
Pilchie 已提交
2819 2820 2821 2822
        }

        protected override Compilation CommonRemoveSyntaxTrees(IEnumerable<SyntaxTree> trees)
        {
2823
            return this.RemoveSyntaxTrees(trees);
P
Pilchie 已提交
2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840
        }

        protected override Compilation CommonRemoveAllSyntaxTrees()
        {
            return this.RemoveAllSyntaxTrees();
        }

        protected override Compilation CommonReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree newTree)
        {
            return this.ReplaceSyntaxTree((SyntaxTree)oldTree, (SyntaxTree)newTree);
        }

        protected override Compilation CommonWithOptions(CompilationOptions options)
        {
            return this.WithOptions((CSharpCompilationOptions)options);
        }

2841
        protected override Compilation CommonWithScriptCompilationInfo(ScriptCompilationInfo info)
P
Pilchie 已提交
2842
        {
2843
            return this.WithScriptCompilationInfo((CSharpScriptCompilationInfo)info);
P
Pilchie 已提交
2844 2845 2846 2847
        }

        protected override bool CommonContainsSyntaxTree(SyntaxTree syntaxTree)
        {
2848
            return this.ContainsSyntaxTree(syntaxTree);
P
Pilchie 已提交
2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880
        }

        protected override ISymbol CommonGetAssemblyOrModuleSymbol(MetadataReference reference)
        {
            return this.GetAssemblyOrModuleSymbol(reference);
        }

        protected override Compilation CommonClone()
        {
            return this.Clone();
        }

        protected override IModuleSymbol CommonSourceModule
        {
            get { return this.SourceModule; }
        }

        protected override INamedTypeSymbol CommonGetSpecialType(SpecialType specialType)
        {
            return this.GetSpecialType(specialType);
        }

        protected override INamespaceSymbol CommonGetCompilationNamespace(INamespaceSymbol namespaceSymbol)
        {
            return this.GetCompilationNamespace(namespaceSymbol);
        }

        protected override INamedTypeSymbol CommonGetTypeByMetadataName(string metadataName)
        {
            return this.GetTypeByMetadataName(metadataName);
        }

2881
        protected override INamedTypeSymbol CommonScriptClass
P
Pilchie 已提交
2882 2883 2884 2885 2886 2887
        {
            get { return this.ScriptClass; }
        }

        protected override IArrayTypeSymbol CommonCreateArrayTypeSymbol(ITypeSymbol elementType, int rank)
        {
2888
            return CreateArrayTypeSymbol(elementType.EnsureCSharpSymbolOrNull<ITypeSymbol, TypeSymbol>(nameof(elementType)), rank);
P
Pilchie 已提交
2889 2890 2891 2892
        }

        protected override IPointerTypeSymbol CommonCreatePointerTypeSymbol(ITypeSymbol elementType)
        {
2893
            return CreatePointerTypeSymbol(elementType.EnsureCSharpSymbolOrNull<ITypeSymbol, TypeSymbol>(nameof(elementType)));
P
Pilchie 已提交
2894 2895
        }

2896 2897 2898 2899
        protected override INamedTypeSymbol CommonCreateTupleTypeSymbol(
            ImmutableArray<ITypeSymbol> elementTypes,
            ImmutableArray<string> elementNames,
            ImmutableArray<Location> elementLocations)
2900
        {
2901 2902 2903 2904 2905 2906
            var typesBuilder = ArrayBuilder<TypeSymbol>.GetInstance(elementTypes.Length);
            for (int i = 0; i < elementTypes.Length; i++)
            {
                typesBuilder.Add(elementTypes[i].EnsureCSharpSymbolOrNull<ITypeSymbol, TypeSymbol>($"{nameof(elementTypes)}[{i}]"));
            }

2907 2908 2909
            return TupleTypeSymbol.Create(
                locationOpt: null, // no location for the type declaration
                elementTypes: typesBuilder.ToImmutableAndFree(),
2910 2911
                elementLocations: elementLocations,
                elementNames: elementNames,
2912
                compilation: this,
2913 2914
                shouldCheckConstraints: false,
                errorPositions: default(ImmutableArray<bool>));
2915
        }
2916

2917
        protected override INamedTypeSymbol CommonCreateTupleTypeSymbol(
2918
            INamedTypeSymbol underlyingType,
2919 2920
            ImmutableArray<string> elementNames,
            ImmutableArray<Location> elementLocations)
2921 2922 2923 2924 2925 2926 2927
        {
            var csharpUnderlyingTuple = underlyingType.EnsureCSharpSymbolOrNull<INamedTypeSymbol, NamedTypeSymbol>(nameof(underlyingType));

            int cardinality;
            if (!csharpUnderlyingTuple.IsTupleCompatible(out cardinality))
            {
                throw new ArgumentException(CodeAnalysisResources.TupleUnderlyingTypeMustBeTupleCompatible, nameof(underlyingType));
2928 2929
            }

J
Julien 已提交
2930
            elementNames = CheckTupleElementNames(cardinality, elementNames);
2931 2932
            CheckTupleElementLocations(cardinality, elementLocations);

2933 2934
            return TupleTypeSymbol.Create(
                csharpUnderlyingTuple, elementNames, elementLocations: elementLocations);
2935 2936
        }

2937
        protected override INamedTypeSymbol CommonCreateAnonymousTypeSymbol(
2938
            ImmutableArray<ITypeSymbol> memberTypes,
2939 2940 2941
            ImmutableArray<string> memberNames,
            ImmutableArray<Location> memberLocations,
            ImmutableArray<bool> memberIsReadOnly)
2942 2943 2944 2945 2946 2947
        {
            for (int i = 0, n = memberTypes.Length; i < n; i++)
            {
                memberTypes[i].EnsureCSharpSymbolOrNull<ITypeSymbol, TypeSymbol>($"{nameof(memberTypes)}[{i}]");
            }

2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963
            if (!memberIsReadOnly.IsDefault && memberIsReadOnly.Any(v => !v))
            {
                throw new ArgumentException($"Non-ReadOnly members are not supported in C# anonymous types.");
            }

            var fields = ArrayBuilder<AnonymousTypeField>.GetInstance();

            for (int i = 0, n = memberTypes.Length; i < n; i++)
            {
                var type = memberTypes[i];
                var name = memberNames[i];
                var location = memberLocations.IsDefault ? Location.None : memberLocations[i];
                fields.Add(new AnonymousTypeField(name, location, (TypeSymbol)type));
            }

            var descriptor = new AnonymousTypeDescriptor(fields.ToImmutableAndFree(), Location.None);
2964 2965 2966 2967

            return this.AnonymousTypeManager.ConstructAnonymousTypeSymbol(descriptor);
        }

P
Pilchie 已提交
2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996
        protected override ITypeSymbol CommonDynamicType
        {
            get { return DynamicType; }
        }

        protected override INamedTypeSymbol CommonObjectType
        {
            get { return this.ObjectType; }
        }

        protected override IMethodSymbol CommonGetEntryPoint(CancellationToken cancellationToken)
        {
            return this.GetEntryPoint(cancellationToken);
        }

        internal override int CompareSourceLocations(Location loc1, Location loc2)
        {
            Debug.Assert(loc1.IsInSource);
            Debug.Assert(loc2.IsInSource);

            var comparison = CompareSyntaxTreeOrdering(loc1.SourceTree, loc2.SourceTree);
            if (comparison != 0)
            {
                return comparison;
            }

            return loc1.SourceSpan.Start - loc2.SourceSpan.Start;
        }

2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007
        internal override int CompareSourceLocations(SyntaxReference loc1, SyntaxReference loc2)
        {
            var comparison = CompareSyntaxTreeOrdering(loc1.SyntaxTree, loc2.SyntaxTree);
            if (comparison != 0)
            {
                return comparison;
            }

            return loc1.Span.Start - loc2.Span.Start;
        }

H
heejaechang 已提交
3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022
        /// <summary>
        /// Return true if there is a source declaration symbol name that meets given predicate.
        /// </summary>
        public override bool ContainsSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (predicate == null)
            {
                throw new ArgumentNullException(nameof(predicate));
            }

            if (filter == SymbolFilter.None)
            {
                throw new ArgumentException(CSharpResources.NoNoneSearchCriteria, nameof(filter));
            }

3023
            return DeclarationTable.ContainsName(this.MergedRootDeclaration, predicate, filter, cancellationToken);
H
heejaechang 已提交
3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043
        }

        /// <summary>
        /// Return source declaration symbols whose name meets given predicate.
        /// </summary>
        public override IEnumerable<ISymbol> GetSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (predicate == null)
            {
                throw new ArgumentNullException(nameof(predicate));
            }

            if (filter == SymbolFilter.None)
            {
                throw new ArgumentException(CSharpResources.NoNoneSearchCriteria, nameof(filter));
            }

            return new SymbolSearcher(this).GetSymbolsWithName(predicate, filter, cancellationToken);
        }

P
Pilchie 已提交
3044
        #endregion
3045

3046
        /// <summary>
3047
        /// Returns if the compilation has all of the members necessary to emit metadata about
3048 3049 3050 3051 3052 3053 3054 3055 3056 3057
        /// dynamic types.
        /// </summary>
        /// <returns></returns>
        internal bool HasDynamicEmitAttributes()
        {
            return
                (object)GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_DynamicAttribute__ctor) != null &&
                (object)GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_DynamicAttribute__ctorTransformFlags) != null;
        }

3058 3059 3060
        internal bool HasTupleNamesAttributes =>
            (object)GetWellKnownTypeMember(WellKnownMember.System_Runtime_CompilerServices_TupleElementNamesAttribute__ctorTransformNames) != null;

3061 3062 3063 3064
        /// <summary>
        /// Returns whether the compilation has the Boolean type and if it's good.
        /// </summary>
        /// <returns>Returns true if Boolean is present and healthy.</returns>
3065 3066 3067
        internal bool CanEmitBoolean() => CanEmitSpecialType(SpecialType.System_Boolean);

        internal bool CanEmitSpecialType(SpecialType type)
3068
        {
3069 3070
            var typeSymbol = GetSpecialType(type);
            var diagnostic = typeSymbol.GetUseSiteDiagnostic();
3071 3072 3073
            return (diagnostic == null) || (diagnostic.Severity != DiagnosticSeverity.Error);
        }

3074
        internal override AnalyzerDriver AnalyzerForLanguage(ImmutableArray<DiagnosticAnalyzer> analyzers, AnalyzerManager analyzerManager)
3075
        {
3076 3077 3078
            Func<SyntaxNode, SyntaxKind> getKind = node => node.Kind();
            Func<SyntaxTrivia, bool> isComment = trivia => trivia.Kind() == SyntaxKind.SingleLineCommentTrivia || trivia.Kind() == SyntaxKind.MultiLineCommentTrivia;
            return new AnalyzerDriver<SyntaxKind>(analyzers, getKind, analyzerManager, isComment);
3079 3080
        }

3081 3082
        internal void SymbolDeclaredEvent(Symbol symbol)
        {
3083
            EventQueue?.TryEnqueue(new SymbolDeclaredCompilationEvent(this, symbol));
3084
        }
3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102

        /// <summary>
        /// Determine if enum arrays can be initialized using block initialization.
        /// </summary>
        /// <returns>True if it's safe to use block initialization for enum arrays.</returns>
        /// <remarks>
        /// In NetFx 4.0, block array initializers do not work on all combinations of {32/64 X Debug/Retail} when array elements are enums.
        /// This is fixed in 4.5 thus enabling block array initialization for a very common case.
        /// We look for the presence of <see cref="System.Runtime.GCLatencyMode.SustainedLowLatency"/> which was introduced in .Net 4.5
        /// </remarks>
        internal bool EnableEnumArrayBlockInitialization
        {
            get
            {
                var sustainedLowLatency = GetWellKnownTypeMember(WellKnownMember.System_Runtime_GCLatencyMode__SustainedLowLatency);
                return sustainedLowLatency != null && sustainedLowLatency.ContainingAssembly == Assembly.CorLibrary;
            }
        }
3103

H
heejaechang 已提交
3104 3105
        private class SymbolSearcher
        {
3106 3107
            private readonly Dictionary<Declaration, NamespaceOrTypeSymbol> _cache;
            private readonly CSharpCompilation _compilation;
H
heejaechang 已提交
3108 3109 3110

            public SymbolSearcher(CSharpCompilation compilation)
            {
3111 3112
                _cache = new Dictionary<Declaration, NamespaceOrTypeSymbol>();
                _compilation = compilation;
H
heejaechang 已提交
3113 3114 3115 3116 3117 3118 3119
            }

            public IEnumerable<ISymbol> GetSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter, CancellationToken cancellationToken)
            {
                var result = new HashSet<ISymbol>();
                var spine = new List<MergedNamespaceOrTypeDeclaration>();

3120
                AppendSymbolsWithName(spine, _compilation.MergedRootDeclaration, predicate, filter, result, cancellationToken);
H
heejaechang 已提交
3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137

                return result;
            }

            private void AppendSymbolsWithName(
                List<MergedNamespaceOrTypeDeclaration> spine, MergedNamespaceOrTypeDeclaration current,
                Func<string, bool> predicate, SymbolFilter filter, HashSet<ISymbol> set, CancellationToken cancellationToken)
            {
                var includeNamespace = (filter & SymbolFilter.Namespace) == SymbolFilter.Namespace;
                var includeType = (filter & SymbolFilter.Type) == SymbolFilter.Type;
                var includeMember = (filter & SymbolFilter.Member) == SymbolFilter.Member;

                if (current.Kind == DeclarationKind.Namespace)
                {
                    if (includeNamespace && predicate(current.Name))
                    {
                        var container = GetSpineSymbol(spine);
3138 3139 3140 3141 3142
                        var symbol = GetSymbol(container, current);
                        if (symbol != null)
                        {
                            set.Add(symbol);
                        }
H
heejaechang 已提交
3143 3144 3145 3146 3147 3148 3149
                    }
                }
                else
                {
                    if (includeType && predicate(current.Name))
                    {
                        var container = GetSpineSymbol(spine);
3150 3151 3152 3153 3154
                        var symbol = GetSymbol(container, current);
                        if (symbol != null)
                        {
                            set.Add(symbol);
                        }
H
heejaechang 已提交
3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188
                    }

                    if (includeMember)
                    {
                        AppendMemberSymbolsWithName(spine, current, predicate, set, cancellationToken);
                    }
                }

                spine.Add(current);

                foreach (var child in current.Children.OfType<MergedNamespaceOrTypeDeclaration>())
                {
                    if (includeMember || includeType)
                    {
                        AppendSymbolsWithName(spine, child, predicate, filter, set, cancellationToken);
                        continue;
                    }

                    if (child.Kind == DeclarationKind.Namespace)
                    {
                        AppendSymbolsWithName(spine, child, predicate, filter, set, cancellationToken);
                    }
                }

                // pop last one
                spine.RemoveAt(spine.Count - 1);
            }

            private void AppendMemberSymbolsWithName(
                List<MergedNamespaceOrTypeDeclaration> spine, MergedNamespaceOrTypeDeclaration current,
                Func<string, bool> predicate, HashSet<ISymbol> set, CancellationToken cancellationToken)
            {
                spine.Add(current);

3189
                var container = GetSpineSymbol(spine);
3190
                if (container != null)
H
heejaechang 已提交
3191
                {
3192
                    foreach (var member in container.GetMembers())
H
heejaechang 已提交
3193
                    {
3194 3195 3196 3197 3198 3199
                        if (!member.IsTypeOrTypeAlias() &&
                            (member.CanBeReferencedByName || member.IsExplicitInterfaceImplementation() || member.IsIndexer()) &&
                            predicate(member.Name))
                        {
                            set.Add(member);
                        }
H
heejaechang 已提交
3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218
                    }
                }

                spine.RemoveAt(spine.Count - 1);
            }

            private NamespaceOrTypeSymbol GetSpineSymbol(List<MergedNamespaceOrTypeDeclaration> spine)
            {
                if (spine.Count == 0)
                {
                    return null;
                }

                var symbol = GetCachedSymbol(spine[spine.Count - 1]);
                if (symbol != null)
                {
                    return symbol;
                }

3219
                var current = _compilation.GlobalNamespace as NamespaceOrTypeSymbol;
H
heejaechang 已提交
3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230
                for (var i = 1; i < spine.Count; i++)
                {
                    current = GetSymbol(current, spine[i]);
                }

                return current;
            }

            private NamespaceOrTypeSymbol GetCachedSymbol(MergedNamespaceOrTypeDeclaration declaration)
            {
                NamespaceOrTypeSymbol symbol;
3231
                if (_cache.TryGetValue(declaration, out symbol))
H
heejaechang 已提交
3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242
                {
                    return symbol;
                }

                return null;
            }

            private NamespaceOrTypeSymbol GetSymbol(NamespaceOrTypeSymbol container, MergedNamespaceOrTypeDeclaration declaration)
            {
                if (container == null)
                {
3243
                    return _compilation.GlobalNamespace;
H
heejaechang 已提交
3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264
                }

                if (declaration.Kind == DeclarationKind.Namespace)
                {
                    AddCache(container.GetMembers(declaration.Name).OfType<NamespaceOrTypeSymbol>());
                }
                else
                {
                    AddCache(container.GetTypeMembers(declaration.Name));
                }

                return GetCachedSymbol(declaration);
            }

            private void AddCache(IEnumerable<NamespaceOrTypeSymbol> symbols)
            {
                foreach (var symbol in symbols)
                {
                    var mergedNamespace = symbol as MergedNamespaceSymbol;
                    if (mergedNamespace != null)
                    {
3265
                        _cache[mergedNamespace.ConstituentNamespaces.OfType<SourceNamespaceSymbol>().First().MergedDeclaration] = symbol;
H
heejaechang 已提交
3266 3267 3268 3269 3270 3271
                        continue;
                    }

                    var sourceNamespace = symbol as SourceNamespaceSymbol;
                    if (sourceNamespace != null)
                    {
3272
                        _cache[sourceNamespace.MergedDeclaration] = sourceNamespace;
H
heejaechang 已提交
3273 3274 3275 3276 3277 3278
                        continue;
                    }

                    var sourceType = symbol as SourceMemberContainerTypeSymbol;
                    if (sourceType != null)
                    {
3279
                        _cache[sourceType.MergedDeclaration] = sourceType;
H
heejaechang 已提交
3280 3281 3282 3283
                    }
                }
            }
        }
P
Pilchie 已提交
3284 3285
    }
}