CSharpCompilation.cs 125.7 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 14 15 16 17
using System.Threading;
using System.Threading.Tasks;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.CSharp.Emit;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
18
using Microsoft.CodeAnalysis.Diagnostics;
P
Pilchie 已提交
19 20
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Instrumentation;
21
using Microsoft.CodeAnalysis.Symbols;
P
Pilchie 已提交
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;

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.
        //
        // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 

T
TomasMatousek 已提交
45 46
        internal static readonly ParallelOptions DefaultParallelOptions = new ParallelOptions();

P
Pilchie 已提交
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
        private readonly CSharpCompilationOptions options;
        private readonly ImmutableArray<SyntaxTree> syntaxTrees; // In ordinal order.
        private readonly ImmutableDictionary<SyntaxTree, Lazy<RootSingleNamespaceDeclaration>> rootNamespaces;
        private readonly DeclarationTable declarationTable;
        private readonly Lazy<Imports> globalImports;
        private readonly Lazy<AliasSymbol> globalNamespaceAlias;  // alias symbol used to resolve "global::".
        private readonly Lazy<ImplicitNamedTypeSymbol> scriptClass;
        private readonly CSharpCompilation previousSubmission;

        // 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.
        private ConcurrentSet<ImportInfo> lazyImportInfos;

        // Cache the CLS diagnostics for the whole compilation so they aren't computed repeatedly.
        // NOTE: Presently, we do not cache the per-tree diagnostics.
        private ImmutableArray<Diagnostic> lazyClsComplianceDiagnostics;

        private Conversions conversions;
        internal Conversions Conversions
        {
            get
            {
                if (conversions == null)
                {
                    Interlocked.CompareExchange(ref conversions, new BuckStopsHereBinder(this).Conversions, null);
                }

                return conversions;
            }
        }

        /// <summary>
        /// Manages anonymous types declared in this compilation. Unifies types that are structurally equivalent.
        /// </summary>
        private AnonymousTypeManager anonymousTypeManager;

        private NamespaceSymbol lazyGlobalNamespace;

        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>
        private SourceAssemblySymbol lazyAssemblySymbol;

        /// <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.
        /// In most cases this can be determined without performing the binding. If the compilation however contains a circular 
        /// metadata reference (a metadata reference that refers back to the compilation) we need to avoid sharing of the binding results.
        /// We do so by creating a new reference manager for such compilation. 
        /// </summary>
        private ReferenceManager referenceManager;

        /// <summary>
        /// Contains the main method of this assembly, if there is one.
        /// </summary>
        private EntryPoint lazyEntryPoint;

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

P
Pilchie 已提交
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149
        public override string Language
        {
            get
            {
                return LanguageNames.CSharp;
            }
        }

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

        /// <summary>
        /// The options the compilation was created with. 
        /// </summary>
        public new CSharpCompilationOptions Options
        {
            get
            {
                return options;
            }
        }

        internal AnonymousTypeManager AnonymousTypeManager
        {
            get
            {
                return anonymousTypeManager;
            }
        }

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

158 159 160 161 162 163 164 165
        /// <summary>
        /// The language version that was used to parse the syntax trees of this compilation.
        /// </summary>
        public LanguageVersion LanguageVersion
        {
            get; private set;
        }

P
Pilchie 已提交
166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191
        public override INamedTypeSymbol CreateErrorTypeSymbol(INamespaceOrTypeSymbol container, string name, int arity)
        {
            return new ExtendedErrorTypeSymbol((NamespaceOrTypeSymbol)container, name, arity, null);
        }

        #region Constructors and Factories

        private static CSharpCompilationOptions DefaultOptions = new CSharpCompilationOptions(OutputKind.ConsoleApplication);
        private static CSharpCompilationOptions DefaultSubmissionOptions = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary);

        /// <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(
192
                assemblyName,
P
Pilchie 已提交
193 194
                options ?? DefaultOptions,
                (syntaxTrees != null) ? syntaxTrees.Cast<SyntaxTree>() : null,
195 196 197 198
                references,
                previousSubmission: null,
                returnType: null,
                hostObjectType: null,
P
Pilchie 已提交
199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279
                isSubmission: false);
        }

        /// <summary>
        /// Creates a new compilation that can be used in scripting.
        /// </summary>
        public static CSharpCompilation CreateSubmission(
            string assemblyName,
            SyntaxTree syntaxTree = null,
            IEnumerable<MetadataReference> references = null,
            CSharpCompilationOptions options = null,
            Compilation previousSubmission = null,
            Type returnType = null,
            Type hostObjectType = null)
        {
            CheckSubmissionOptions(options);

            return Create(
                assemblyName,
                options ?? DefaultSubmissionOptions,
                (syntaxTree != null) ? new[] { syntaxTree } : SpecializedCollections.EmptyEnumerable<SyntaxTree>(),
                references,
                (CSharpCompilation)previousSubmission,
                returnType,
                hostObjectType,
                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);
            CheckAssemblyName(assemblyName);

            var validatedReferences = ValidateReferences<CSharpCompilationReference>(references);
            ValidateSubmissionParameters(previousSubmission, returnType, ref hostObjectType);

            var compilation = new CSharpCompilation(
                assemblyName,
                options,
                validatedReferences,
                ImmutableArray<SyntaxTree>.Empty,
                ImmutableDictionary.Create<SyntaxTree, int>(ReferenceEqualityComparer.Instance),
                ImmutableDictionary.Create<SyntaxTree, Lazy<RootSingleNamespaceDeclaration>>(),
                DeclarationTable.Empty,
                previousSubmission,
                returnType,
                hostObjectType,
                isSubmission,
                referenceManager: null,
                reuseReferenceManager: false);

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

            Debug.Assert((object)compilation.lazyAssemblySymbol == null);
            return compilation;
        }

        private CSharpCompilation(
            string assemblyName,
            CSharpCompilationOptions options,
            ImmutableArray<MetadataReference> references,
            ImmutableArray<SyntaxTree> syntaxTrees,
            ImmutableDictionary<SyntaxTree, int> syntaxTreeOrdinalMap,
            ImmutableDictionary<SyntaxTree, Lazy<RootSingleNamespaceDeclaration>> rootNamespaces,
            DeclarationTable declarationTable,
            CSharpCompilation previousSubmission,
            Type submissionReturnType,
            Type hostObjectType,
            bool isSubmission,
            ReferenceManager referenceManager,
280 281 282
            bool reuseReferenceManager,
            AsyncQueue<CompilationEvent> eventQueue = null)
            : base(assemblyName, references, submissionReturnType, hostObjectType, isSubmission, syntaxTreeOrdinalMap, eventQueue)
P
Pilchie 已提交
283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300
        {
            using (Logger.LogBlock(FunctionId.CSharp_Compilation_Create, message: assemblyName))
            {
                this.wellKnownMemberSignatureComparer = new WellKnownMembersSignatureComparer(this);
                this.options = options;
                this.syntaxTrees = syntaxTrees;

                this.rootNamespaces = rootNamespaces;
                this.declarationTable = declarationTable;

                Debug.Assert(syntaxTrees.All(tree => syntaxTrees[syntaxTreeOrdinalMap[tree]] == tree));
                Debug.Assert(syntaxTrees.SetEquals(rootNamespaces.Keys.AsImmutable(), EqualityComparer<SyntaxTree>.Default));

                this.builtInOperators = new BuiltInOperators(this);
                this.scriptClass = new Lazy<ImplicitNamedTypeSymbol>(BindScriptClass);
                this.globalImports = new Lazy<Imports>(BindGlobalUsings);
                this.globalNamespaceAlias = new Lazy<AliasSymbol>(CreateGlobalNamespaceAlias);
                this.anonymousTypeManager = new AnonymousTypeManager(this);
301
                this.LanguageVersion = CommonLanguageVersion(syntaxTrees);
P
Pilchie 已提交
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321

                if (isSubmission)
                {
                    Debug.Assert(previousSubmission == null || previousSubmission.HostObjectType == hostObjectType);

                    this.previousSubmission = previousSubmission;
                }
                else
                {
                    Debug.Assert(previousSubmission == null && submissionReturnType == null && hostObjectType == null);
                }

                if (reuseReferenceManager)
                {
                    referenceManager.AssertCanReuseForCompilation(this);
                    this.referenceManager = referenceManager;
                }
                else
                {
                    this.referenceManager = new ReferenceManager(
322
                        MakeSourceAssemblySimpleName(),
P
Pilchie 已提交
323 324 325 326 327
                        options.AssemblyIdentityComparer,
                        (referenceManager != null) ? referenceManager.ObservedMetadata : null);
                }

                Debug.Assert((object)this.lazyAssemblySymbol == null);
328
                if (EventQueue != null) EventQueue.Enqueue(new CompilationStartedEvent(this));
P
Pilchie 已提交
329 330 331
            }
        }

332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351
        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)
                {
                    throw new ArgumentException("inconsistent language versions", nameof(syntaxTrees));
                }
            }

            return result ?? CSharpParseOptions.Default.LanguageVersion;
        }


P
Pilchie 已提交
352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
        /// <summary>
        /// Create a duplicate of this compilation with different symbol instances.
        /// </summary>
        public new CSharpCompilation Clone()
        {
            return new CSharpCompilation(
                this.AssemblyName,
                this.options,
                this.ExternalReferences,
                this.SyntaxTrees,
                this.syntaxTreeOrdinalMap,
                this.rootNamespaces,
                this.declarationTable,
                this.previousSubmission,
                this.SubmissionReturnType,
                this.HostObjectType,
                this.IsSubmission,
                this.referenceManager,
                reuseReferenceManager: true);
        }

        private CSharpCompilation UpdateSyntaxTrees(
            ImmutableArray<SyntaxTree> syntaxTrees,
            ImmutableDictionary<SyntaxTree, int> syntaxTreeOrdinalMap,
            ImmutableDictionary<SyntaxTree, Lazy<RootSingleNamespaceDeclaration>> rootNamespaces,
            DeclarationTable declarationTable,
            bool referenceDirectivesChanged)
        {
            return new CSharpCompilation(
                this.AssemblyName,
                this.options,
                this.ExternalReferences,
                syntaxTrees,
                syntaxTreeOrdinalMap,
                rootNamespaces,
                declarationTable,
                this.previousSubmission,
                this.SubmissionReturnType,
                this.HostObjectType,
                this.IsSubmission,
                this.referenceManager,
                reuseReferenceManager: !referenceDirectivesChanged);
        }

        /// <summary>
        /// Creates a new compilation with the specified name.
        /// </summary>
        public new CSharpCompilation WithAssemblyName(string assemblyName)
        {
            CheckAssemblyName(assemblyName);

            // 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 
            // to this compilation.

            return new CSharpCompilation(
                assemblyName,
                this.options,
                this.ExternalReferences,
                this.SyntaxTrees,
                this.syntaxTreeOrdinalMap,
                this.rootNamespaces,
                this.declarationTable,
                this.previousSubmission,
                this.SubmissionReturnType,
                this.HostObjectType,
                this.IsSubmission,
                this.referenceManager,
                reuseReferenceManager: assemblyName == this.AssemblyName);
        }

        /// <summary>
        /// Creates a new compilation with the specified references.
        /// </summary>
        /// <remarks>
        /// The new <see cref="CSharpCompilation"/> will query the given <see cref="MetadataReference"/> for the underlying 
        /// metadata as soon as the are needed. 
        /// 
        /// 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,
                this.options,
                ValidateReferences<CSharpCompilationReference>(references),
                this.SyntaxTrees,
                this.syntaxTreeOrdinalMap,
                this.rootNamespaces,
                this.declarationTable,
                this.previousSubmission,
                this.SubmissionReturnType,
                this.HostObjectType,
                this.IsSubmission,
                referenceManager: null,
                reuseReferenceManager: false);
        }

        /// <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)
        {
            // Checks to see if the new options support reusing the reference manager
            bool reuseReferenceManager = this.Options.CanReuseCompilationReferenceManager(options);

            return new CSharpCompilation(
                this.AssemblyName,
                options,
                this.ExternalReferences,
                this.syntaxTrees,
                this.syntaxTreeOrdinalMap,
                this.rootNamespaces,
                this.declarationTable,
                this.previousSubmission,
                this.SubmissionReturnType,
                this.HostObjectType,
                this.IsSubmission,
                this.referenceManager,
                reuseReferenceManager);
        }

        /// <summary>
        /// Returns a new compilation with the given compilation set as the previous submission.
        /// </summary>
        internal CSharpCompilation WithPreviousSubmission(CSharpCompilation newPreviousSubmission)
        {
            if (!this.IsSubmission)
            {
                throw new NotSupportedException("Can't have a previousSubmission when not a submission");
            }

            // Reference binding doesn't depend on previous submission so we can reuse it.

            return new CSharpCompilation(
                this.AssemblyName,
                this.options,
                this.ExternalReferences,
                this.SyntaxTrees,
                this.syntaxTreeOrdinalMap,
                this.rootNamespaces,
                this.declarationTable,
                newPreviousSubmission,
                this.SubmissionReturnType,
                this.HostObjectType,
                this.IsSubmission,
                this.referenceManager,
                reuseReferenceManager: true);
        }

515 516 517
        /// <summary>
        /// Returns a new compilation with a given event queue.
        /// </summary>
518
        internal override Compilation WithEventQueue(AsyncQueue<CompilationEvent> eventQueue)
519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
        {
            return new CSharpCompilation(
                this.AssemblyName,
                this.options,
                this.ExternalReferences,
                this.SyntaxTrees,
                this.syntaxTreeOrdinalMap,
                this.rootNamespaces,
                this.declarationTable,
                this.previousSubmission,
                this.SubmissionReturnType,
                this.HostObjectType,
                this.IsSubmission,
                this.referenceManager,
                reuseReferenceManager: true,
                eventQueue: eventQueue);
        }

P
Pilchie 已提交
537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561
        #endregion

        #region Submission

        internal new CSharpCompilation PreviousSubmission
        {
            get { return previousSubmission; }
        }

        // TODO (tomat): consider moving this method to SemanticModel

        /// <summary>
        /// Returns the type of the submission return value. 
        /// </summary>
        /// <returns>
        /// The type of the last expression of the submission. 
        /// Null if the type of the last expression is unknown (null).
        /// Void type if the type of the last expression statement is void or 
        /// the submission ends with a declaration or statement that is not an expression statement.
        /// </returns>
        /// <remarks>
        /// Note that the return type is System.Void for both compilations "System.Console.WriteLine();" and "System.Console.WriteLine()", 
        /// and <paramref name="hasValue"/> is <c>False</c> for the former and <c>True</c> for the latter.
        /// </remarks>
        /// <param name="hasValue">True if the submission has value, i.e. if it ends with a statement that is an expression statement.</param>
562
        /// <exception cref="InvalidOperationException">The compilation doesn't represent a submission (<see cref="Compilation.IsSubmission"/> return false).</exception>
P
Pilchie 已提交
563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578
        internal new TypeSymbol GetSubmissionResultType(out bool hasValue)
        {
            if (!IsSubmission)
            {
                throw new InvalidOperationException(CSharpResources.ThisCompilationNotInteractive);
            }

            hasValue = false;

            // submission can be empty or comprise of a script file
            SyntaxTree tree = SyntaxTrees.SingleOrDefault();
            if (tree == null || tree.Options.Kind != SourceCodeKind.Interactive)
            {
                return GetSpecialType(SpecialType.System_Void);
            }

579 580
            var lastStatement = (GlobalStatementSyntax)tree.GetCompilationUnitRoot().Members.LastOrDefault(decl => decl.Kind() == SyntaxKind.GlobalStatement);
            if (lastStatement == null || lastStatement.Statement.Kind() != SyntaxKind.ExpressionStatement)
P
Pilchie 已提交
581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851
            {
                return GetSpecialType(SpecialType.System_Void);
            }

            var expressionStatement = (ExpressionStatementSyntax)lastStatement.Statement;
            if (!expressionStatement.SemicolonToken.IsMissing)
            {
                return GetSpecialType(SpecialType.System_Void);
            }

            var model = GetSemanticModel(tree);
            hasValue = true;
            var expression = expressionStatement.Expression;
            var info = model.GetTypeInfo(expression);
            return (TypeSymbol)info.ConvertedType;
        }

        #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
        {
            get { return this.syntaxTrees; }
        }

        /// <summary>
        /// Returns true if this compilation contains the specified tree.  False otherwise.
        /// </summary>
        public new bool ContainsSyntaxTree(SyntaxTree syntaxTree)
        {
            var cstree = syntaxTree as SyntaxTree;
            return cstree != null && rootNamespaces.ContainsKey((cstree));
        }

        /// <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)
        {
            using (Logger.LogBlock(FunctionId.CSharp_Compilation_AddSyntaxTrees, message: this.AssemblyName))
            {
                if (trees == null)
                {
                    throw new ArgumentNullException("trees");
                }

                if (trees.IsEmpty())
                {
                    return this;
                }

                // We're using a try-finally for this builder because there's a test that 
                // specifically checks for one or more of the argument exceptions below
                // and we don't want to see console spew (even though we don't generally
                // care about pool "leaks" in exceptional cases).  Alternatively, we
                // could create a new ArrayBuilder.
                var builder = ArrayBuilder<SyntaxTree>.GetInstance();
                try
                {
                    builder.AddRange(this.SyntaxTrees);

                    bool referenceDirectivesChanged = false;
                    var oldTreeCount = this.SyntaxTrees.Length;
                    var ordinalMap = this.syntaxTreeOrdinalMap;
                    var declMap = rootNamespaces;
                    var declTable = declarationTable;
                    int i = 0;
                    foreach (var tree in trees.Cast<CSharpSyntaxTree>())
                    {
                        if (tree == null)
                        {
                            throw new ArgumentNullException("trees[" + i + "]");
                        }

                        if (!tree.HasCompilationUnitRoot)
                        {
                            throw new ArgumentException(String.Format(CSharpResources.TreeMustHaveARootNodeWith, i));
                        }

                        if (declMap.ContainsKey(tree))
                        {
                            throw new ArgumentException(CSharpResources.SyntaxTreeAlreadyPresent, String.Format(CSharpResources.Trees0, i));
                        }

                        if (IsSubmission && tree.Options.Kind == SourceCodeKind.Regular)
                        {
                            throw new ArgumentException(CSharpResources.SubmissionCanOnlyInclude, String.Format(CSharpResources.Trees0, i));
                        }

                        AddSyntaxTreeToDeclarationMapAndTable(tree, options, IsSubmission, ref declMap, ref declTable, ref referenceDirectivesChanged);
                        builder.Add(tree);
                        ordinalMap = ordinalMap.Add(tree, oldTreeCount + i);

                        i++;
                    }

                    if (IsSubmission && declMap.Count > 1)
                    {
                        throw new ArgumentException(CSharpResources.SubmissionCanHaveAtMostOne, "trees");
                    }

                    return UpdateSyntaxTrees(builder.ToImmutable(), ordinalMap, declMap, declTable, referenceDirectivesChanged);
                }
                finally
                {
                    builder.Free();
                }
            }
        }

        private static void AddSyntaxTreeToDeclarationMapAndTable(
            SyntaxTree tree,
            CSharpCompilationOptions options,
            bool isSubmission,
            ref ImmutableDictionary<SyntaxTree, Lazy<RootSingleNamespaceDeclaration>> declMap,
            ref DeclarationTable declTable,
            ref bool referenceDirectivesChanged)
        {
            var lazyRoot = new Lazy<RootSingleNamespaceDeclaration>(() => DeclarationTreeBuilder.ForTree(tree, options.ScriptClassName ?? "", isSubmission));
            declMap = declMap.SetItem(tree, lazyRoot);
            declTable = declTable.AddRootDeclaration(lazyRoot);
            referenceDirectivesChanged = referenceDirectivesChanged || tree.HasReferenceDirectives();
        }

        /// <summary>
        /// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees
        /// added later. 
        /// </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
        /// added later. 
        /// </summary>
        public new CSharpCompilation RemoveSyntaxTrees(IEnumerable<SyntaxTree> trees)
        {
            using (Logger.LogBlock(FunctionId.CSharp_Compilation_RemoveSyntaxTrees, message: this.AssemblyName))
            {
                if (trees == null)
                {
                    throw new ArgumentNullException("trees");
                }

                if (trees.IsEmpty())
                {
                    return this;
                }

                bool referenceDirectivesChanged = false;
                var removeSet = new HashSet<SyntaxTree>();
                var declMap = rootNamespaces;
                var declTable = declarationTable;
                foreach (var tree in trees.Cast<CSharpSyntaxTree>())
                {
                    RemoveSyntaxTreeFromDeclarationMapAndTable(tree, ref declMap, ref declTable, ref referenceDirectivesChanged);
                    removeSet.Add(tree);
                }

                Debug.Assert(!removeSet.IsEmpty());

                // We're going to have to revise the ordinals of all
                // trees after the first one removed, so just build
                // a new map.
                var ordinalMap = ImmutableDictionary.Create<SyntaxTree, int>();
                var builder = ArrayBuilder<SyntaxTree>.GetInstance();
                int i = 0;
                foreach (var tree in this.SyntaxTrees)
                {
                    if (!removeSet.Contains(tree))
                    {
                        builder.Add(tree);
                        ordinalMap = ordinalMap.Add(tree, i++);
                    }
                }

                return UpdateSyntaxTrees(builder.ToImmutableAndFree(), ordinalMap, declMap, declTable, referenceDirectivesChanged);
            }
        }

        private static void RemoveSyntaxTreeFromDeclarationMapAndTable(
            SyntaxTree tree,
            ref ImmutableDictionary<SyntaxTree, Lazy<RootSingleNamespaceDeclaration>> declMap,
            ref DeclarationTable declTable,
            ref bool referenceDirectivesChanged)
        {
            Lazy<RootSingleNamespaceDeclaration> lazyRoot;
            if (!declMap.TryGetValue(tree, out lazyRoot))
            {
                throw new ArgumentException(string.Format(CSharpResources.SyntaxTreeNotFoundTo, tree), "trees");
            }

            declTable = declTable.RemoveRootDeclaration(lazyRoot);
            declMap = declMap.Remove(tree);
            referenceDirectivesChanged = referenceDirectivesChanged || tree.HasReferenceDirectives();
        }

        /// <summary>
        /// Creates a new compilation without any syntax trees. Preserves metadata info
        /// from this compilation for use with trees added later. 
        /// </summary>
        public new CSharpCompilation RemoveAllSyntaxTrees()
        {
            return UpdateSyntaxTrees(
                ImmutableArray<SyntaxTree>.Empty,
                ImmutableDictionary.Create<SyntaxTree, int>(),
                ImmutableDictionary.Create<SyntaxTree, Lazy<RootSingleNamespaceDeclaration>>(),
                DeclarationTable.Empty,
                referenceDirectivesChanged: declarationTable.ReferenceDirectives.Any());
        }

        /// <summary>
        /// Creates a new compilation without the old tree but with the new tree.
        /// </summary>
        public new CSharpCompilation ReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree newTree)
        {
            using (Logger.LogBlock(FunctionId.CSharp_Compilation_ReplaceSyntaxTree, message: this.AssemblyName))
            {
                // this is just to force a cast exception
                oldTree = (CSharpSyntaxTree)oldTree;
                newTree = (CSharpSyntaxTree)newTree;

                if (oldTree == null)
                {
                    throw new ArgumentNullException("oldTree");
                }

                if (newTree == null)
                {
                    return this.RemoveSyntaxTrees(oldTree);
                }
                else if (newTree == oldTree)
                {
                    return this;
                }

                if (!newTree.HasCompilationUnitRoot)
                {
                    throw new ArgumentException(CSharpResources.TreeMustHaveARootNodeWith, "newTree");
                }

                var declMap = rootNamespaces;
                var declTable = declarationTable;
                bool referenceDirectivesChanged = false;

                // TODO(tomat): Consider comparing #r's of the old and the new tree. If they are exactly the same we could still reuse.
                // This could be a perf win when editing a script file in the IDE. The services create a new compilation every keystroke 
                // that replaces the tree with a new one.

                RemoveSyntaxTreeFromDeclarationMapAndTable(oldTree, ref declMap, ref declTable, ref referenceDirectivesChanged);
                AddSyntaxTreeToDeclarationMapAndTable(newTree, options, this.IsSubmission, ref declMap, ref declTable, ref referenceDirectivesChanged);

                var ordinalMap = this.syntaxTreeOrdinalMap;

                Debug.Assert(ordinalMap.ContainsKey(oldTree)); // Checked by RemoveSyntaxTreeFromDeclarationMapAndTable
                var oldOrdinal = ordinalMap[oldTree];

P
Pharring 已提交
852
                var newArray = this.SyntaxTrees.SetItem(oldOrdinal, newTree);
P
Pilchie 已提交
853 854 855 856 857

                // CONSIDER: should this be an operation on ImmutableDictionary?
                ordinalMap = ordinalMap.Remove(oldTree);
                ordinalMap = ordinalMap.SetItem(newTree, oldOrdinal);

P
Pharring 已提交
858
                return UpdateSyntaxTrees(newArray, ordinalMap, declMap, declTable, referenceDirectivesChanged);
P
Pilchie 已提交
859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 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 919 920 921 922 923 924 925 926 927 928 929 930 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 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
            }
        }

        #endregion

        #region References

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

        internal new ReferenceManager GetBoundReferenceManager()
        {
            if ((object)lazyAssemblySymbol == null)
            {
                referenceManager.CreateSourceAssemblyForCompilation(this);
                Debug.Assert((object)lazyAssemblySymbol != null);
            }

            // referenceManager can only be accessed after we initialized the lazyAssemblySymbol.
            // In fact, initialization of the assembly symbol might change the reference manager.
            return referenceManager;
        }

        // for testing only:
        internal bool ReferenceManagerEquals(CSharpCompilation other)
        {
            return ReferenceEquals(this.referenceManager, other.referenceManager);
        }

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

        internal override IDictionary<string, MetadataReference> ReferenceDirectiveMap
        {
            get
            {
                return GetBoundReferenceManager().ReferenceDirectiveMap;
            }
        }

        // 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>
        /// Uses object identity when comparing two references. 
        /// </remarks>
        internal new Symbol GetAssemblyOrModuleSymbol(MetadataReference reference)
        {
            if (reference == null)
            {
                throw new ArgumentNullException("reference");
            }

            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
        {
            get { return declarationTable.ReferenceDirectives; }
        }

        /// <summary>
        /// Returns a metadata reference that a given #r resolves to.
        /// </summary>
        /// <param name="directive">#r directive.</param>
        /// <returns>Metadata reference the specified directive resolves to.</returns>
        public MetadataReference GetDirectiveReference(ReferenceDirectiveTriviaSyntax directive)
        {
            return ReferenceDirectiveMap[directive.File.ValueText];
        }

        /// <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);
        }

1015
        public override CompilationReference ToMetadataReference(ImmutableArray<string> aliases = default(ImmutableArray<string>), bool embedInteropTypes = false)
P
Pilchie 已提交
1016
        {
1017
            return new CSharpCompilationReference(this, aliases, embedInteropTypes);
P
Pilchie 已提交
1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
        }

        // 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.
        // Metadata imported from aliased assemblies is not visible at the source level except through 
        // the use of an extern alias directive. So exclude them from this list which is used to construct
        // the global namespace.
        private IEnumerable<ModuleSymbol> GetAllUnaliasedModules()
        {
            // Get all assemblies in this compilation, including the source assembly and all referenced assemblies.
            ArrayBuilder<ModuleSymbol> modules = new ArrayBuilder<ModuleSymbol>();

            // NOTE: This includes referenced modules - they count as modules of the compilation assembly.
            modules.AddRange(this.Assembly.Modules);

            foreach (var pair in GetBoundReferenceManager().ReferencedAssembliesMap)
            {
                MetadataReference reference = pair.Key;
                ReferenceManager.ReferencedAssembly referencedAssembly = pair.Value;
                if (reference.Properties.Kind == MetadataImageKind.Assembly) // Already handled modules above.
                {
1039
                    if (referencedAssembly.DeclarationsAccessibleWithoutAlias())
P
Pilchie 已提交
1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 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 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 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 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206
                    {
                        modules.AddRange(referencedAssembly.Symbol.Modules);
                    }
                }
            }

            return modules;
        }

        /// <summary>
        /// Gets the <see cref="MetadataReference"/> that corresponds to the assembly symbol. 
        /// </summary>
        public new MetadataReference GetMetadataReference(IAssemblySymbol assemblySymbol)
        {
            return this.GetBoundReferenceManager().ReferencedAssembliesMap.Where(kvp => object.ReferenceEquals(kvp.Value.Symbol, assemblySymbol)).Select(kvp => kvp.Key).FirstOrDefault();
        }

        #endregion

        #region Symbols

        /// <summary>
        /// The AssemblySymbol that represents the assembly being created.
        /// </summary>
        internal SourceAssemblySymbol SourceAssembly
        {
            get
            {
                GetBoundReferenceManager();
                return lazyAssemblySymbol;
            }
        }

        /// <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>
        /// Gets the root namespace that contains all namespaces and types defined in source code or in 
        /// referenced metadata, merged into a single namespace hierarchy.
        /// </summary>
        internal new NamespaceSymbol GlobalNamespace
        {
            get
            {
                if ((object)lazyGlobalNamespace == null)
                {
                    using (Logger.LogBlock(FunctionId.CSharp_Compilation_GetGlobalNamespace, message: this.AssemblyName))
                    {
                        // Get the root namespace from each module, and merge them all together
                        HashSet<NamespaceSymbol> allGlobalNamespaces = new HashSet<NamespaceSymbol>();
                        foreach (ModuleSymbol module in GetAllUnaliasedModules())
                        {
                            allGlobalNamespaces.Add(module.GlobalNamespace);
                        }

                        var result = MergedNamespaceSymbol.Create(new NamespaceExtent(this),
                            null,
                            allGlobalNamespaces.AsImmutable());
                        Interlocked.CompareExchange(ref lazyGlobalNamespace, result, null);
                    }
                }

                return lazyGlobalNamespace;
            }
        }

        /// <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;
        }

        private ConcurrentDictionary<string, NamespaceSymbol> externAliasTargets;

        internal bool GetExternAliasTarget(string aliasName, out NamespaceSymbol @namespace)
        {
            if (externAliasTargets == null)
            {
                Interlocked.CompareExchange(ref this.externAliasTargets, new ConcurrentDictionary<string, NamespaceSymbol>(), null);
            }
            else if (externAliasTargets.TryGetValue(aliasName, out @namespace))
            {
                return !(@namespace is MissingNamespaceSymbol);
            }

            ArrayBuilder<NamespaceSymbol> builder = null;
            foreach (var referencedAssembly in GetBoundReferenceManager().ReferencedAssembliesMap.Values)
            {
                if (referencedAssembly.Aliases.Contains(aliasName))
                {
                    builder = builder ?? ArrayBuilder<NamespaceSymbol>.GetInstance();
                    builder.Add(referencedAssembly.Symbol.GlobalNamespace);
                }
            }

            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).
            @namespace = externAliasTargets.GetOrAdd(aliasName, @namespace);

            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
        {
            get { return scriptClass.Value; }
        }

        /// <summary>
        /// Resolves a symbol that represents script container (Script class). Uses the
1207
        /// full name of the container class stored in <see cref="CompilationOptions.ScriptClassName"/> to find the symbol.
P
Pilchie 已提交
1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 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 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335
        /// </summary>
        /// <returns>The Script class symbol or null if it is not defined.</returns>
        private ImplicitNamedTypeSymbol BindScriptClass()
        {
            if (options.ScriptClassName == null || !options.ScriptClassName.IsValidClrTypeName())
            {
                return null;
            }

            var namespaceOrType = this.Assembly.GlobalNamespace.GetNamespaceOrTypeByQualifiedName(options.ScriptClassName.Split('.')).AsSingleton();
            return namespaceOrType as ImplicitNamedTypeSymbol;
        }

        internal Imports GlobalImports
        {
            get { return globalImports.Value; }
        }

        internal IEnumerable<NamespaceOrTypeSymbol> GlobalUsings
        {
            get
            {
                return GlobalImports.Usings.Select(u => u.NamespaceOrType);
            }
        }

        internal AliasSymbol GlobalNamespaceAlias
        {
            get
            {
                return globalNamespaceAlias.Value;
            }
        }

        /// <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)
            {
                throw new ArgumentOutOfRangeException("specialType");
            }

            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);
        }

        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.
        private TypeSymbol lazyHostObjectTypeSymbol;

        internal TypeSymbol GetHostObjectTypeSymbol()
        {
            if (HostObjectType != null && (object)lazyHostObjectTypeSymbol == null)
            {
                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);
                }

                Interlocked.CompareExchange(ref lazyHostObjectTypeSymbol, symbol, null);
            }

            return lazyHostObjectTypeSymbol;
        }

        internal TypeSymbol GetSubmissionReturnType()
        {
            if (IsSubmission && (object)ScriptClass != null)
            {
                // the second parameter of Script class instance constructor is the submission return value:
                return ((MethodSymbol)ScriptClass.GetMembers(WellKnownMemberNames.InstanceConstructorName)[0]).Parameters[1].Type;
            }
            else
            {
                return null;
            }
        }

        /// <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)
        {
1336
            return this.Assembly.GetTypeByMetadataName(fullyQualifiedMetadataName, includeReferences: true, isWellKnownType: false);
P
Pilchie 已提交
1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 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 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 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 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 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 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736
        }

        /// <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);
            return entryPoint == null ? null : entryPoint.MethodSymbol;
        }

        internal EntryPoint GetEntryPointAndDiagnostics(CancellationToken cancellationToken)
        {
            if (!this.Options.OutputKind.IsApplication())
            {
                return null;
            }

            Debug.Assert(!this.IsSubmission);

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

            if (this.lazyEntryPoint == null)
            {
                MethodSymbol entryPoint;
                ImmutableArray<Diagnostic> diagnostics;
                FindEntryPoint(cancellationToken, out entryPoint, out diagnostics);

                Interlocked.CompareExchange(ref this.lazyEntryPoint, new EntryPoint(entryPoint, diagnostics), null);
            }

            return this.lazyEntryPoint;
        }

        private void FindEntryPoint(CancellationToken cancellationToken, out MethodSymbol entryPoint, out ImmutableArray<Diagnostic> sealedDiagnostics)
        {
            using (Logger.LogBlock(FunctionId.CSharp_Compilation_FindEntryPoint, message: this.AssemblyName, cancellationToken: cancellationToken))
            {
                DiagnosticBag diagnostics = DiagnosticBag.GetInstance();

                try
                {
                    entryPoint = null;

                    ArrayBuilder<MethodSymbol> entryPointCandidates;
                    NamedTypeSymbol mainType;

                    string mainTypeName = this.Options.MainTypeName;
                    NamespaceSymbol globalNamespace = this.SourceModule.GlobalNamespace;

                    if (mainTypeName != null)
                    {
                        // Global code is the entry point, ignore all other Mains.
                        // TODO: don't special case scripts (DevDiv #13119).
                        if ((object)this.ScriptClass != null)
                        {
                            // CONSIDER: we could use the symbol instead of just the name.
                            diagnostics.Add(ErrorCode.WRN_MainIgnored, NoLocation.Singleton, mainTypeName);
                            return;
                        }

                        var mainTypeOrNamespace = globalNamespace.GetNamespaceOrTypeByQualifiedName(mainTypeName.Split('.')).OfMinimalArity();
                        if ((object)mainTypeOrNamespace == null)
                        {
                            diagnostics.Add(ErrorCode.ERR_MainClassNotFound, NoLocation.Singleton, mainTypeName);
                            return;
                        }

                        mainType = mainTypeOrNamespace as NamedTypeSymbol;
                        if ((object)mainType == null || mainType.IsGenericType || (mainType.TypeKind != TypeKind.Class && mainType.TypeKind != TypeKind.Struct))
                        {
                            diagnostics.Add(ErrorCode.ERR_MainClassNotClass, mainTypeOrNamespace.Locations.First(), mainTypeOrNamespace);
                            return;
                        }

                        entryPointCandidates = ArrayBuilder<MethodSymbol>.GetInstance();
                        EntryPointCandidateFinder.FindCandidatesInSingleType(mainType, entryPointCandidates, cancellationToken);

                        // NOTE: Any return after this point must free entryPointCandidates.
                    }
                    else
                    {
                        mainType = null;

                        entryPointCandidates = ArrayBuilder<MethodSymbol>.GetInstance();
                        EntryPointCandidateFinder.FindCandidatesInNamespace(globalNamespace, entryPointCandidates, cancellationToken);

                        // NOTE: Any return after this point must free entryPointCandidates.

                        // global code is the entry point, ignore all other Mains:
                        if ((object)this.ScriptClass != null)
                        {
                            foreach (var main in entryPointCandidates)
                            {
                                diagnostics.Add(ErrorCode.WRN_MainIgnored, main.Locations.First(), main);
                            }

                            entryPointCandidates.Free();
                            return;
                        }
                    }

                    DiagnosticBag warnings = DiagnosticBag.GetInstance();
                    var viableEntryPoints = ArrayBuilder<MethodSymbol>.GetInstance();
                    foreach (var candidate in entryPointCandidates)
                    {
                        if (!candidate.HasEntryPointSignature())
                        {
                            // a single error for partial methods:
                            warnings.Add(ErrorCode.WRN_InvalidMainSig, candidate.Locations.First(), candidate);
                            continue;
                        }

                        if (candidate.IsGenericMethod || candidate.ContainingType.IsGenericType)
                        {
                            // a single error for partial methods:
                            warnings.Add(ErrorCode.WRN_MainCantBeGeneric, candidate.Locations.First(), candidate);
                            continue;
                        }

                        if (candidate.IsAsync)
                        {
                            diagnostics.Add(ErrorCode.ERR_MainCantBeAsync, candidate.Locations.First(), candidate);
                        }

                        viableEntryPoints.Add(candidate);
                    }

                    if ((object)mainType == null || viableEntryPoints.Count == 0)
                    {
                        diagnostics.AddRange(warnings);
                    }

                    warnings.Free();

                    if (viableEntryPoints.Count == 0)
                    {
                        if ((object)mainType == null)
                        {
                            diagnostics.Add(ErrorCode.ERR_NoEntryPoint, NoLocation.Singleton);
                        }
                        else
                        {
                            diagnostics.Add(ErrorCode.ERR_NoMainInClass, mainType.Locations.First(), mainType);
                        }

                    }
                    else if (viableEntryPoints.Count > 1)
                    {
                        viableEntryPoints.Sort(LexicalOrderSymbolComparer.Instance);
                        var info = new CSDiagnosticInfo(
                             ErrorCode.ERR_MultipleEntryPoints,
                             args: SpecializedCollections.EmptyArray<object>(),
                             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
                    {
                        entryPoint = viableEntryPoints[0];
                    }

                    viableEntryPoints.Free();
                    entryPointCandidates.Free();
                }
                finally
                {
                    sealedDiagnostics = diagnostics.ToReadOnlyAndFree();
                }
            }
        }

        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)
        {
            using (Logger.LogBlock(FunctionId.CSharp_Compilation_ClassifyConversion, message: this.AssemblyName))
            {
                // 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.

                if ((object)source == null)
                {
                    throw new ArgumentNullException("source");
                }

                if ((object)destination == null)
                {
                    throw new ArgumentNullException("destination");
                }

                var cssource = source.EnsureCSharpSymbolOrNull<ITypeSymbol, TypeSymbol>("source");
                var csdest = destination.EnsureCSharpSymbolOrNull<ITypeSymbol, TypeSymbol>("destination");

                HashSet<DiagnosticInfo> useSiteDiagnostics = null;
                return Conversions.ClassifyConversion(cssource, csdest, ref useSiteDiagnostics);
            }
        }

        /// <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)
            {
                throw new ArgumentNullException("elementType");
            }

            return new ArrayTypeSymbol(this.Assembly, elementType, ImmutableArray<CustomModifier>.Empty, rank);
        }

        /// <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)
            {
                throw new ArgumentNullException("elementType");
            }

            return new PointerTypeSymbol(elementType);
        }

        #endregion

        #region Binding

        /// <summary>
        /// Gets a new SyntaxTreeSemanticModel for the specified syntax tree.
        /// </summary>
        public new SemanticModel GetSemanticModel(SyntaxTree syntaxTree)
        {
            if (syntaxTree == null)
            {
                throw new ArgumentNullException("tree");
            }

            if (!this.SyntaxTrees.Contains((SyntaxTree)syntaxTree))
            {
                throw new ArgumentException("tree");
            }

            return new SyntaxTreeSemanticModel(this, (SyntaxTree)syntaxTree);
        }

        // 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.
        private WeakReference<BinderFactory>[] binderFactories;

        internal BinderFactory GetBinderFactory(SyntaxTree syntaxTree)
        {
            var treeNum = GetSyntaxTreeOrdinal(syntaxTree);
            var binderFactories = this.binderFactories;
            if (binderFactories == null)
            {
                binderFactories = new WeakReference<BinderFactory>[this.syntaxTrees.Length];
                binderFactories = Interlocked.CompareExchange(ref this.binderFactories, binderFactories, null) ?? binderFactories;
            }

            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(SyntaxReference reference)
        {
            return GetBinderFactory(reference.SyntaxTree).GetBinder((CSharpSyntaxNode)reference.GetSyntax());
        }

        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)
        {
            return GetBinderFactory(declaration.SyntaxReference.SyntaxTree).GetImportsBinder((CSharpSyntaxNode)declaration.SyntaxReference.GetSyntax()).GetImports();
        }

        internal Imports GetSubmissionImports()
        {
            return ((SourceNamespaceSymbol)SourceModule.GlobalNamespace).GetBoundImportsMerged().SingleOrDefault() ?? Imports.Empty;
        }

        internal InteractiveUsingsBinder GetInteractiveUsingsBinder()
        {
            Debug.Assert(IsSubmission);

            // empty compilation:
            if ((object)ScriptClass == null)
            {
                Debug.Assert(SyntaxTrees.Length == 0);
                return null;
            }

            return GetBinderFactory(SyntaxTrees.Single()).GetInteractiveUsingsBinder();
        }

        private Imports BindGlobalUsings()
        {
            return Imports.FromGlobalUsings(this);
        }

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

1737
        void CompleteTree(SyntaxTree tree)
P
Pilchie 已提交
1738
        {
1739 1740
            bool completedCompilationUnit = false;
            bool completedCompilation = false;
P
Pilchie 已提交
1741

1742 1743
            if (lazyCompilationUnitCompletedTrees == null) Interlocked.CompareExchange(ref lazyCompilationUnitCompletedTrees, new HashSet<SyntaxTree>(), null);
            lock (lazyCompilationUnitCompletedTrees)
P
Pilchie 已提交
1744
            {
1745 1746 1747 1748 1749 1750 1751 1752 1753
                if (lazyCompilationUnitCompletedTrees.Add(tree))
                {
                    completedCompilationUnit = true;
                    if (lazyCompilationUnitCompletedTrees.Count == SyntaxTrees.Length)
                    {
                        completedCompilation = true;
                    }
                }
            }
P
Pilchie 已提交
1754

1755 1756
            if (completedCompilationUnit)
            {
1757
                EventQueue.Enqueue(new CompilationUnitCompletedEvent(this, tree));
1758 1759 1760 1761
            }

            if (completedCompilation)
            {
1762
                EventQueue.Enqueue(new CompilationCompletedEvent(this));
1763 1764 1765 1766 1767 1768 1769 1770 1771
                EventQueue.Complete(); // signal the end of compilation events
            }
        }

        internal void ReportUnusedImports(DiagnosticBag diagnostics, CancellationToken cancellationToken, SyntaxTree filterTree = null)
        {
            if (this.lazyImportInfos != null)
            {
                foreach (ImportInfo info in this.lazyImportInfos)
P
Pilchie 已提交
1772
                {
1773 1774 1775 1776
                    cancellationToken.ThrowIfCancellationRequested();

                    SyntaxTree infoTree = info.Tree;
                    if (filterTree == null || filterTree == infoTree)
P
Pilchie 已提交
1777
                    {
1778 1779 1780 1781
                        TextSpan infoSpan = info.Span;
                        if (!this.IsImportDirectiveUsed(infoTree, infoSpan.Start))
                        {
                            ErrorCode code = info.Kind == SyntaxKind.ExternAliasDirective
1782 1783
                                ? ErrorCode.HDN_UnusedExternAlias
                                : ErrorCode.HDN_UnusedUsingDirective;
1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803
                            diagnostics.Add(code, infoTree.GetLocation(infoSpan));
                        }
                    }
                }
            }

            // 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
                {
                    foreach (var tree in SyntaxTrees)
                    {
                        CompleteTree(tree);
P
Pilchie 已提交
1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821
                    }
                }
            }
        }

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

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

        private void RecordImportInternal(CSharpSyntaxNode syntax)
        {
            LazyInitializer.EnsureInitialized(ref this.lazyImportInfos).
1822
                Add(new ImportInfo(syntax.SyntaxTree, syntax.Kind(), syntax.Span));
P
Pilchie 已提交
1823 1824
        }

1825
        private struct ImportInfo : IEquatable<ImportInfo>
P
Pilchie 已提交
1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839
        {
            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)
            {
1840 1841
                return (obj is ImportInfo) && Equals((ImportInfo)obj);
            }
1842

1843 1844 1845 1846 1847 1848
            public bool Equals(ImportInfo other)
            {
                return
                    other.Kind == this.Kind &&
                    other.Tree == this.Tree &&
                    other.Span == this.Span;
P
Pilchie 已提交
1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952
            }

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

        #endregion

        #region Diagnostics

        internal override CommonMessageProvider MessageProvider
        {
            get { return CSharp.MessageProvider.Instance; }
        }

        /// <summary>
        /// The bag in which semantic analysis should deposit its diagnostics.
        /// </summary>
        internal DiagnosticBag SemanticDiagnostics
        {
            get
            {
                if (this.lazySemanticDiagnostics == null)
                {
                    var diagnostics = new DiagnosticBag();
                    Interlocked.CompareExchange(ref this.lazySemanticDiagnostics, diagnostics, null);
                }

                return this.lazySemanticDiagnostics;
            }
        }

        private DiagnosticBag lazySemanticDiagnostics;

        /// <summary>
        /// A bag in which diagnostics that should be reported after code gen can be deposited.
        /// </summary>
        internal DiagnosticBag AdditionalCodegenWarnings
        {
            get
            {
                return this.additionalCodegenWarnings;
            }
        }

        private DiagnosticBag additionalCodegenWarnings = new DiagnosticBag();

        internal DeclarationTable Declarations
        {
            get
            {
                return this.declarationTable;
            }
        }

        /// <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))
        {
            return GetDiagnostics(CompilationStage.Parse, false, cancellationToken);
        }

        /// <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))
        {
            return GetDiagnostics(CompilationStage.Declare, false, cancellationToken);
        }

        /// <summary>
        /// Gets the diagnostics produced during the analysis of method bodies and field initializers.
        /// </summary>
        public override ImmutableArray<Diagnostic> GetMethodBodyDiagnostics(CancellationToken cancellationToken = default(CancellationToken))
        {
            return GetDiagnostics(CompilationStage.Compile, false, cancellationToken);
        }

        /// <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))
        {
            return GetDiagnostics(DefaultDiagnosticsStage, true, cancellationToken);
        }

        internal ImmutableArray<Diagnostic> GetDiagnostics(CompilationStage stage, bool includeEarlierStages, CancellationToken cancellationToken)
        {
            using (Logger.LogBlock(FunctionId.CSharp_Compilation_GetDiagnostics, message: this.AssemblyName, cancellationToken: cancellationToken))
            {
                var builder = DiagnosticBag.GetInstance();

                if (stage == CompilationStage.Parse || (stage > CompilationStage.Parse && includeEarlierStages))
                {
                    if (this.Options.ConcurrentBuild)
                    {
                        var parallelOptions = cancellationToken.CanBeCanceled
                                            ? new ParallelOptions() { CancellationToken = cancellationToken }
T
TomasMatousek 已提交
1953
                                            : DefaultParallelOptions;
P
Pilchie 已提交
1954 1955

                        Parallel.For(0, this.SyntaxTrees.Length, parallelOptions,
1956
                            UICultureUtilities.WithCurrentUICulture<int>(i => builder.AddRange(this.SyntaxTrees[i].GetDiagnostics(cancellationToken))));
P
Pilchie 已提交
1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
                    }
                    else
                    {
                        foreach (var syntaxTree in this.SyntaxTrees)
                        {
                            cancellationToken.ThrowIfCancellationRequested();
                            builder.AddRange(syntaxTree.GetDiagnostics(cancellationToken));
                        }
                    }
                }

                if (stage == CompilationStage.Declare || stage > CompilationStage.Declare && includeEarlierStages)
                {
                    builder.AddRange(Options.Errors);

                    cancellationToken.ThrowIfCancellationRequested();

                    // the set of diagnostics related to establishing references.
                    builder.AddRange(GetBoundReferenceManager().Diagnostics);

                    cancellationToken.ThrowIfCancellationRequested();

                    builder.AddRange(GetSourceDeclarationDiagnostics(cancellationToken: cancellationToken));
                }

                cancellationToken.ThrowIfCancellationRequested();

                if (stage == CompilationStage.Compile || stage > CompilationStage.Compile && includeEarlierStages)
                {
T
TomasMatousek 已提交
1986
                    var methodBodyDiagnostics = DiagnosticBag.GetInstance();
1987
                    GetDiagnosticsForAllMethodBodies(methodBodyDiagnostics, cancellationToken);
T
TomasMatousek 已提交
1988
                    builder.AddRangeAndFree(methodBodyDiagnostics);
P
Pilchie 已提交
1989 1990 1991 1992 1993 1994 1995 1996 1997 1998
                }

                // Before returning diagnostics, we filter warnings
                // to honor the compiler options (e.g., /nowarn, /warnaserror and /warn) and the pragmas.
                var result = DiagnosticBag.GetInstance();
                FilterAndAppendAndFreeDiagnostics(result, ref builder);
                return result.ToReadOnlyAndFree<Diagnostic>();
            }
        }

T
TomasMatousek 已提交
1999 2000
        // Do the steps in compilation to get the method body diagnostics, but don't actually generate
        // IL or emit an assembly.
2001
        private void GetDiagnosticsForAllMethodBodies(DiagnosticBag diagnostics, CancellationToken cancellationToken)
T
TomasMatousek 已提交
2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015
        {
            MethodCompiler.CompileMethodBodies(
                compilation: this,
                moduleBeingBuiltOpt: null,
                generateDebugInfo: false,
                hasDeclarationErrors: false,
                diagnostics: diagnostics,
                filterOpt: null,
                cancellationToken: cancellationToken);

            DocumentationCommentCompiler.WriteDocumentationCommentXml(this, null, null, diagnostics, cancellationToken);
            this.ReportUnusedImports(diagnostics, cancellationToken);
        }

2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031
        private static bool IsDefinedOrImplementedInSourceTree(Symbol symbol, SyntaxTree tree, TextSpan? span)
        {
            if (symbol.IsDefinedInSourceTree(tree, span))
            {
                return true;
            }

            if (symbol.IsPartialDefinition())
            {
                MethodSymbol implementationPart = ((MethodSymbol)symbol).PartialImplementationPart;
                if ((object)implementationPart != null)
                {
                    return implementationPart.IsDefinedInSourceTree(tree, span);
                }
            }

2032 2033 2034 2035 2036 2037
            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);
            }

2038 2039 2040
            return false;
        }

T
TomasMatousek 已提交
2041 2042 2043 2044 2045 2046 2047 2048 2049 2050
        private ImmutableArray<Diagnostic> GetDiagnosticsForMethodBodiesInTree(SyntaxTree tree, TextSpan? span, CancellationToken cancellationToken)
        {
            DiagnosticBag diagnostics = DiagnosticBag.GetInstance();

            MethodCompiler.CompileMethodBodies(
                compilation: this,
                moduleBeingBuiltOpt: null,
                generateDebugInfo: false,
                hasDeclarationErrors: false,
                diagnostics: diagnostics,
2051
                filterOpt: s => IsDefinedOrImplementedInSourceTree(s, tree, span),
T
TomasMatousek 已提交
2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065
                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)
            {
                ReportUnusedImports(diagnostics, cancellationToken, tree);
            }

            return diagnostics.ToReadOnlyAndFree();
        }

P
Pilchie 已提交
2066 2067 2068 2069 2070 2071 2072
        /// <summary>
        /// Filter out warnings based on the compiler options (/nowarn, /warn and /warnaserror) and the pragma warning directives.
        /// 'incoming' is freed.
        /// </summary>
        /// <returns>True when there is no error or warning treated as an error.</returns>
        internal override bool FilterAndAppendAndFreeDiagnostics(DiagnosticBag accumulator, ref DiagnosticBag incoming)
        {
2073
            bool result = FilterAndAppendDiagnostics(accumulator, incoming.AsEnumerableWithoutResolution());
P
Pilchie 已提交
2074 2075 2076 2077 2078
            incoming.Free();
            incoming = null;
            return result;
        }

2079 2080 2081 2082 2083 2084 2085
        internal override Diagnostic FilterDiagnostic(Diagnostic d)
        {
            return FilterDiagnostic(d, options);
        }

        private static Diagnostic FilterDiagnostic(Diagnostic d, CSharpCompilationOptions options)
        {
2086
            return CSharpDiagnosticFilter.Filter(d, options.WarningLevel, options.GeneralDiagnosticOption, options.SpecificDiagnosticOptions);
2087 2088
        }

P
Pilchie 已提交
2089 2090 2091
        /// <summary>
        /// Filter out warnings based on the compiler options (/nowarn, /warn and /warnaserror) and the pragma warning directives.
        /// </summary>
2092
        /// <returns>True when there is no error.</returns>
2093
        private bool FilterAndAppendDiagnostics(DiagnosticBag accumulator, IEnumerable<Diagnostic> incoming)
P
Pilchie 已提交
2094
        {
2095
            bool hasError = false;
P
Pilchie 已提交
2096 2097 2098

            foreach (Diagnostic d in incoming)
            {
2099
                var filtered = FilterDiagnostic(d, this.options);
2100
                if (filtered == null)
P
Pilchie 已提交
2101 2102 2103
                {
                    continue;
                }
2104
                else if (filtered.Severity == DiagnosticSeverity.Error)
P
Pilchie 已提交
2105
                {
2106
                    hasError = true;
P
Pilchie 已提交
2107
                }
2108

2109
                accumulator.Add(filtered);
P
Pilchie 已提交
2110 2111
            }

2112
            return !hasError;
P
Pilchie 已提交
2113 2114
        }

2115

P
Pilchie 已提交
2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212

        private ImmutableArray<Diagnostic> GetSourceDeclarationDiagnostics(SyntaxTree syntaxTree = null, TextSpan? filterSpanWithinTree = null, Func<IEnumerable<Diagnostic>, SyntaxTree, TextSpan?, IEnumerable<Diagnostic>> locationFilterOpt = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            // global imports diagnostics (specified via compilation options):
            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);

            var result = this.SemanticDiagnostics.AsEnumerable().Concat(
                ((SourceModuleSymbol)this.SourceModule).Diagnostics);

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

            if (this.lazyClsComplianceDiagnostics.IsDefault)
            {
                var builder = DiagnosticBag.GetInstance();
                ClsComplianceChecker.CheckCompliance(this, builder, cancellationToken);
                ImmutableInterlocked.InterlockedInitialize(ref this.lazyClsComplianceDiagnostics, builder.ToReadOnlyAndFree());
            }

            Debug.Assert(!this.lazyClsComplianceDiagnostics.IsDefault);
            return this.lazyClsComplianceDiagnostics;
        }

        private static IEnumerable<Diagnostic> FilterDiagnosticsByLocation(IEnumerable<Diagnostic> diagnostics, SyntaxTree tree, TextSpan? filterSpanWithinTree)
        {
            foreach (var diagnostic in diagnostics)
            {
                if (diagnostic.ContainsLocation(tree, filterSpanWithinTree))
                {
                    yield return diagnostic;
                }
            }
        }

        internal ImmutableArray<Diagnostic> GetDiagnosticsForSyntaxTree(
            CompilationStage stage,
            SyntaxTree syntaxTree,
            TextSpan? filterSpanWithinTree,
            bool includeEarlierStages,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            cancellationToken.ThrowIfCancellationRequested();

            var builder = DiagnosticBag.GetInstance();
            if (stage == CompilationStage.Parse || (stage > CompilationStage.Parse && includeEarlierStages))
            {
                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);
                Debug.Assert(declarationDiagnostics.All(d => d.ContainsLocation(syntaxTree, filterSpanWithinTree)));
                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
                //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. 
                //For that reason the bag must be also filtered by tree.
T
TomasMatousek 已提交
2213
                IEnumerable<Diagnostic> methodBodyDiagnostics = GetDiagnosticsForMethodBodiesInTree(syntaxTree, filterSpanWithinTree, cancellationToken);
P
Pilchie 已提交
2214 2215

                // TODO: Enable the below commented assert and remove the filtering code in the next line.
T
TomasMatousek 已提交
2216
                //       GetDiagnosticsForMethodBodiesInTree seems to be returning diagnostics with locations that don't satisfy the filter tree/span, this must be fixed.
P
Pilchie 已提交
2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274
                // 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();
            FilterAndAppendAndFreeDiagnostics(result, ref builder);
            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

        internal override bool IsDelaySign
        {
            get { return SourceAssembly.IsDelaySign; }
        }

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

        internal override FunctionId EmitFunctionId
        {
            get { return FunctionId.CSharp_Compilation_Emit; }
        }

        internal override CommonPEModuleBuilder CreateModuleBuilder(
2275
            EmitOptions emitOptions,
P
Pilchie 已提交
2276 2277 2278
            IEnumerable<ResourceDescription> manifestResources,
            Func<IAssemblySymbol, AssemblyIdentity> assemblySymbolMapper,
            CompilationTestData testData,
2279 2280
            DiagnosticBag diagnostics,
            CancellationToken cancellationToken)
P
Pilchie 已提交
2281 2282
        {
            return this.CreateModuleBuilder(
2283
                emitOptions,
P
Pilchie 已提交
2284 2285 2286
                manifestResources,
                assemblySymbolMapper,
                testData,
2287
                diagnostics,
2288 2289
                ImmutableArray<NamedTypeSymbol>.Empty,
                cancellationToken);
P
Pilchie 已提交
2290 2291 2292
        }

        internal CommonPEModuleBuilder CreateModuleBuilder(
2293
            EmitOptions emitOptions,
P
Pilchie 已提交
2294 2295 2296
            IEnumerable<ResourceDescription> manifestResources,
            Func<IAssemblySymbol, AssemblyIdentity> assemblySymbolMapper,
            CompilationTestData testData,
2297
            DiagnosticBag diagnostics,
2298 2299
            ImmutableArray<NamedTypeSymbol> additionalTypes,
            CancellationToken cancellationToken)
P
Pilchie 已提交
2300 2301 2302 2303 2304 2305 2306 2307
        {
            // Do not waste a slot in the submission chain for submissions that contain no executable code
            // (they may only contain #r directives, usings, etc.)
            if (IsSubmission && !HasCodeToEmit())
            {
                return null;
            }

2308
            string runtimeMDVersion = GetRuntimeMetadataVersion(emitOptions, diagnostics);
P
Pilchie 已提交
2309 2310
            if (runtimeMDVersion == null)
            {
2311
                return null;
P
Pilchie 已提交
2312 2313
            }

2314
            var moduleProps = ConstructModuleSerializationProperties(emitOptions, runtimeMDVersion);
P
Pilchie 已提交
2315 2316 2317 2318 2319 2320 2321

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

            PEModuleBuilder moduleBeingBuilt;
2322
            if (this.options.OutputKind.IsNetModule())
P
Pilchie 已提交
2323 2324 2325 2326 2327
            {
                Debug.Assert(additionalTypes.IsEmpty);

                moduleBeingBuilt = new PENetModuleBuilder(
                    (SourceModuleSymbol)SourceModule,
2328
                    emitOptions,
P
Pilchie 已提交
2329
                    moduleProps,
2330
                    manifestResources);
P
Pilchie 已提交
2331 2332 2333
            }
            else
            {
2334
                var kind = this.options.OutputKind.IsValid() ? this.options.OutputKind : OutputKind.DynamicallyLinkedLibrary;
2335 2336
                moduleBeingBuilt = new PEAssemblyBuilder(
                    SourceAssembly,
2337
                    emitOptions,
2338 2339 2340 2341
                    kind,
                    moduleProps,
                    manifestResources,
                    assemblySymbolMapper,
2342
                    additionalTypes);
P
Pilchie 已提交
2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354
            }

            // testData is only passed when running tests.
            if (testData != null)
            {
                moduleBeingBuilt.SetMethodTestData(testData.Methods);
                testData.Module = moduleBeingBuilt;
            }

            return moduleBeingBuilt;
        }

2355
        internal override bool CompileImpl(
P
Pilchie 已提交
2356 2357 2358 2359
            CommonPEModuleBuilder moduleBuilder,
            Stream win32Resources,
            Stream xmlDocStream,
            bool generateDebugInfo,
2360
            DiagnosticBag diagnostics,
2361 2362
            Predicate<ISymbol> filterOpt,
            CancellationToken cancellationToken)
P
Pilchie 已提交
2363
        {
2364 2365 2366 2367
            // 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...)
            bool hasDeclarationErrors = !FilterAndAppendDiagnostics(diagnostics, GetDiagnostics(CompilationStage.Declare, true, cancellationToken));

P
Pilchie 已提交
2368 2369 2370 2371 2372
            // TODO (tomat): NoPIA:
            // EmbeddedSymbolManager.MarkAllDeferredSymbolsAsReferenced(this)

            var moduleBeingBuilt = (PEModuleBuilder)moduleBuilder;

2373
            if (moduleBeingBuilt.EmitOptions.EmitMetadataOnly)
P
Pilchie 已提交
2374 2375 2376 2377 2378 2379
            {
                if (hasDeclarationErrors)
                {
                    return false;
                }

T
TomasMatousek 已提交
2380
                SynthesizedMetadataCompiler.ProcessSynthesizedMembers(this, moduleBeingBuilt, cancellationToken);
P
Pilchie 已提交
2381 2382 2383 2384 2385
            }
            else
            {
                if (generateDebugInfo && moduleBeingBuilt != null)
                {
2386
                    if (!StartSourceChecksumCalculation(moduleBeingBuilt, diagnostics))
P
Pilchie 已提交
2387
                    {
2388
                        return false;
P
Pilchie 已提交
2389 2390 2391
                    }
                }

2392
                // Perform initial bind of method bodies in spite of earlier errors. This is the same
P
Pilchie 已提交
2393 2394 2395 2396 2397
                // 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 已提交
2398
                MethodCompiler.CompileMethodBodies(
P
Pilchie 已提交
2399 2400 2401 2402 2403
                    this,
                    moduleBeingBuilt,
                    generateDebugInfo,
                    hasDeclarationErrors,
                    diagnostics: methodBodyDiagnosticBag,
2404
                    filterOpt: filterOpt,
P
Pilchie 已提交
2405
                    cancellationToken: cancellationToken);
T
TomasMatousek 已提交
2406

P
Pilchie 已提交
2407 2408 2409
                SetupWin32Resources(moduleBeingBuilt, win32Resources, methodBodyDiagnosticBag);

                ReportManifestResourceDuplicates(
2410
                    moduleBeingBuilt.ManifestResources,
P
Pilchie 已提交
2411 2412 2413 2414
                    SourceAssembly.Modules.Skip(1).Select((m) => m.Name),   //all modules except the first one
                    AddedModulesResourceNames(methodBodyDiagnosticBag),
                    methodBodyDiagnosticBag);

2415
                bool hasMethodBodyErrorOrWarningAsError = !FilterAndAppendAndFreeDiagnostics(diagnostics, ref methodBodyDiagnosticBag);
P
Pilchie 已提交
2416 2417 2418 2419 2420 2421 2422 2423

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

            cancellationToken.ThrowIfCancellationRequested();
2424

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

2428
            string assemblyName = FileNameUtilities.ChangeExtension(moduleBeingBuilt.EmitOptions.OutputNameOverride, extension: null);
2429
            DocumentationCommentCompiler.WriteDocumentationCommentXml(this, assemblyName, xmlDocStream, xmlDiagnostics, cancellationToken);
P
Pilchie 已提交
2430

2431
            if (!FilterAndAppendAndFreeDiagnostics(diagnostics, ref xmlDiagnostics))
P
Pilchie 已提交
2432 2433 2434 2435 2436 2437 2438 2439
            {
                return false;
            }

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

2440
            if (!FilterAndAppendAndFreeDiagnostics(diagnostics, ref importDiagnostics))
P
Pilchie 已提交
2441 2442 2443 2444 2445 2446 2447 2448
            {
                Debug.Assert(false, "Should never produce an error");
                return false;
            }

            return true;
        }

2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494
        // TODO: consider unifying with VB
        private bool StartSourceChecksumCalculation(PEModuleBuilder moduleBeingBuilt, DiagnosticBag diagnostics)
        {
            // Check that all syntax trees are debuggable:
            bool allTreesDebuggable = true;
            foreach (var tree in this.syntaxTrees)
            {
                if (!string.IsNullOrEmpty(tree.FilePath) && tree.GetText().Encoding == null)
                {
                    diagnostics.Add(ErrorCode.ERR_EncodinglessSyntaxTree, tree.GetRoot().GetLocation());
                    allTreesDebuggable = false;
                }
            }

            if (!allTreesDebuggable)
            {
                return false;
            }

            // Add debug documents for all trees with distinct paths.
            foreach (var tree in this.syntaxTrees)
            {
                if (!string.IsNullOrEmpty(tree.FilePath))
                {
                    // compilation does not guarantee that all trees will have distinct paths.
                    // Do not attempt adding a document for a particular path if we already added one.
                    string normalizedPath = moduleBeingBuilt.NormalizeDebugDocumentPath(tree.FilePath, basePath: null);
                    var existingDoc = moduleBeingBuilt.TryGetDebugDocumentForNormalizedPath(normalizedPath);
                    if (existingDoc == null)
                    {
                        moduleBeingBuilt.AddDebugDocument(MakeDebugSourceDocumentForTree(normalizedPath, tree));
                    }
                }
            }

            // Add debug documents for all pragmas. 
            // If there are clashes with already processed directives, report warnings.
            // If there are clashes with debug documents that came from actual trees, ignore the pragma.
            foreach (var tree in this.syntaxTrees)
            {
                AddDebugSourceDocumentsForChecksumDirectives(moduleBeingBuilt, tree, diagnostics);
            }

            return true;
        }

P
Pilchie 已提交
2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520
        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;
                }
            }
        }

2521 2522 2523
        internal override EmitDifferenceResult EmitDifference(
            EmitBaseline baseline,
            IEnumerable<SemanticEdit> edits,
2524
            Func<ISymbol, bool> isAddedSymbol,
2525 2526 2527
            Stream metadataStream,
            Stream ilStream,
            Stream pdbStream,
A
angocke 已提交
2528
            ICollection<MethodDefinitionHandle> updatedMethods,
2529 2530
            CompilationTestData testData,
            CancellationToken cancellationToken)
P
Pilchie 已提交
2531
        {
2532 2533 2534 2535
            return EmitHelpers.EmitDifference(
                this,
                baseline,
                edits,
2536
                isAddedSymbol,
2537 2538 2539
                metadataStream,
                ilStream,
                pdbStream,
2540
                updatedMethods,
2541 2542 2543
                testData,
                cancellationToken);
        }
P
Pilchie 已提交
2544

2545
        internal string GetRuntimeMetadataVersion(EmitOptions emitOptions, DiagnosticBag diagnostics)
2546
        {
2547
            string runtimeMDVersion = GetRuntimeMetadataVersion(emitOptions);
2548
            if (runtimeMDVersion != null)
P
Pilchie 已提交
2549
            {
2550
                return runtimeMDVersion;
P
Pilchie 已提交
2551 2552
            }

2553 2554 2555
            DiagnosticBag runtimeMDVersionDiagnostics = DiagnosticBag.GetInstance();
            runtimeMDVersionDiagnostics.Add(ErrorCode.WRN_NoRuntimeMetadataVersion, NoLocation.Singleton);
            if (!FilterAndAppendAndFreeDiagnostics(diagnostics, ref runtimeMDVersionDiagnostics))
P
Pilchie 已提交
2556
            {
2557
                return null;
P
Pilchie 已提交
2558 2559
            }

2560
            return string.Empty; //prevent emitter from crashing.
P
Pilchie 已提交
2561 2562
        }

2563
        private string GetRuntimeMetadataVersion(EmitOptions emitOptions)
P
Pilchie 已提交
2564 2565 2566 2567 2568 2569 2570 2571
        {
            var corAssembly = Assembly.CorLibrary as Symbols.Metadata.PE.PEAssemblySymbol;

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

2572
            return emitOptions.RuntimeMetadataVersion;
P
Pilchie 已提交
2573 2574 2575
        }

        private static void AddDebugSourceDocumentsForChecksumDirectives(
2576 2577
            PEModuleBuilder moduleBeingBuilt,
            SyntaxTree tree,
2578
            DiagnosticBag diagnostics)
P
Pilchie 已提交
2579
        {
2580
            var checksumDirectives = tree.GetRoot().GetDirectives(d => d.Kind() == SyntaxKind.PragmaChecksumDirectiveTrivia &&
P
Pilchie 已提交
2581 2582 2583 2584
                                                                 !d.ContainsDiagnostics);

            foreach (var directive in checksumDirectives)
            {
2585 2586
                var checksumDirective = (PragmaChecksumDirectiveTriviaSyntax)directive;
                var path = checksumDirective.File.ValueText;
P
Pilchie 已提交
2587

2588
                var checksumText = checksumDirective.Bytes.ValueText;
P
Pilchie 已提交
2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602
                var normalizedPath = moduleBeingBuilt.NormalizeDebugDocumentPath(path, basePath: tree.FilePath);
                var existingDoc = moduleBeingBuilt.TryGetDebugDocumentForNormalizedPath(normalizedPath);

                // 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;
2603
                    }
P
Pilchie 已提交
2604

2605 2606
                    var checksumAndAlgorithm = existingDoc.ChecksumAndAlgorithm;
                    if (ChecksumMatches(checksumText, checksumAndAlgorithm.Item1))
P
Pilchie 已提交
2607
                    {
2608 2609
                        var guid = Guid.Parse(checksumDirective.Guid.ValueText);
                        if (guid == checksumAndAlgorithm.Item2)
P
Pilchie 已提交
2610 2611 2612 2613 2614 2615 2616 2617
                        {
                            // all parts match, nothing to do
                            continue;
                        }
                    }

                    // did not match to an existing document
                    // produce a warning and ignore the pragma
2618
                    diagnostics.Add(ErrorCode.WRN_ConflictingChecksum, new SourceLocation(checksumDirective), path);
P
Pilchie 已提交
2619 2620 2621 2622 2623 2624
                }
                else
                {
                    var newDocument = new Cci.DebugSourceDocument(
                        normalizedPath,
                        Cci.DebugSourceDocument.CorSymLanguageTypeCSharp,
2625 2626
                        MakeChecksumBytes(checksumDirective.Bytes.ValueText),
                        Guid.Parse(checksumDirective.Guid.ValueText));
P
Pilchie 已提交
2627 2628 2629 2630 2631 2632

                    moduleBeingBuilt.AddDebugDocument(newDocument);
                }
            }
        }

2633
        private static bool ChecksumMatches(string bytesText, ImmutableArray<byte> bytes)
P
Pilchie 已提交
2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654
        {
            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;
        }

2655
        private static ImmutableArray<byte> MakeChecksumBytes(string bytesText)
P
Pilchie 已提交
2656
        {
2657 2658
            int length = bytesText.Length / 2;
            var builder = ArrayBuilder<byte>.GetInstance(length);
P
Pilchie 已提交
2659

2660
            for (int i = 0; i < length; i++)
P
Pilchie 已提交
2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673
            {
                // 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();
        }

        private static Cci.DebugSourceDocument MakeDebugSourceDocumentForTree(string normalizedPath, SyntaxTree tree)
        {
2674
            return new Cci.DebugSourceDocument(normalizedPath, Cci.DebugSourceDocument.CorSymLanguageTypeCSharp, () => tree.GetChecksumAndAlgorithm());
P
Pilchie 已提交
2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 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 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 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 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905
        }

        private void SetupWin32Resources(PEModuleBuilder moduleBeingBuilt, Stream win32Resources, DiagnosticBag diagnostics)
        {
            if (win32Resources == null)
                return;

            switch (DetectWin32ResourceForm(win32Resources))
            {
                case Win32ResourceForm.COFF:
                    moduleBeingBuilt.Win32ResourceSection = MakeWin32ResourcesFromCOFF(win32Resources, diagnostics);
                    break;
                case Win32ResourceForm.RES:
                    moduleBeingBuilt.Win32Resources = MakeWin32ResourceList(win32Resources, diagnostics);
                    break;
                default:
                    diagnostics.Add(ErrorCode.ERR_BadWin32Res, NoLocation.Singleton, "Unrecognized file format.");
                    break;
            }
        }

        protected override bool HasCodeToEmit()
        {
            foreach (var syntaxTree in SyntaxTrees)
            {
                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 ITypeSymbol CommonGetSubmissionResultType(out bool hasValue)
        {
            return GetSubmissionResultType(out hasValue);
        }

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

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

        protected override CompilationOptions CommonOptions
        {
            get { return options; }
        }

        protected override Compilation CommonPreviousSubmission
        {
            get { return previousSubmission; }
        }

        protected override SemanticModel CommonGetSemanticModel(SyntaxTree syntaxTree)
        {
            return this.GetSemanticModel((SyntaxTree)syntaxTree);
        }

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

        protected override Compilation CommonAddSyntaxTrees(IEnumerable<SyntaxTree> trees)
        {
            var array = trees as SyntaxTree[];
            if (array != null)
            {
                return this.AddSyntaxTrees(array);
            }

            if (trees == null)
            {
                throw new ArgumentNullException("trees");
            }

            return this.AddSyntaxTrees(trees.Cast<SyntaxTree>());
        }

        protected override Compilation CommonRemoveSyntaxTrees(IEnumerable<SyntaxTree> trees)
        {
            var array = trees as SyntaxTree[];
            if (array != null)
            {
                return this.RemoveSyntaxTrees(array);
            }

            if (trees == null)
            {
                throw new ArgumentNullException("trees");
            }

            return this.RemoveSyntaxTrees(trees.Cast<SyntaxTree>());
        }

        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);
        }

        protected override Compilation CommonWithPreviousSubmission(Compilation newPreviousSubmission)
        {
            return this.WithPreviousSubmission((CSharpCompilation)newPreviousSubmission);
        }

        protected override bool CommonContainsSyntaxTree(SyntaxTree syntaxTree)
        {
            return this.ContainsSyntaxTree((SyntaxTree)syntaxTree);
        }

        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);
        }

        protected override INamedTypeSymbol CommonScriptClass
        {
            get { return this.ScriptClass; }
        }

        protected override IArrayTypeSymbol CommonCreateArrayTypeSymbol(ITypeSymbol elementType, int rank)
        {
            return CreateArrayTypeSymbol(elementType.EnsureCSharpSymbolOrNull<ITypeSymbol, TypeSymbol>("elementType"), rank);
        }

        protected override IPointerTypeSymbol CommonCreatePointerTypeSymbol(ITypeSymbol elementType)
        {
            return CreatePointerTypeSymbol(elementType.EnsureCSharpSymbolOrNull<ITypeSymbol, TypeSymbol>("elementType"));
        }

        protected override ITypeSymbol CommonDynamicType
        {
            get { return DynamicType; }
        }

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

        protected override MetadataReference CommonGetMetadataReference(IAssemblySymbol assemblySymbol)
        {
            var symbol = assemblySymbol as AssemblySymbol;
            if ((object)symbol != null)
            {
                return this.GetMetadataReference(symbol);
            }
            else
            {
                return null;
            }
        }

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

H
heejaechang 已提交
2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941
        /// <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));
            }

            return this.declarationTable.ContainsName(predicate, filter, cancellationToken);
        }

        /// <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 已提交
2942
        #endregion
2943

2944
        internal override AnalyzerDriver AnalyzerForLanguage(ImmutableArray<DiagnosticAnalyzer> analyzers, AnalyzerOptions options, Func<Exception, DiagnosticAnalyzer, bool> continueOnAnalyzerException, CancellationToken cancellationToken)
2945
        {
2946
            return new AnalyzerDriver<SyntaxKind>(analyzers, n => n.Kind(), options, continueOnAnalyzerException, cancellationToken);
2947 2948
        }

2949 2950
        internal void SymbolDeclaredEvent(Symbol symbol)
        {
2951
            if (EventQueue != null) EventQueue.Enqueue(new SymbolDeclaredCompilationEvent(this, symbol));
2952
        }
2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970

        /// <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;
            }
        }
H
heejaechang 已提交
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 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048

        private class SymbolSearcher
        {
            private readonly Dictionary<Declaration, NamespaceOrTypeSymbol> cache;
            private readonly CSharpCompilation compilation;

            public SymbolSearcher(CSharpCompilation compilation)
            {
                this.cache = new Dictionary<Declaration, NamespaceOrTypeSymbol>();
                this.compilation = compilation;
            }

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

                AppendSymbolsWithName(spine, this.compilation.declarationTable.MergedRoot, predicate, filter, result, cancellationToken);

                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);
                        set.Add(GetSymbol(container, current));
                    }
                }
                else
                {
                    if (includeType && predicate(current.Name))
                    {
                        var container = GetSpineSymbol(spine);
                        set.Add(GetSymbol(container, current));
                    }

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

3049 3050
                var container = GetSpineSymbol(spine);
                foreach (var member in container.GetMembers())
H
heejaechang 已提交
3051
                {
3052 3053 3054
                    if (!member.IsTypeOrTypeAlias() &&
                        (member.CanBeReferencedByName || member.IsExplicitInterfaceImplementation() || member.IsIndexer()) &&
                        predicate(member.Name))
H
heejaechang 已提交
3055
                    {
3056
                        set.Add(member);
H
heejaechang 已提交
3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140
                    }
                }

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

                var current = this.compilation.GlobalNamespace as NamespaceOrTypeSymbol;
                for (var i = 1; i < spine.Count; i++)
                {
                    current = GetSymbol(current, spine[i]);
                }

                return current;
            }

            private NamespaceOrTypeSymbol GetCachedSymbol(MergedNamespaceOrTypeDeclaration declaration)
            {
                NamespaceOrTypeSymbol symbol;
                if (this.cache.TryGetValue(declaration, out symbol))
                {
                    return symbol;
                }

                return null;
            }

            private NamespaceOrTypeSymbol GetSymbol(NamespaceOrTypeSymbol container, MergedNamespaceOrTypeDeclaration declaration)
            {
                if (container == null)
                {
                    return this.compilation.GlobalNamespace;
                }

                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)
                    {
                        this.cache[mergedNamespace.ConstituentNamespaces.OfType<SourceNamespaceSymbol>().First().MergedDeclaration] = symbol;
                        continue;
                    }

                    var sourceNamespace = symbol as SourceNamespaceSymbol;
                    if (sourceNamespace != null)
                    {
                        this.cache[sourceNamespace.MergedDeclaration] = sourceNamespace;
                        continue;
                    }

                    var sourceType = symbol as SourceMemberContainerTypeSymbol;
                    if (sourceType != null)
                    {
                        this.cache[sourceType.MergedDeclaration] = sourceType;
                    }
                }
            }
        }
P
Pilchie 已提交
3141 3142
    }
}