Compilation.cs 134.8 KB
Newer Older
T
Tomas Matousek 已提交
1 2 3 4 5 6
// Copyright (c) Microsoft.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.Immutable;
7
using System.ComponentModel;
T
Tomas Matousek 已提交
8
using System.Diagnostics;
9
using System.Diagnostics.Contracts;
T
Tomas Matousek 已提交
10 11 12 13
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Metadata;
T
Tomas Matousek 已提交
14
using System.Reflection.Metadata.Ecma335;
15
using System.Reflection.PortableExecutable;
16
using System.Security.Cryptography;
T
Tomas Matousek 已提交
17 18 19 20 21 22
using System.Text;
using System.Threading;
using Microsoft.CodeAnalysis.CodeGen;
using Microsoft.CodeAnalysis.Collections;
using Microsoft.CodeAnalysis.Diagnostics;
using Microsoft.CodeAnalysis.Emit;
23
using Microsoft.CodeAnalysis.Operations;
T
Tomas Matousek 已提交
24
using Microsoft.CodeAnalysis.PooledObjects;
T
Tomas Matousek 已提交
25
using Microsoft.CodeAnalysis.Symbols;
26
using Microsoft.DiaSymReader;
T
Tomas Matousek 已提交
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis
{
    /// <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 abstract partial class Compilation
    {
        /// <summary>
        /// Returns true if this is a case sensitive compilation, false otherwise.  Case sensitivity
        /// affects compilation features such as name lookup as well as choosing what names to emit
        /// when there are multiple different choices (for example between a virtual method and an
        /// override).
        /// </summary>
        public abstract bool IsCaseSensitive { get; }

        /// <summary>
        /// Used for test purposes only to emulate missing members.
        /// </summary>
        private SmallDictionary<int, bool> _lazyMakeWellKnownTypeMissingMap;

        /// <summary>
        /// Used for test purposes only to emulate missing members.
        /// </summary>
        private SmallDictionary<int, bool> _lazyMakeMemberMissingMap;

59 60
        // Protected for access in CSharpCompilation.WithAdditionalFeatures
        protected readonly IReadOnlyDictionary<string, string> _features;
61

62 63 64
        public ScriptCompilationInfo ScriptCompilationInfo => CommonScriptCompilationInfo;
        internal abstract ScriptCompilationInfo CommonScriptCompilationInfo { get; }

T
Tomas Matousek 已提交
65 66 67
        internal Compilation(
            string name,
            ImmutableArray<MetadataReference> references,
68
            IReadOnlyDictionary<string, string> features,
T
Tomas Matousek 已提交
69 70 71 72
            bool isSubmission,
            AsyncQueue<CompilationEvent> eventQueue)
        {
            Debug.Assert(!references.IsDefault);
73
            Debug.Assert(features != null);
T
Tomas Matousek 已提交
74 75 76 77 78

            this.AssemblyName = name;
            this.ExternalReferences = references;
            this.EventQueue = eventQueue;

79
            _lazySubmissionSlotIndex = isSubmission ? SubmissionSlotIndexToBeAllocated : SubmissionSlotIndexNotApplicable;
80
            _features = features;
81 82
        }

83
        protected static IReadOnlyDictionary<string, string> SyntaxTreeCommonFeatures(IEnumerable<SyntaxTree> trees)
84 85 86 87 88 89 90 91 92 93 94 95 96 97
        {
            IReadOnlyDictionary<string, string> set = null;

            foreach (var tree in trees)
            {
                var treeFeatures = tree.Options.Features;
                if (set == null)
                {
                    set = treeFeatures;
                }
                else
                {
                    if ((object)set != treeFeatures && !set.SetEquals(treeFeatures))
                    {
98
                        throw new ArgumentException(CodeAnalysisResources.InconsistentSyntaxTreeFeature, nameof(trees));
99 100 101 102 103 104 105 106 107 108 109
                    }
                }
            }

            if (set == null)
            {
                // Edge case where there are no syntax trees
                set = ImmutableDictionary<string, string>.Empty;
            }

            return set;
T
Tomas Matousek 已提交
110 111
        }

112
        internal abstract AnalyzerDriver AnalyzerForLanguage(ImmutableArray<DiagnosticAnalyzer> analyzers, AnalyzerManager analyzerManager);
T
Tomas Matousek 已提交
113 114 115 116 117 118

        /// <summary>
        /// Gets the source language ("C#" or "Visual Basic").
        /// </summary>
        public abstract string Language { get; }

119
        internal static void ValidateScriptCompilationParameters(Compilation previousScriptCompilation, Type returnType, ref Type globalsType)
T
Tomas Matousek 已提交
120
        {
121
            if (globalsType != null && !IsValidHostObjectType(globalsType))
T
Tomas Matousek 已提交
122
            {
123
                throw new ArgumentException(CodeAnalysisResources.ReturnTypeCannotBeValuePointerbyRefOrOpen, nameof(globalsType));
T
Tomas Matousek 已提交
124 125 126 127
            }

            if (returnType != null && !IsValidSubmissionReturnType(returnType))
            {
V
Vladimir Reshetnikov 已提交
128
                throw new ArgumentException(CodeAnalysisResources.ReturnTypeCannotBeVoidByRefOrOpen, nameof(returnType));
T
Tomas Matousek 已提交
129 130
            }

131
            if (previousScriptCompilation != null)
T
Tomas Matousek 已提交
132
            {
133
                if (globalsType == null)
T
Tomas Matousek 已提交
134
                {
135
                    globalsType = previousScriptCompilation.HostObjectType;
T
Tomas Matousek 已提交
136
                }
137
                else if (globalsType != previousScriptCompilation.HostObjectType)
T
Tomas Matousek 已提交
138
                {
139
                    throw new ArgumentException(CodeAnalysisResources.TypeMustBeSameAsHostObjectTypeOfPreviousSubmission, nameof(globalsType));
T
Tomas Matousek 已提交
140 141 142
                }

                // Force the previous submission to be analyzed. This is required for anonymous types unification.
143
                if (previousScriptCompilation.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error))
T
Tomas Matousek 已提交
144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162
                {
                    throw new InvalidOperationException(CodeAnalysisResources.PreviousSubmissionHasErrors);
                }
            }
        }

        /// <summary>
        /// Checks options passed to submission compilation constructor.
        /// Throws an exception if the options are not applicable to submissions.
        /// </summary>
        internal static void CheckSubmissionOptions(CompilationOptions options)
        {
            if (options == null)
            {
                return;
            }

            if (options.OutputKind.IsValid() && options.OutputKind != OutputKind.DynamicallyLinkedLibrary)
            {
V
Vladimir Reshetnikov 已提交
163
                throw new ArgumentException(CodeAnalysisResources.InvalidOutputKindForSubmission, nameof(options));
T
Tomas Matousek 已提交
164 165
            }

A
Andy Gocke 已提交
166 167 168 169 170
            if (options.CryptoKeyContainer != null ||
                options.CryptoKeyFile != null ||
                options.DelaySign != null ||
                !options.CryptoPublicKey.IsEmpty ||
                (options.DelaySign == true && options.PublicSign))
T
Tomas Matousek 已提交
171
            {
V
Vladimir Reshetnikov 已提交
172
                throw new ArgumentException(CodeAnalysisResources.InvalidCompilationOptions, nameof(options));
T
Tomas Matousek 已提交
173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193
            }
        }

        /// <summary>
        /// Creates a new compilation equivalent to this one with different symbol instances.
        /// </summary>
        public Compilation Clone()
        {
            return CommonClone();
        }

        protected abstract Compilation CommonClone();

        /// <summary>
        /// Returns a new compilation with a given event queue.
        /// </summary>
        internal abstract Compilation WithEventQueue(AsyncQueue<CompilationEvent> eventQueue);

        /// <summary>
        /// Gets a new <see cref="SemanticModel"/> for the specified syntax tree.
        /// </summary>
C
Charles Stoner 已提交
194
        /// <param name="syntaxTree">The specified syntax tree.</param>
195
        /// <param name="ignoreAccessibility">
196
        /// True if the SemanticModel should ignore accessibility rules when answering semantic questions.
197
        /// </param>
198
        public SemanticModel GetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility = false)
T
Tomas Matousek 已提交
199
        {
200
            return CommonGetSemanticModel(syntaxTree, ignoreAccessibility);
T
Tomas Matousek 已提交
201 202
        }

203
        protected abstract SemanticModel CommonGetSemanticModel(SyntaxTree syntaxTree, bool ignoreAccessibility);
T
Tomas Matousek 已提交
204 205 206 207 208

        /// <summary>
        /// Returns a new INamedTypeSymbol representing an error type with the given name and arity
        /// in the given optional container.
        /// </summary>
209 210 211 212 213 214 215 216 217
        public INamedTypeSymbol CreateErrorTypeSymbol(INamespaceOrTypeSymbol container, string name, int arity)
        {
            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            if (arity < 0)
            {
218
                throw new ArgumentException($"{nameof(arity)} must be >= 0", nameof(arity));
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
            }

            return CommonCreateErrorTypeSymbol(container, name, arity);
        }

        protected abstract INamedTypeSymbol CommonCreateErrorTypeSymbol(INamespaceOrTypeSymbol container, string name, int arity);

        /// <summary>
        /// Returns a new INamespaceSymbol representing an error (missing) namespace with the given name.
        /// </summary>
        public INamespaceSymbol CreateErrorNamespaceSymbol(INamespaceSymbol container, string name)
        {
            if (container == null)
            {
                throw new ArgumentNullException(nameof(container));
            }

            if (name == null)
            {
                throw new ArgumentNullException(nameof(name));
            }

            return CommonCreateErrorNamespaceSymbol(container, name);
        }

        protected abstract INamespaceSymbol CommonCreateErrorNamespaceSymbol(INamespaceSymbol container, string name);
T
Tomas Matousek 已提交
245 246 247 248 249 250 251 252 253 254

        #region Name

        internal const string UnspecifiedModuleAssemblyName = "?";

        /// <summary>
        /// Simple assembly name, or null if not specified.
        /// </summary>
        /// <remarks>
        /// The name is used for determining internals-visible-to relationship with referenced assemblies.
255
        ///
T
Tomas Matousek 已提交
256
        /// If the compilation represents an assembly the value of <see cref="AssemblyName"/> is its simple name.
257
        ///
T
Tomas Matousek 已提交
258 259 260
        /// Unless <see cref="CompilationOptions.ModuleName"/> specifies otherwise the module name
        /// written to metadata is <see cref="AssemblyName"/> with an extension based upon <see cref="CompilationOptions.OutputKind"/>.
        /// </remarks>
261
        public string AssemblyName { get; }
T
Tomas Matousek 已提交
262

263
        internal void CheckAssemblyName(DiagnosticBag diagnostics)
T
Tomas Matousek 已提交
264
        {
265
            // We could only allow name == null if OutputKind is Module.
266
            // However, it does no harm that we allow name == null for assemblies as well, so we don't enforce it.
T
Tomas Matousek 已提交
267

268
            if (this.AssemblyName != null)
T
Tomas Matousek 已提交
269
            {
270
                MetadataHelpers.CheckAssemblyOrModuleName(this.AssemblyName, MessageProvider, MessageProvider.ERR_BadAssemblyName, diagnostics);
T
Tomas Matousek 已提交
271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343
            }
        }

        internal string MakeSourceAssemblySimpleName()
        {
            return AssemblyName ?? UnspecifiedModuleAssemblyName;
        }

        internal string MakeSourceModuleName()
        {
            return Options.ModuleName ??
                   (AssemblyName != null ? AssemblyName + Options.OutputKind.GetDefaultExtension() : UnspecifiedModuleAssemblyName);
        }

        /// <summary>
        /// Creates a compilation with the specified assembly name.
        /// </summary>
        /// <param name="assemblyName">The new assembly name.</param>
        /// <returns>A new compilation.</returns>
        public Compilation WithAssemblyName(string assemblyName)
        {
            return CommonWithAssemblyName(assemblyName);
        }

        protected abstract Compilation CommonWithAssemblyName(string outputName);

        #endregion

        #region Options

        /// <summary>
        /// Gets the options the compilation was created with.
        /// </summary>
        public CompilationOptions Options { get { return CommonOptions; } }

        protected abstract CompilationOptions CommonOptions { get; }

        /// <summary>
        /// Creates a new compilation with the specified compilation options.
        /// </summary>
        /// <param name="options">The new options.</param>
        /// <returns>A new compilation.</returns>
        public Compilation WithOptions(CompilationOptions options)
        {
            return CommonWithOptions(options);
        }

        protected abstract Compilation CommonWithOptions(CompilationOptions options);

        #endregion

        #region Submissions

        // An index in the submission slot array. Allocated lazily in compilation phase based upon the slot index of the previous submission.
        // Special values:
        // -1 ... neither this nor previous submissions in the chain allocated a slot (the submissions don't contain code)
        // -2 ... the slot of this submission hasn't been determined yet
        // -3 ... this is not a submission compilation
        private int _lazySubmissionSlotIndex;
        private const int SubmissionSlotIndexNotApplicable = -3;
        private const int SubmissionSlotIndexToBeAllocated = -2;

        /// <summary>
        /// True if the compilation represents an interactive submission.
        /// </summary>
        internal bool IsSubmission
        {
            get
            {
                return _lazySubmissionSlotIndex != SubmissionSlotIndexNotApplicable;
            }
        }

344 345 346 347 348 349 350 351 352 353 354
        /// <summary>
        /// The previous submission, if any, or null.
        /// </summary>
        private Compilation PreviousSubmission
        {
            get
            {
                return ScriptCompilationInfo?.PreviousScriptCompilation;
            }
        }

T
Tomas Matousek 已提交
355 356 357 358 359 360 361 362 363
        /// <summary>
        /// Gets or allocates a runtime submission slot index for this compilation.
        /// </summary>
        /// <returns>Non-negative integer if this is a submission and it or a previous submission contains code, negative integer otherwise.</returns>
        internal int GetSubmissionSlotIndex()
        {
            if (_lazySubmissionSlotIndex == SubmissionSlotIndexToBeAllocated)
            {
                // TODO (tomat): remove recursion
364
                int lastSlotIndex = ScriptCompilationInfo.PreviousScriptCompilation?.GetSubmissionSlotIndex() ?? 0;
T
Tomas Matousek 已提交
365 366 367 368 369 370
                _lazySubmissionSlotIndex = HasCodeToEmit() ? lastSlotIndex + 1 : lastSlotIndex;
            }

            return _lazySubmissionSlotIndex;
        }

371
        // The type of interactive submission result requested by the host, or null if this compilation doesn't represent a submission.
T
Tomas Matousek 已提交
372 373 374 375
        //
        // The type is resolved to a symbol when the Script's instance ctor symbol is constructed. The symbol needs to be resolved against
        // the references of this compilation.
        //
376
        // Consider (tomat): As an alternative to Reflection Type we could hold onto any piece of information that lets us
T
Tomas Matousek 已提交
377 378 379 380 381
        // resolve the type symbol when needed.

        /// <summary>
        /// The type object that represents the type of submission result the host requested.
        /// </summary>
382
        internal Type SubmissionReturnType => ScriptCompilationInfo?.ReturnTypeOpt;
T
Tomas Matousek 已提交
383 384 385 386 387 388 389

        internal static bool IsValidSubmissionReturnType(Type type)
        {
            return !(type == typeof(void) || type.IsByRef || type.GetTypeInfo().ContainsGenericParameters);
        }

        /// <summary>
390
        /// The type of the globals object or null if not specified for this compilation.
T
Tomas Matousek 已提交
391
        /// </summary>
392
        internal Type HostObjectType => ScriptCompilationInfo?.GlobalsType;
T
Tomas Matousek 已提交
393 394 395 396 397 398 399

        internal static bool IsValidHostObjectType(Type type)
        {
            var info = type.GetTypeInfo();
            return !(info.IsValueType || info.IsPointer || info.IsByRef || info.ContainsGenericParameters);
        }

400
        internal abstract bool HasSubmissionResult();
T
Tomas Matousek 已提交
401

402 403
        public Compilation WithScriptCompilationInfo(ScriptCompilationInfo info) => CommonWithScriptCompilationInfo(info);
        protected abstract Compilation CommonWithScriptCompilationInfo(ScriptCompilationInfo info);
T
Tomas Matousek 已提交
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

        #endregion

        #region Syntax Trees

        /// <summary>
        /// Gets the syntax trees (parsed from source code) that this compilation was created with.
        /// </summary>
        public IEnumerable<SyntaxTree> SyntaxTrees { get { return CommonSyntaxTrees; } }
        protected abstract IEnumerable<SyntaxTree> CommonSyntaxTrees { get; }

        /// <summary>
        /// Creates a new compilation with additional syntax trees.
        /// </summary>
        /// <param name="trees">The new syntax trees.</param>
        /// <returns>A new compilation.</returns>
        public Compilation AddSyntaxTrees(params SyntaxTree[] trees)
        {
            return CommonAddSyntaxTrees(trees);
        }

        /// <summary>
        /// Creates a new compilation with additional syntax trees.
        /// </summary>
        /// <param name="trees">The new syntax trees.</param>
        /// <returns>A new compilation.</returns>
        public Compilation AddSyntaxTrees(IEnumerable<SyntaxTree> trees)
        {
            return CommonAddSyntaxTrees(trees);
        }

        protected abstract Compilation CommonAddSyntaxTrees(IEnumerable<SyntaxTree> trees);

        /// <summary>
        /// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees
        /// added later.
        /// </summary>
        /// <param name="trees">The new syntax trees.</param>
        /// <returns>A new compilation.</returns>
        public Compilation RemoveSyntaxTrees(params SyntaxTree[] trees)
        {
            return CommonRemoveSyntaxTrees(trees);
        }

        /// <summary>
        /// Creates a new compilation without the specified syntax trees. Preserves metadata info for use with trees
        /// added later.
        /// </summary>
        /// <param name="trees">The new syntax trees.</param>
        /// <returns>A new compilation.</returns>
        public Compilation RemoveSyntaxTrees(IEnumerable<SyntaxTree> trees)
        {
            return CommonRemoveSyntaxTrees(trees);
        }

        protected abstract Compilation CommonRemoveSyntaxTrees(IEnumerable<SyntaxTree> trees);

        /// <summary>
        /// Creates a new compilation without any syntax trees. Preserves metadata info for use with
        /// trees added later.
        /// </summary>
        public Compilation RemoveAllSyntaxTrees()
        {
            return CommonRemoveAllSyntaxTrees();
        }

        protected abstract Compilation CommonRemoveAllSyntaxTrees();

        /// <summary>
        /// Creates a new compilation with an old syntax tree replaced with a new syntax tree.
        /// Reuses metadata from old compilation object.
        /// </summary>
        /// <param name="newTree">The new tree.</param>
        /// <param name="oldTree">The old tree.</param>
        /// <returns>A new compilation.</returns>
        public Compilation ReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree newTree)
        {
            return CommonReplaceSyntaxTree(oldTree, newTree);
        }

        protected abstract Compilation CommonReplaceSyntaxTree(SyntaxTree oldTree, SyntaxTree newTree);

        /// <summary>
        /// Returns true if this compilation contains the specified tree. False otherwise.
        /// </summary>
        /// <param name="syntaxTree">A syntax tree.</param>
        public bool ContainsSyntaxTree(SyntaxTree syntaxTree)
        {
            return CommonContainsSyntaxTree(syntaxTree);
        }

        protected abstract bool CommonContainsSyntaxTree(SyntaxTree syntaxTree);

        /// <summary>
        /// The event queue that this compilation was created with.
        /// </summary>
        internal readonly AsyncQueue<CompilationEvent> EventQueue;

        #endregion

        #region References

        internal static ImmutableArray<MetadataReference> ValidateReferences<T>(IEnumerable<MetadataReference> references)
            where T : CompilationReference
        {
            var result = references.AsImmutableOrEmpty();
            for (int i = 0; i < result.Length; i++)
            {
                var reference = result[i];
                if (reference == null)
                {
515
                    throw new ArgumentNullException($"{nameof(references)}[{i}]");
T
Tomas Matousek 已提交
516 517 518 519 520 521
                }

                var peReference = reference as PortableExecutableReference;
                if (peReference == null && !(reference is T))
                {
                    Debug.Assert(reference is UnresolvedMetadataReference || reference is CompilationReference);
522 523
                    throw new ArgumentException(string.Format(CodeAnalysisResources.ReferenceOfTypeIsInvalid1, reference.GetType()),
                                    $"{nameof(references)}[{i}]");
T
Tomas Matousek 已提交
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539
                }
            }

            return result;
        }

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

        internal abstract CommonReferenceManager CommonGetBoundReferenceManager();

        /// <summary>
        /// Metadata references passed to the compilation constructor.
        /// </summary>
540
        public ImmutableArray<MetadataReference> ExternalReferences { get; }
T
Tomas Matousek 已提交
541 542 543 544 545 546 547 548 549 550 551 552 553 554

        /// <summary>
        /// Unique metadata references specified via #r directive in the source code of this compilation.
        /// </summary>
        public abstract ImmutableArray<MetadataReference> DirectiveReferences { get; }

        /// <summary>
        /// All reference directives used in this compilation.
        /// </summary>
        internal abstract IEnumerable<ReferenceDirective> ReferenceDirectives { get; }

        /// <summary>
        /// Maps values of #r references to resolved metadata references.
        /// </summary>
A
Andy Gocke 已提交
555
        internal abstract IDictionary<(string path, string content), MetadataReference> ReferenceDirectiveMap { get; }
T
Tomas Matousek 已提交
556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 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

        /// <summary>
        /// All metadata references -- references passed to the compilation
        /// constructor as well as references specified via #r directives.
        /// </summary>
        public IEnumerable<MetadataReference> References
        {
            get
            {
                foreach (var reference in ExternalReferences)
                {
                    yield return reference;
                }

                foreach (var reference in DirectiveReferences)
                {
                    yield return reference;
                }
            }
        }

        /// <summary>
        /// Creates a metadata reference for this compilation.
        /// </summary>
        /// <param name="aliases">
        /// Optional aliases that can be used to refer to the compilation root namespace via extern alias directive.
        /// </param>
        /// <param name="embedInteropTypes">
        /// Embed the COM types from the reference so that the compiled
        /// application no longer requires a primary interop assembly (PIA).
        /// </param>
        public abstract CompilationReference ToMetadataReference(ImmutableArray<string> aliases = default(ImmutableArray<string>), bool embedInteropTypes = false);

        /// <summary>
        /// Creates a new compilation with the specified references.
        /// </summary>
        /// <param name="newReferences">
        /// The new references.
        /// </param>
        /// <returns>A new compilation.</returns>
        public Compilation WithReferences(IEnumerable<MetadataReference> newReferences)
        {
            return this.CommonWithReferences(newReferences);
        }

        /// <summary>
        /// Creates a new compilation with the specified references.
        /// </summary>
        /// <param name="newReferences">The new references.</param>
        /// <returns>A new compilation.</returns>
        public Compilation WithReferences(params MetadataReference[] newReferences)
        {
            return this.WithReferences((IEnumerable<MetadataReference>)newReferences);
        }

        /// <summary>
        /// Creates a new compilation with the specified references.
        /// </summary>
        protected abstract Compilation CommonWithReferences(IEnumerable<MetadataReference> newReferences);

        /// <summary>
        /// Creates a new compilation with additional metadata references.
        /// </summary>
        /// <param name="references">The new references.</param>
        /// <returns>A new compilation.</returns>
        public Compilation AddReferences(params MetadataReference[] references)
        {
            return AddReferences((IEnumerable<MetadataReference>)references);
        }

        /// <summary>
        /// Creates a new compilation with additional metadata references.
        /// </summary>
        /// <param name="references">The new references.</param>
        /// <returns>A new compilation.</returns>
        public Compilation AddReferences(IEnumerable<MetadataReference> references)
        {
            if (references == null)
            {
V
Vladimir Reshetnikov 已提交
635
                throw new ArgumentNullException(nameof(references));
T
Tomas Matousek 已提交
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
            }

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

            return CommonWithReferences(this.ExternalReferences.Union(references));
        }

        /// <summary>
        /// Creates a new compilation without the specified metadata references.
        /// </summary>
        /// <param name="references">The new references.</param>
        /// <returns>A new compilation.</returns>
        public Compilation RemoveReferences(params MetadataReference[] references)
        {
            return RemoveReferences((IEnumerable<MetadataReference>)references);
        }

        /// <summary>
        /// Creates a new compilation without the specified metadata references.
        /// </summary>
        /// <param name="references">The new references.</param>
        /// <returns>A new compilation.</returns>
        public Compilation RemoveReferences(IEnumerable<MetadataReference> references)
        {
            if (references == null)
            {
V
Vladimir Reshetnikov 已提交
665
                throw new ArgumentNullException(nameof(references));
T
Tomas Matousek 已提交
666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681
            }

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

            var refSet = new HashSet<MetadataReference>(this.ExternalReferences);

            //EDMAURER if AddingReferences accepts duplicates, then a consumer supplying a list with
            //duplicates to add will not know exactly which to remove. Let them supply a list with
            //duplicates here.
            foreach (var r in references.Distinct())
            {
                if (!refSet.Remove(r))
                {
682 683
                    throw new ArgumentException(string.Format(CodeAnalysisResources.MetadataRefNotFoundToRemove1, r),
                                nameof(references));
T
Tomas Matousek 已提交
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
                }
            }

            return CommonWithReferences(refSet);
        }

        /// <summary>
        /// Creates a new compilation without any metadata references.
        /// </summary>
        public Compilation RemoveAllReferences()
        {
            return CommonWithReferences(SpecializedCollections.EmptyEnumerable<MetadataReference>());
        }

        /// <summary>
        /// Creates a new compilation with an old metadata reference replaced with a new metadata
        /// reference.
        /// </summary>
        /// <param name="newReference">The new reference.</param>
        /// <param name="oldReference">The old reference.</param>
        /// <returns>A new compilation.</returns>
        public Compilation ReplaceReference(MetadataReference oldReference, MetadataReference newReference)
        {
            if (oldReference == null)
            {
V
Vladimir Reshetnikov 已提交
709
                throw new ArgumentNullException(nameof(oldReference));
T
Tomas Matousek 已提交
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
            }

            if (newReference == null)
            {
                return this.RemoveReferences(oldReference);
            }

            return this.RemoveReferences(oldReference).AddReferences(newReference);
        }

        /// <summary>
        /// Gets the <see cref="IAssemblySymbol"/> or <see cref="IModuleSymbol"/> for a metadata reference used to create this
        /// compilation.
        /// </summary>
        /// <param name="reference">The target reference.</param>
        /// <returns>
        /// Assembly or module symbol corresponding to the given reference or null if there is none.
        /// </returns>
        public ISymbol GetAssemblyOrModuleSymbol(MetadataReference reference)
        {
            return CommonGetAssemblyOrModuleSymbol(reference);
        }

        protected abstract ISymbol CommonGetAssemblyOrModuleSymbol(MetadataReference reference);

        /// <summary>
736
        /// Gets the <see cref="MetadataReference"/> that corresponds to the assembly symbol.
T
Tomas Matousek 已提交
737 738 739 740
        /// </summary>
        /// <param name="assemblySymbol">The target symbol.</param>
        public MetadataReference GetMetadataReference(IAssemblySymbol assemblySymbol)
        {
741
            return GetBoundReferenceManager().GetMetadataReference(assemblySymbol);
T
Tomas Matousek 已提交
742 743 744 745 746 747
        }

        /// <summary>
        /// Assembly identities of all assemblies directly referenced by this compilation.
        /// </summary>
        /// <remarks>
748 749
        /// Includes identities of references passed in the compilation constructor
        /// as well as those specified via directives in source code.
T
Tomas Matousek 已提交
750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
        /// </remarks>
        public abstract IEnumerable<AssemblyIdentity> ReferencedAssemblyNames { get; }

        #endregion

        #region Symbols

        /// <summary>
        /// The <see cref="IAssemblySymbol"/> that represents the assembly being created.
        /// </summary>
        public IAssemblySymbol Assembly { get { return CommonAssembly; } }
        protected abstract IAssemblySymbol CommonAssembly { get; }

        /// <summary>
        /// Gets the <see cref="IModuleSymbol"/> for the module being created by compiling all of
        /// the source code.
        /// </summary>
        public IModuleSymbol SourceModule { get { return CommonSourceModule; } }
        protected abstract IModuleSymbol CommonSourceModule { get; }

        /// <summary>
771
        /// The root namespace that contains all namespaces and types defined in source code or in
T
Tomas Matousek 已提交
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
        /// referenced metadata, merged into a single namespace hierarchy.
        /// </summary>
        public INamespaceSymbol GlobalNamespace { get { return CommonGlobalNamespace; } }
        protected abstract INamespaceSymbol CommonGlobalNamespace { get; }

        /// <summary>
        /// Gets the corresponding compilation namespace for the specified module or assembly namespace.
        /// </summary>
        public INamespaceSymbol GetCompilationNamespace(INamespaceSymbol namespaceSymbol)
        {
            return CommonGetCompilationNamespace(namespaceSymbol);
        }

        protected abstract INamespaceSymbol CommonGetCompilationNamespace(INamespaceSymbol namespaceSymbol);

        internal abstract CommonAnonymousTypeManager CommonAnonymousTypeManager { get; }

        /// <summary>
        /// Returns the Main method that will serves as the entry point of the assembly, if it is
        /// executable (and not a script).
        /// </summary>
        public IMethodSymbol GetEntryPoint(CancellationToken cancellationToken)
        {
            return CommonGetEntryPoint(cancellationToken);
        }

        protected abstract IMethodSymbol CommonGetEntryPoint(CancellationToken cancellationToken);

        /// <summary>
        /// Get the symbol for the predefined type from the Cor Library referenced by this
        /// compilation.
        /// </summary>
        public INamedTypeSymbol GetSpecialType(SpecialType specialType)
        {
            return CommonGetSpecialType(specialType);
        }

809 810 811 812 813
        /// <summary>
        /// Get the symbol for the predefined type member from the COR Library referenced by this compilation.
        /// </summary>
        internal abstract ISymbol CommonGetSpecialTypeMember(SpecialMember specialMember);

T
Tomas Matousek 已提交
814 815 816 817 818 819 820
        /// <summary>
        /// Returns true if the type is System.Type.
        /// </summary>
        internal abstract bool IsSystemTypeReference(ITypeSymbol type);

        protected abstract INamedTypeSymbol CommonGetSpecialType(SpecialType specialType);

821 822 823
        /// <summary>
        /// Lookup member declaration in well known type used by this Compilation.
        /// </summary>
T
Tomas Matousek 已提交
824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847
        internal abstract ISymbol CommonGetWellKnownTypeMember(WellKnownMember member);

        /// <summary>
        /// Returns true if the specified type is equal to or derives from System.Attribute well-known type.
        /// </summary>
        internal abstract bool IsAttributeType(ITypeSymbol type);

        /// <summary>
        /// The INamedTypeSymbol for the .NET System.Object type, which could have a TypeKind of
        /// Error if there was no COR Library in this Compilation.
        /// </summary>
        public INamedTypeSymbol ObjectType { get { return CommonObjectType; } }
        protected abstract INamedTypeSymbol CommonObjectType { get; }

        /// <summary>
        /// The TypeSymbol for the type 'dynamic' in this Compilation.
        /// </summary>
        public ITypeSymbol DynamicType { get { return CommonDynamicType; } }
        protected abstract ITypeSymbol CommonDynamicType { get; }

        /// <summary>
        /// A symbol representing the implicit Script class. This is null if the class is not
        /// defined in the compilation.
        /// </summary>
848 849
        public INamedTypeSymbol ScriptClass { get { return CommonScriptClass; } }
        protected abstract INamedTypeSymbol CommonScriptClass { get; }
T
Tomas Matousek 已提交
850

851 852 853 854 855 856 857 858 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
        /// <summary>
        /// Resolves a symbol that represents script container (Script class). Uses the
        /// full name of the container class stored in <see cref="CompilationOptions.ScriptClassName"/> to find the symbol.
        /// </summary>
        /// <returns>The Script class symbol or null if it is not defined.</returns>
        protected INamedTypeSymbol CommonBindScriptClass()
        {
            string scriptClassName = this.Options.ScriptClassName ?? "";

            string[] parts = scriptClassName.Split('.');
            INamespaceSymbol container = this.SourceModule.GlobalNamespace;

            for (int i = 0; i < parts.Length - 1; i++)
            {
                INamespaceSymbol next = container.GetNestedNamespace(parts[i]);
                if (next == null)
                {
                    AssertNoScriptTrees();
                    return null;
                }

                container = next;
            }

            foreach (INamedTypeSymbol candidate in container.GetTypeMembers(parts[parts.Length - 1]))
            {
                if (candidate.IsScriptClass)
                {
                    return candidate;
                }
            }

            AssertNoScriptTrees();
            return null;
        }

        [Conditional("DEBUG")]
        private void AssertNoScriptTrees()
        {
            foreach (var tree in this.SyntaxTrees)
            {
                Debug.Assert(tree.Options.Kind != SourceCodeKind.Script);
            }
        }

T
Tomas Matousek 已提交
896 897 898 899
        /// <summary>
        /// Returns a new ArrayTypeSymbol representing an array type tied to the base types of the
        /// COR Library in this Compilation.
        /// </summary>
900
        public IArrayTypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank = 1, NullableAnnotation elementNullableAnnotation = NullableAnnotation.None)
T
Tomas Matousek 已提交
901
        {
902
            return CommonCreateArrayTypeSymbol(elementType, rank, elementNullableAnnotation);
T
Tomas Matousek 已提交
903 904
        }

905 906 907 908 909 910 911 912 913 914 915
        /// <summary>
        /// Returns a new ArrayTypeSymbol representing an array type tied to the base types of the
        /// COR Library in this Compilation.
        /// </summary>
        /// <remarks>This overload is for backwards compatibility. Do not remove.</remarks>
        public IArrayTypeSymbol CreateArrayTypeSymbol(ITypeSymbol elementType, int rank)
        {
            return CreateArrayTypeSymbol(elementType, rank, elementNullableAnnotation: default);
        }

        protected abstract IArrayTypeSymbol CommonCreateArrayTypeSymbol(ITypeSymbol elementType, int rank, NullableAnnotation elementNullableAnnotation);
T
Tomas Matousek 已提交
916 917 918 919 920 921 922 923 924 925 926 927

        /// <summary>
        /// Returns a new PointerTypeSymbol representing a pointer type tied to a type in this
        /// Compilation.
        /// </summary>
        public IPointerTypeSymbol CreatePointerTypeSymbol(ITypeSymbol pointedAtType)
        {
            return CommonCreatePointerTypeSymbol(pointedAtType);
        }

        protected abstract IPointerTypeSymbol CommonCreatePointerTypeSymbol(ITypeSymbol elementType);

928 929 930 931 932 933 934 935 936
        // PERF: ETW Traces show that analyzers may use this method frequently, often requesting
        // the same symbol over and over again. XUnit analyzers, in particular, were consuming almost
        // 1% of CPU time when building Roslyn itself. This is an extremely simple cache that evicts on
        // hash code conflicts, but seems to do the trick. The size is mostly arbitrary. My guess
        // is that there are maybe a couple dozen analyzers in the solution and each one has
        // ~0-2 unique well-known types, and the chance of hash collision is very low.
        private ConcurrentCache<string, INamedTypeSymbol> _getTypeCache =
            new ConcurrentCache<string, INamedTypeSymbol>(50, ReferenceEqualityComparer.Instance);

T
Tomas Matousek 已提交
937 938 939 940 941 942 943 944 945 946
        /// <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>
        /// <returns>Null if the type can't be found.</returns>
        /// <remarks>
        /// Since VB does not have the concept of extern aliases, it considers all referenced assemblies.
        /// </remarks>
        public INamedTypeSymbol GetTypeByMetadataName(string fullyQualifiedMetadataName)
        {
947 948 949 950 951 952 953
            if (!_getTypeCache.TryGetValue(fullyQualifiedMetadataName, out var val))
            {
                val = CommonGetTypeByMetadataName(fullyQualifiedMetadataName);
                // Ignore if someone added the same value before us
                _ = _getTypeCache.TryAdd(fullyQualifiedMetadataName, val);
            }
            return val;
T
Tomas Matousek 已提交
954 955 956 957
        }

        protected abstract INamedTypeSymbol CommonGetTypeByMetadataName(string metadataName);

958
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
959
        /// <summary>
960 961
        /// Returns a new INamedTypeSymbol with the given element types and
        /// (optional) element names, locations, and nullable annotations.
962
        /// </summary>
963
        public INamedTypeSymbol CreateTupleTypeSymbol(
964
            ImmutableArray<ITypeSymbol> elementTypes,
965 966 967
            ImmutableArray<string> elementNames = default,
            ImmutableArray<Location> elementLocations = default,
            ImmutableArray<NullableAnnotation> elementNullableAnnotations = default)
968
        {
969 970 971 972 973
            if (elementTypes.IsDefault)
            {
                throw new ArgumentNullException(nameof(elementTypes));
            }

974
            int n = elementTypes.Length;
975 976 977 978 979
            if (elementTypes.Length <= 1)
            {
                throw new ArgumentException(CodeAnalysisResources.TuplesNeedAtLeastTwoElements, nameof(elementNames));
            }

980 981 982
            elementNames = CheckTupleElementNames(n, elementNames);
            CheckTupleElementLocations(n, elementLocations);
            CheckTupleElementNullableAnnotations(n, elementNullableAnnotations);
983

984
            for (int i = 0; i < n; i++)
985 986 987 988 989 990 991 992 993 994 995 996
            {
                if (elementTypes[i] == null)
                {
                    throw new ArgumentNullException($"{nameof(elementTypes)}[{i}]");
                }

                if (!elementLocations.IsDefault && elementLocations[i] == null)
                {
                    throw new ArgumentNullException($"{nameof(elementLocations)}[{i}]");
                }
            }

997
            return CommonCreateTupleTypeSymbol(elementTypes, elementNames, elementLocations, elementNullableAnnotations);
998
        }
999
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
1000

1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025
        /// <summary>
        /// Returns a new INamedTypeSymbol with the given element types, names, and locations.
        /// </summary>
        /// <remarks>This overload is for backwards compatibility. Do not remove.</remarks>
        public INamedTypeSymbol CreateTupleTypeSymbol(
            ImmutableArray<ITypeSymbol> elementTypes,
            ImmutableArray<string> elementNames,
            ImmutableArray<Location> elementLocations)
        {
            return CreateTupleTypeSymbol(elementTypes, elementNames, elementLocations, elementNullableAnnotations: default);
        }

        protected static void CheckTupleElementNullableAnnotations(
            int cardinality,
            ImmutableArray<NullableAnnotation> elementNullableAnnotations)
        {
            if (!elementNullableAnnotations.IsDefault)
            {
                if (elementNullableAnnotations.Length != cardinality)
                {
                    throw new ArgumentException(CodeAnalysisResources.TupleElementNullableAnnotationCountMismatch, nameof(elementNullableAnnotations));
                }
            }
        }

1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038
        /// <summary>
        /// Check that if any names are provided, and their number matches the expected cardinality.
        /// Returns a normalized version of the element names (empty array if all the names are null).
        /// </summary>
        protected static ImmutableArray<string> CheckTupleElementNames(int cardinality, ImmutableArray<string> elementNames)
        {
            if (!elementNames.IsDefault)
            {
                if (elementNames.Length != cardinality)
                {
                    throw new ArgumentException(CodeAnalysisResources.TupleElementNameCountMismatch, nameof(elementNames));
                }

V
VSadov 已提交
1039 1040 1041 1042 1043 1044 1045 1046
                for (int i = 0; i < elementNames.Length; i++)
                {
                    if (elementNames[i] == "")
                    {
                        throw new ArgumentException(CodeAnalysisResources.TupleElementNameEmpty, $"{nameof(elementNames)}[{i}]");
                    }
                }

1047 1048 1049 1050 1051 1052 1053 1054 1055
                if (elementNames.All(n => n == null))
                {
                    return default(ImmutableArray<string>);
                }
            }

            return elementNames;
        }

C
CyrusNajmabadi 已提交
1056
        protected static void CheckTupleElementLocations(
1057
            int cardinality,
1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068
            ImmutableArray<Location> elementLocations)
        {
            if (!elementLocations.IsDefault)
            {
                if (elementLocations.Length != cardinality)
                {
                    throw new ArgumentException(CodeAnalysisResources.TupleElementLocationCountMismatch, nameof(elementLocations));
                }
            }
        }

1069
        protected abstract INamedTypeSymbol CommonCreateTupleTypeSymbol(
1070
            ImmutableArray<ITypeSymbol> elementTypes,
1071
            ImmutableArray<string> elementNames,
1072 1073
            ImmutableArray<Location> elementLocations,
            ImmutableArray<NullableAnnotation> elementNullableAnnotations);
1074

1075
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
1076
        /// <summary>
1077 1078 1079
        /// Returns a new INamedTypeSymbol with the given underlying type and
        /// (optional) element names, locations, and nullable annotations.
        /// The underlying type needs to be tuple-compatible.
1080
        /// </summary>
1081
        public INamedTypeSymbol CreateTupleTypeSymbol(
1082
            INamedTypeSymbol underlyingType,
1083 1084 1085
            ImmutableArray<string> elementNames = default,
            ImmutableArray<Location> elementLocations = default,
            ImmutableArray<NullableAnnotation> elementNullableAnnotations = default)
1086
        {
1087 1088 1089 1090 1091
            if ((object)underlyingType == null)
            {
                throw new ArgumentNullException(nameof(underlyingType));
            }

1092
            return CommonCreateTupleTypeSymbol(underlyingType, elementNames, elementLocations, elementNullableAnnotations);
1093
        }
1094
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
1095

1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108
        /// <summary>
        /// Returns a new INamedTypeSymbol with the given underlying type and element names and locations.
        /// The underlying type needs to be tuple-compatible.
        /// </summary>
        /// <remarks>This overload is for backwards compatibility. Do not remove.</remarks>
        public INamedTypeSymbol CreateTupleTypeSymbol(
            INamedTypeSymbol underlyingType,
            ImmutableArray<string> elementNames,
            ImmutableArray<Location> elementLocations)
        {
            return CreateTupleTypeSymbol(underlyingType, elementNames, elementLocations, elementNullableAnnotations: default);
        }

1109
        protected abstract INamedTypeSymbol CommonCreateTupleTypeSymbol(
1110
            INamedTypeSymbol underlyingType,
1111
            ImmutableArray<string> elementNames,
1112 1113
            ImmutableArray<Location> elementLocations,
            ImmutableArray<NullableAnnotation> elementNullableAnnotations);
1114

1115
        /// <summary>
1116
        /// Returns a new anonymous type symbol with the given member types, names, source locations, and nullable annotations.
1117
        /// Anonymous type members will be readonly by default.  Writable properties are
1118
        /// supported in VB and can be created by passing in <see langword="false"/> in the
1119
        /// appropriate locations in <paramref name="memberIsReadOnly"/>.
1120 1121
        /// </summary>
        public INamedTypeSymbol CreateAnonymousTypeSymbol(
1122 1123
            ImmutableArray<ITypeSymbol> memberTypes,
            ImmutableArray<string> memberNames,
1124 1125 1126
            ImmutableArray<bool> memberIsReadOnly = default,
            ImmutableArray<Location> memberLocations = default,
            ImmutableArray<NullableAnnotation> memberNullableAnnotations = default)
1127
        {
C
CyrusNajmabadi 已提交
1128 1129 1130 1131 1132 1133 1134 1135 1136 1137
            if (memberTypes.IsDefault)
            {
                throw new ArgumentNullException(nameof(memberTypes));
            }

            if (memberNames.IsDefault)
            {
                throw new ArgumentNullException(nameof(memberNames));
            }

1138 1139
            if (memberTypes.Length != memberNames.Length)
            {
1140 1141
                throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeMemberAndNamesCountMismatch2,
                                                    nameof(memberTypes), nameof(memberNames)));
1142 1143
            }

1144 1145
            if (!memberLocations.IsDefault && memberLocations.Length != memberTypes.Length)
            {
1146 1147
                throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeArgumentCountMismatch2,
                                                    nameof(memberLocations), nameof(memberNames)));
1148 1149 1150 1151
            }

            if (!memberIsReadOnly.IsDefault && memberIsReadOnly.Length != memberTypes.Length)
            {
1152 1153
                throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeArgumentCountMismatch2,
                                                    nameof(memberIsReadOnly), nameof(memberNames)));
1154 1155
            }

1156 1157 1158 1159 1160 1161
            if (!memberNullableAnnotations.IsDefault && memberNullableAnnotations.Length != memberTypes.Length)
            {
                throw new ArgumentException(string.Format(CodeAnalysisResources.AnonymousTypeArgumentCountMismatch2,
                                                    nameof(memberNullableAnnotations), nameof(memberNames)));
            }

1162 1163 1164 1165 1166 1167
            for (int i = 0, n = memberTypes.Length; i < n; i++)
            {
                if (memberTypes[i] == null)
                {
                    throw new ArgumentNullException($"{nameof(memberTypes)}[{i}]");
                }
C
CyrusNajmabadi 已提交
1168 1169 1170 1171 1172

                if (memberNames[i] == null)
                {
                    throw new ArgumentNullException($"{nameof(memberNames)}[{i}]");
                }
1173 1174 1175 1176 1177

                if (!memberLocations.IsDefault && memberLocations[i] == null)
                {
                    throw new ArgumentNullException($"{nameof(memberLocations)}[{i}]");
                }
1178 1179
            }

1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196
            return CommonCreateAnonymousTypeSymbol(memberTypes, memberNames, memberLocations, memberIsReadOnly, memberNullableAnnotations);
        }

        /// <summary>
        /// Returns a new anonymous type symbol with the given member types, names, and source locations.
        /// Anonymous type members will be readonly by default.  Writable properties are
        /// supported in VB and can be created by passing in <see langword="false"/> in the
        /// appropriate locations in <paramref name="memberIsReadOnly"/>.
        /// </summary>
        /// <remarks>This overload is for backwards compatibility. Do not remove.</remarks>
        public INamedTypeSymbol CreateAnonymousTypeSymbol(
            ImmutableArray<ITypeSymbol> memberTypes,
            ImmutableArray<string> memberNames,
            ImmutableArray<bool> memberIsReadOnly,
            ImmutableArray<Location> memberLocations)
        {
            return CreateAnonymousTypeSymbol(memberTypes, memberNames, memberIsReadOnly, memberLocations, memberNullableAnnotations: default);
1197 1198 1199
        }

        protected abstract INamedTypeSymbol CommonCreateAnonymousTypeSymbol(
1200
            ImmutableArray<ITypeSymbol> memberTypes,
1201 1202
            ImmutableArray<string> memberNames,
            ImmutableArray<Location> memberLocations,
1203 1204
            ImmutableArray<bool> memberIsReadOnly,
            ImmutableArray<NullableAnnotation> memberNullableAnnotations);
1205

1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224
        /// <summary>
        /// Classifies a conversion from <paramref name="source"/> to <paramref name="destination"/> according
        /// to this compilation's programming language.
        /// </summary>
        /// <param name="source">Source type of value to be converted</param>
        /// <param name="destination">Destination type of value to be converted</param>
        /// <returns>A <see cref="CommonConversion"/> that classifies the conversion from the
        /// <paramref name="source"/> type to the <paramref name="destination"/> type.</returns>
        public abstract CommonConversion ClassifyCommonConversion(ITypeSymbol source, ITypeSymbol destination);

        /// <summary>
        /// Returns true if there is an implicit (C#) or widening (VB) conversion from
        /// <paramref name="fromType"/> to <paramref name="toType"/>. Returns false if
        /// either <paramref name="fromType"/> or <paramref name="toType"/> is null, or
        /// if no such conversion exists.
        /// </summary>
        public bool HasImplicitConversion(ITypeSymbol fromType, ITypeSymbol toType)
            => fromType != null && toType != null && this.ClassifyCommonConversion(fromType, toType).IsImplicit;

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 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360
        /// <summary>
        /// Checks if <paramref name="symbol"/> is accessible from within <paramref name="within"/>. An optional qualifier of type
        /// <paramref name="throughType"/> is used to resolve protected access for instance members. All symbols are
        /// required to be from this compilation or some assembly referenced (<see cref="References"/>) by this
        /// compilation. <paramref name="within"/> is required to be an <see cref="INamedTypeSymbol"/> or <see cref="IAssemblySymbol"/>.
        /// </summary>
        /// <remarks>
        /// <para>Submissions can reference symbols from previous submissions and their referenced assemblies, even
        /// though those references are missing from <see cref="References"/>.
        /// See https://github.com/dotnet/roslyn/issues/27356.
        /// This implementation works around that by permitting symbols from previous submissions as well.</para>
        /// <para>It is advised to avoid the use of this API within the compilers, as the compilers have additional
        /// requirements for access checking that are not satisfied by this implementation, including the
        /// avoidance of infinite recursion that could result from the use of the ISymbol APIs here, the detection
        /// of use-site diagnostics, and additional returned details (from the compiler's internal APIs) that are
        /// helpful for more precisely diagnosing reasons for accessibility failure.</para>
        /// </remarks>
        public bool IsSymbolAccessibleWithin(
            ISymbol symbol,
            ISymbol within,
            ITypeSymbol throughType = null)
        {
            if (symbol is null)
            {
                throw new ArgumentNullException(nameof(symbol));
            }

            if (within is null)
            {
                throw new ArgumentNullException(nameof(within));
            }

            if (!(within is INamedTypeSymbol || within is IAssemblySymbol))
            {
                throw new ArgumentException(string.Format(CodeAnalysisResources.IsSymbolAccessibleBadWithin, nameof(within)), nameof(within));
            }

            checkInCompilationReferences(symbol, nameof(symbol));
            checkInCompilationReferences(within, nameof(within));
            if (!(throughType is null))
            {
                checkInCompilationReferences(throughType, nameof(throughType));
            }

            return IsSymbolAccessibleWithinCore(symbol, within, throughType);

            void checkInCompilationReferences(ISymbol s, string parameterName)
            {
                var containingAssembly = computeContainingAssembly(s);
                if (!assemblyIsInReferences(containingAssembly))
                {
                    throw new ArgumentException(string.Format(CodeAnalysisResources.IsSymbolAccessibleWrongAssembly, parameterName), parameterName);
                }
            }

            bool assemblyIsInReferences(IAssemblySymbol a)
            {
                if (assemblyIsInCompilationReferences(a, this))
                {
                    return true;
                }

                if (this.IsSubmission)
                {
                    // Submissions can reference symbols from previous submissions and their referenced assemblies, even
                    // though those references are missing from this.References. We work around that by digging in
                    // to find references of previous submissions. See https://github.com/dotnet/roslyn/issues/27356
                    for (Compilation c = this.PreviousSubmission; c != null; c = c.PreviousSubmission)
                    {
                        if (assemblyIsInCompilationReferences(a, c))
                        {
                            return true;
                        }
                    }
                }

                return false;
            }

            bool assemblyIsInCompilationReferences(IAssemblySymbol a, Compilation compilation)
            {
                if (a.Equals(compilation.Assembly))
                {
                    return true;
                }

                foreach (var reference in compilation.References)
                {
                    if (a.Equals(compilation.GetAssemblyOrModuleSymbol(reference)))
                    {
                        return true;
                    }
                }

                return false;
            }

            IAssemblySymbol computeContainingAssembly(ISymbol s)
            {
                while (true)
                {
                    switch (s.Kind)
                    {
                        case SymbolKind.Assembly:
                            return (IAssemblySymbol)s;
                        case SymbolKind.PointerType:
                            s = ((IPointerTypeSymbol)s).PointedAtType;
                            continue;
                        case SymbolKind.ArrayType:
                            s = ((IArrayTypeSymbol)s).ElementType;
                            continue;
                        case SymbolKind.Alias:
                            s = ((IAliasSymbol)s).Target;
                            continue;
                        case SymbolKind.Discard:
                            s = ((IDiscardSymbol)s).Type;
                            continue;
                        case SymbolKind.DynamicType:
                        case SymbolKind.ErrorType:
                        case SymbolKind.Preprocessing:
                        case SymbolKind.Namespace:
                            // these symbols are not restricted in where they can be accessed, so unless they report
                            // a containing assembly, we treat them as in the current assembly for access purposes
                            return s.ContainingAssembly ?? this.Assembly;
                        default:
                            return s.ContainingAssembly;
                    }
                }
            }
        }

        private protected abstract bool IsSymbolAccessibleWithinCore(
            ISymbol symbol,
            ISymbol within,
            ITypeSymbol throughType);

1361 1362
        internal abstract IConvertibleConversion ClassifyConvertibleConversion(IOperation source, ITypeSymbol destination, out Optional<object> constantValue);

T
Tomas Matousek 已提交
1363 1364 1365 1366
        #endregion

        #region Diagnostics

1367
        internal const CompilationStage DefaultDiagnosticsStage = CompilationStage.Compile;
T
Tomas Matousek 已提交
1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390

        /// <summary>
        /// Gets the diagnostics produced during the parsing stage.
        /// </summary>
        public abstract ImmutableArray<Diagnostic> GetParseDiagnostics(CancellationToken cancellationToken = default(CancellationToken));

        /// <summary>
        /// Gets the diagnostics produced during symbol declaration.
        /// </summary>
        public abstract ImmutableArray<Diagnostic> GetDeclarationDiagnostics(CancellationToken cancellationToken = default(CancellationToken));

        /// <summary>
        /// Gets the diagnostics produced during the analysis of method bodies and field initializers.
        /// </summary>
        public abstract ImmutableArray<Diagnostic> GetMethodBodyDiagnostics(CancellationToken cancellationToken = default(CancellationToken));

        /// <summary>
        /// Gets all the diagnostics for the compilation, including syntax, declaration, and
        /// binding. Does not include any diagnostics that might be produced during emit, see
        /// <see cref="EmitResult"/>.
        /// </summary>
        public abstract ImmutableArray<Diagnostic> GetDiagnostics(CancellationToken cancellationToken = default(CancellationToken));

M
Manish Vasani 已提交
1391
        internal abstract void GetDiagnostics(CompilationStage stage, bool includeEarlierStages, DiagnosticBag diagnostics, CancellationToken cancellationToken = default);
1392

M
Manish Vasani 已提交
1393
        internal void EnsureCompilationEventQueueCompleted()
1394
        {
M
Manish Vasani 已提交
1395
            Debug.Assert(EventQueue != null);
1396

M
Manish Vasani 已提交
1397
            lock (EventQueue)
1398
            {
M
Manish Vasani 已提交
1399
                if (!EventQueue.IsCompleted)
1400
                {
M
Manish Vasani 已提交
1401
                    CompleteCompilationEventQueue_NoLock();
1402 1403 1404 1405
                }
            }
        }

M
Manish Vasani 已提交
1406 1407 1408
        internal void CompleteCompilationEventQueue_NoLock()
        {
            Debug.Assert(EventQueue != null);
1409

M
Manish Vasani 已提交
1410 1411 1412 1413 1414 1415
            // Signal the end of compilation.
            EventQueue.TryEnqueue(new CompilationCompletedEvent(this));
            EventQueue.PromiseNotToEnqueue();
            EventQueue.TryComplete();
        }

T
Tomas Matousek 已提交
1416 1417
        internal abstract CommonMessageProvider MessageProvider { get; }

C
Charles Stoner 已提交
1418 1419 1420 1421
        /// <summary>
        /// Filter out warnings based on the compiler options (/nowarn, /warn and /warnaserror) and the pragma warning directives.
        /// 'incoming' is freed.
        /// </summary>
T
Tomas Matousek 已提交
1422 1423
        /// <param name="accumulator">Bag to which filtered diagnostics will be added.</param>
        /// <param name="incoming">Diagnostics to be filtered.</param>
1424
        /// <returns>True if there are no unsuppressed errors (i.e., no errors which fail compilation).</returns>
M
Manish Vasani 已提交
1425 1426 1427
        internal bool FilterAndAppendAndFreeDiagnostics(DiagnosticBag accumulator, ref DiagnosticBag incoming)
        {
            bool result = FilterAndAppendDiagnostics(accumulator, incoming.AsEnumerableWithoutResolution(), exclude: null);
C
Charles Stoner 已提交
1428 1429 1430 1431 1432 1433 1434 1435
            incoming.Free();
            incoming = null;
            return result;
        }

        /// <summary>
        /// Filter out warnings based on the compiler options (/nowarn, /warn and /warnaserror) and the pragma warning directives.
        /// </summary>
1436
        /// <returns>True if there are no unsuppressed errors (i.e., no errors which fail compilation).</returns>
M
Manish Vasani 已提交
1437
        internal bool FilterAndAppendDiagnostics(DiagnosticBag accumulator, IEnumerable<Diagnostic> incoming, HashSet<int> exclude)
C
Charles Stoner 已提交
1438 1439 1440 1441 1442 1443
        {
            bool hasError = false;
            bool reportSuppressedDiagnostics = Options.ReportSuppressedDiagnostics;

            foreach (Diagnostic d in incoming)
            {
1444 1445 1446 1447 1448
                if (exclude?.Contains(d.Code) == true)
                {
                    continue;
                }

M
Manish Vasani 已提交
1449 1450 1451
                var filtered = Options.FilterDiagnostic(d);
                if (filtered == null ||
                    (!reportSuppressedDiagnostics && filtered.IsSuppressed))
C
Charles Stoner 已提交
1452
                {
M
Manish Vasani 已提交
1453
                    continue;
C
Charles Stoner 已提交
1454
                }
M
Manish Vasani 已提交
1455
                else if (filtered.IsUnsuppressableError())
C
Charles Stoner 已提交
1456 1457 1458 1459 1460 1461 1462 1463 1464
                {
                    hasError = true;
                }

                accumulator.Add(filtered);
            }

            return !hasError;
        }
T
Tomas Matousek 已提交
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

        #endregion

        #region Resources

        /// <summary>
        /// Create a stream filled with default win32 resources.
        /// </summary>
        public Stream CreateDefaultWin32Resources(bool versionResource, bool noManifest, Stream manifestContents, Stream iconInIcoFormat)
        {
            //Win32 resource encodings use a lot of 16bit values. Do all of the math checked with the
            //expectation that integer types are well-chosen with size in mind.
            checked
            {
                var result = new MemoryStream(1024);

                //start with a null resource just as rc.exe does
                AppendNullResource(result);

                if (versionResource)
                    AppendDefaultVersionResource(result);

                if (!noManifest)
                {
                    if (this.Options.OutputKind.IsApplication())
                    {
                        // Applications use a default manifest if one is not specified.
                        if (manifestContents == null)
                        {
                            manifestContents = typeof(Compilation).GetTypeInfo().Assembly.GetManifestResourceStream("Microsoft.CodeAnalysis.Resources.default.win32manifest");
                        }
                    }
                    else
                    {
                        // Modules never have manifests, even if one is specified.
                        //Debug.Assert(!this.Options.OutputKind.IsNetModule() || manifestContents == null);
                    }

                    if (manifestContents != null)
                    {
                        Win32ResourceConversions.AppendManifestToResourceStream(result, manifestContents, !this.Options.OutputKind.IsApplication());
                    }
                }

                if (iconInIcoFormat != null)
                {
                    Win32ResourceConversions.AppendIconToResourceStream(result, iconInIcoFormat);
                }

                result.Position = 0;
                return result;
            }
        }

        internal static void AppendNullResource(Stream resourceStream)
        {
            var writer = new BinaryWriter(resourceStream);
            writer.Write((UInt32)0);
            writer.Write((UInt32)0x20);
            writer.Write((UInt16)0xFFFF);
            writer.Write((UInt16)0);
            writer.Write((UInt16)0xFFFF);
            writer.Write((UInt16)0);
            writer.Write((UInt32)0);            //DataVersion
            writer.Write((UInt16)0);            //MemoryFlags
            writer.Write((UInt16)0);            //LanguageId
1531 1532
            writer.Write((UInt32)0);            //Version
            writer.Write((UInt32)0);            //Characteristics
T
Tomas Matousek 已提交
1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543
        }

        protected abstract void AppendDefaultVersionResource(Stream resourceStream);

        internal enum Win32ResourceForm : byte
        {
            UNKNOWN,
            COFF,
            RES
        }

C
Charles Stoner 已提交
1544
        internal static Win32ResourceForm DetectWin32ResourceForm(Stream win32Resources)
T
Tomas Matousek 已提交
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
        {
            var reader = new BinaryReader(win32Resources, Encoding.Unicode);

            var initialPosition = win32Resources.Position;
            var initial32Bits = reader.ReadUInt32();
            win32Resources.Position = initialPosition;

            //RC.EXE output starts with a resource that contains no data.
            if (initial32Bits == 0)
                return Win32ResourceForm.RES;
            else if ((initial32Bits & 0xFFFF0000) != 0 || (initial32Bits & 0x0000FFFF) != 0xFFFF)
                // See CLiteWeightStgdbRW::FindObjMetaData in peparse.cpp
                return Win32ResourceForm.COFF;
            else
                return Win32ResourceForm.UNKNOWN;
        }

        internal Cci.ResourceSection MakeWin32ResourcesFromCOFF(Stream win32Resources, DiagnosticBag diagnostics)
        {
            if (win32Resources == null)
            {
                return null;
            }

            Cci.ResourceSection resources;

            try
            {
                resources = COFFResourceReader.ReadWin32ResourcesFromCOFF(win32Resources);
            }
            catch (BadImageFormatException ex)
            {
                diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message));
                return null;
            }
            catch (IOException ex)
            {
                diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message));
                return null;
            }
            catch (ResourceException ex)
            {
                diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message));
                return null;
            }

            return resources;
        }

        internal List<Win32Resource> MakeWin32ResourceList(Stream win32Resources, DiagnosticBag diagnostics)
        {
            if (win32Resources == null)
            {
                return null;
            }
1600
            List<RESOURCE> resources;
T
Tomas Matousek 已提交
1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624

            try
            {
                resources = CvtResFile.ReadResFile(win32Resources);
            }
            catch (ResourceException ex)
            {
                diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, Location.None, ex.Message));
                return null;
            }

            if (resources == null)
            {
                return null;
            }

            var resourceList = new List<Win32Resource>();

            foreach (var r in resources)
            {
                var result = new Win32Resource(
                    data: r.data,
                    codePage: 0,
                    languageId: r.LanguageId,
1625 1626
                    //EDMAURER converting to int from ushort.
                    //Go to short first to avoid sign extension.
T
Tomas Matousek 已提交
1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638
                    id: unchecked((short)r.pstringName.Ordinal),
                    name: r.pstringName.theString,
                    typeId: unchecked((short)r.pstringType.Ordinal),
                    typeName: r.pstringType.theString
                );

                resourceList.Add(result);
            }

            return resourceList;
        }

1639 1640 1641 1642 1643
        internal void SetupWin32Resources(CommonPEModuleBuilder moduleBeingBuilt, Stream win32Resources, DiagnosticBag diagnostics)
        {
            if (win32Resources == null)
                return;

1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655
            Win32ResourceForm resourceForm;

            try
            {
                resourceForm = DetectWin32ResourceForm(win32Resources);
            }
            catch (EndOfStreamException)
            {
                diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, NoLocation.Singleton, CodeAnalysisResources.UnrecognizedResourceFileFormat));
                return;
            }
            catch (Exception ex)
1656
            {
1657 1658 1659 1660 1661
                diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, NoLocation.Singleton, ex.Message));
                return;
            }

            switch (resourceForm)
1662
            {
1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674
                case Win32ResourceForm.COFF:
                    moduleBeingBuilt.Win32ResourceSection = MakeWin32ResourcesFromCOFF(win32Resources, diagnostics);
                    break;
                case Win32ResourceForm.RES:
                    moduleBeingBuilt.Win32Resources = MakeWin32ResourceList(win32Resources, diagnostics);
                    break;
                default:
                    diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_BadWin32Resource, NoLocation.Singleton, CodeAnalysisResources.UnrecognizedResourceFileFormat));
                    break;
            }
        }

T
Tomas Matousek 已提交
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
        internal void ReportManifestResourceDuplicates(
            IEnumerable<ResourceDescription> manifestResources,
            IEnumerable<string> addedModuleNames,
            IEnumerable<string> addedModuleResourceNames,
            DiagnosticBag diagnostics)
        {
            if (Options.OutputKind == OutputKind.NetModule && !(manifestResources != null && manifestResources.Any()))
            {
                return;
            }

            var uniqueResourceNames = new HashSet<string>();

            if (manifestResources != null && manifestResources.Any())
            {
                var uniqueFileNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
                foreach (var resource in manifestResources)
                {
                    if (!uniqueResourceNames.Add(resource.ResourceName))
                    {
                        diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceNotUnique, Location.None, resource.ResourceName));
                    }

                    // file name could be null if resource is embedded
                    var fileName = resource.FileName;
                    if (fileName != null && !uniqueFileNames.Add(fileName))
                    {
                        diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceFileNameNotUnique, Location.None, fileName));
                    }
                }

                foreach (var fileName in addedModuleNames)
                {
                    if (!uniqueFileNames.Add(fileName))
                    {
                        diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceFileNameNotUnique, Location.None, fileName));
                    }
                }
            }

            if (Options.OutputKind != OutputKind.NetModule)
            {
                foreach (string name in addedModuleResourceNames)
                {
                    if (!uniqueResourceNames.Add(name))
                    {
                        diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceNotUnique, Location.None, name));
                    }
                }
            }
        }

        #endregion

1729 1730
        #region Emit

J
Jared Parsons 已提交
1731 1732 1733 1734 1735
        /// <summary>
        /// There are two ways to sign PE files
        ///   1. By directly signing the <see cref="PEBuilder"/>
        ///   2. Write the unsigned PE to disk and use CLR COM APIs to sign.
        /// The preferred method is #1 as it's more efficient and more resilient (no reliance on %TEMP%). But 
1736
        /// we must continue to support #2 as it's the only way to do the following:
J
Jared Parsons 已提交
1737
        ///   - Access private keys stored in a key container
1738
        ///   - Do proper counter signature verification for AssemblySignatureKey attributes
J
Jared Parsons 已提交
1739 1740 1741
        /// </summary>
        internal bool SignUsingBuilder =>
            string.IsNullOrEmpty(StrongNameKeys.KeyContainer) &&
1742
            !StrongNameKeys.HasCounterSignature &&
J
Jared Parsons 已提交
1743 1744
            !_features.ContainsKey("UseLegacyStrongNameProvider");

T
Tomas Matousek 已提交
1745 1746 1747
        /// <summary>
        /// Constructs the module serialization properties out of the compilation options of this compilation.
        /// </summary>
1748
        internal Cci.ModulePropertiesForSerialization ConstructModuleSerializationProperties(
T
Tomas Matousek 已提交
1749 1750 1751 1752 1753 1754
            EmitOptions emitOptions,
            string targetRuntimeVersion,
            Guid moduleVersionId = default(Guid))
        {
            CompilationOptions compilationOptions = this.Options;
            Platform platform = compilationOptions.Platform;
1755
            OutputKind outputKind = compilationOptions.OutputKind;
T
Tomas Matousek 已提交
1756 1757 1758 1759 1760 1761

            if (!platform.IsValid())
            {
                platform = Platform.AnyCpu;
            }

1762 1763 1764 1765 1766 1767 1768
            if (!outputKind.IsValid())
            {
                outputKind = OutputKind.DynamicallyLinkedLibrary;
            }

            bool requires64Bit = platform.Requires64Bit();
            bool requires32Bit = platform.Requires32Bit();
T
Tomas Matousek 已提交
1769 1770 1771 1772

            ushort fileAlignment;
            if (emitOptions.FileAlignment == 0 || !CompilationOptions.IsValidFileAlignment(emitOptions.FileAlignment))
            {
1773 1774 1775
                fileAlignment = requires64Bit
                    ? Cci.ModulePropertiesForSerialization.DefaultFileAlignment64Bit
                    : Cci.ModulePropertiesForSerialization.DefaultFileAlignment32Bit;
T
Tomas Matousek 已提交
1776 1777 1778 1779 1780 1781
            }
            else
            {
                fileAlignment = (ushort)emitOptions.FileAlignment;
            }

1782
            ulong baseAddress = unchecked(emitOptions.BaseAddress + 0x8000) & (requires64Bit ? 0xffffffffffff0000 : 0x00000000ffff0000);
T
Tomas Matousek 已提交
1783 1784 1785 1786 1787 1788 1789 1790

            // cover values smaller than 0x8000, overflow and default value 0):
            if (baseAddress == 0)
            {
                if (outputKind == OutputKind.ConsoleApplication ||
                    outputKind == OutputKind.WindowsApplication ||
                    outputKind == OutputKind.WindowsRuntimeApplication)
                {
1791
                    baseAddress = (requires64Bit) ? Cci.ModulePropertiesForSerialization.DefaultExeBaseAddress64Bit : Cci.ModulePropertiesForSerialization.DefaultExeBaseAddress32Bit;
T
Tomas Matousek 已提交
1792 1793 1794
                }
                else
                {
1795
                    baseAddress = (requires64Bit) ? Cci.ModulePropertiesForSerialization.DefaultDllBaseAddress64Bit : Cci.ModulePropertiesForSerialization.DefaultDllBaseAddress32Bit;
T
Tomas Matousek 已提交
1796 1797 1798
                }
            }

1799 1800 1801
            ulong sizeOfHeapCommit = requires64Bit
                ? Cci.ModulePropertiesForSerialization.DefaultSizeOfHeapCommit64Bit
                : Cci.ModulePropertiesForSerialization.DefaultSizeOfHeapCommit32Bit;
T
Tomas Matousek 已提交
1802 1803 1804

            // Dev10 always uses the default value for 32bit for sizeOfHeapReserve.
            // check with link -dump -headers <filename>
1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827
            const ulong sizeOfHeapReserve = Cci.ModulePropertiesForSerialization.DefaultSizeOfHeapReserve32Bit;

            ulong sizeOfStackReserve = requires64Bit
                ? Cci.ModulePropertiesForSerialization.DefaultSizeOfStackReserve64Bit
                : Cci.ModulePropertiesForSerialization.DefaultSizeOfStackReserve32Bit;

            ulong sizeOfStackCommit = requires64Bit
                ? Cci.ModulePropertiesForSerialization.DefaultSizeOfStackCommit64Bit
                : Cci.ModulePropertiesForSerialization.DefaultSizeOfStackCommit32Bit;

            SubsystemVersion subsystemVersion;
            if (emitOptions.SubsystemVersion.Equals(SubsystemVersion.None) || !emitOptions.SubsystemVersion.IsValid)
            {
                subsystemVersion = SubsystemVersion.Default(outputKind, platform);
            }
            else
            {
                subsystemVersion = emitOptions.SubsystemVersion;
            }

            Machine machine;
            switch (platform)
            {
1828
                case Platform.Arm64:
T
Tomas Matousek 已提交
1829
                    machine = Machine.Arm64;
1830 1831
                    break;

1832 1833 1834 1835 1836 1837 1838
                case Platform.Arm:
                    machine = Machine.ArmThumb2;
                    break;

                case Platform.X64:
                    machine = Machine.Amd64;
                    break;
T
Tomas Matousek 已提交
1839

1840 1841 1842
                case Platform.Itanium:
                    machine = Machine.IA64;
                    break;
T
Tomas Matousek 已提交
1843

1844 1845 1846
                case Platform.X86:
                    machine = Machine.I386;
                    break;
T
Tomas Matousek 已提交
1847

1848 1849 1850 1851
                case Platform.AnyCpu:
                case Platform.AnyCpu32BitPreferred:
                    machine = Machine.Unknown;
                    break;
T
Tomas Matousek 已提交
1852

1853 1854 1855 1856 1857
                default:
                    throw ExceptionUtilities.UnexpectedValue(platform);
            }

            return new Cci.ModulePropertiesForSerialization(
T
Tomas Matousek 已提交
1858
                persistentIdentifier: moduleVersionId,
T
Tomas Matousek 已提交
1859
                corFlags: GetCorHeaderFlags(machine, HasStrongName, prefers32Bit: platform == Platform.AnyCpu32BitPreferred),
T
Tomas Matousek 已提交
1860
                fileAlignment: fileAlignment,
T
Tomas Matousek 已提交
1861
                sectionAlignment: Cci.ModulePropertiesForSerialization.DefaultSectionAlignment,
T
Tomas Matousek 已提交
1862
                targetRuntimeVersion: targetRuntimeVersion,
1863
                machine: machine,
T
Tomas Matousek 已提交
1864 1865 1866 1867 1868
                baseAddress: baseAddress,
                sizeOfHeapReserve: sizeOfHeapReserve,
                sizeOfHeapCommit: sizeOfHeapCommit,
                sizeOfStackReserve: sizeOfStackReserve,
                sizeOfStackCommit: sizeOfStackCommit,
T
Tomas Matousek 已提交
1869
                dllCharacteristics: GetDllCharacteristics(emitOptions.HighEntropyVirtualAddressSpace, compilationOptions.OutputKind == OutputKind.WindowsRuntimeApplication),
1870 1871 1872 1873 1874 1875
                imageCharacteristics: GetCharacteristics(outputKind, requires32Bit),
                subsystem: GetSubsystem(outputKind),
                majorSubsystemVersion: (ushort)subsystemVersion.Major,
                minorSubsystemVersion: (ushort)subsystemVersion.Minor,
                linkerMajorVersion: this.LinkerMajorVersion,
                linkerMinorVersion: 0);
T
Tomas Matousek 已提交
1876 1877
        }

T
Tomas Matousek 已提交
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
        private static CorFlags GetCorHeaderFlags(Machine machine, bool strongNameSigned, bool prefers32Bit)
        {
            CorFlags result = CorFlags.ILOnly;

            if (machine == Machine.I386)
            {
                result |= CorFlags.Requires32Bit;
            }

            if (strongNameSigned)
            {
                result |= CorFlags.StrongNameSigned;
            }

            if (prefers32Bit)
            {
                result |= CorFlags.Requires32Bit | CorFlags.Prefers32Bit;
            }

            return result;
        }

        internal static DllCharacteristics GetDllCharacteristics(bool enableHighEntropyVA, bool configureToExecuteInAppContainer)
        {
            var result =
                DllCharacteristics.DynamicBase |
                DllCharacteristics.NxCompatible |
                DllCharacteristics.NoSeh |
                DllCharacteristics.TerminalServerAware;

            if (enableHighEntropyVA)
            {
                // IMAGE_DLLCHARACTERISTICS_HIGH_ENTROPY_VA
                result |= (DllCharacteristics)0x0020;
            }

            if (configureToExecuteInAppContainer)
            {
                result |= DllCharacteristics.AppContainer;
            }

            return result;
        }

1922 1923 1924 1925 1926 1927 1928
        private static Characteristics GetCharacteristics(OutputKind outputKind, bool requires32Bit)
        {
            var characteristics = Characteristics.ExecutableImage;

            if (requires32Bit)
            {
                // 32 bit machine (The standard says to always set this, the linker team says otherwise)
1929
                // The loader team says that this is not used for anything in the OS.
1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978
                characteristics |= Characteristics.Bit32Machine;
            }
            else
            {
                // Large address aware (the standard says never to set this, the linker team says otherwise).
                // The loader team says that this is not overridden for managed binaries and will be respected if set.
                characteristics |= Characteristics.LargeAddressAware;
            }

            switch (outputKind)
            {
                case OutputKind.WindowsRuntimeMetadata:
                case OutputKind.DynamicallyLinkedLibrary:
                case OutputKind.NetModule:
                    characteristics |= Characteristics.Dll;
                    break;

                case OutputKind.ConsoleApplication:
                case OutputKind.WindowsRuntimeApplication:
                case OutputKind.WindowsApplication:
                    break;

                default:
                    throw ExceptionUtilities.UnexpectedValue(outputKind);
            }

            return characteristics;
        }

        private static Subsystem GetSubsystem(OutputKind outputKind)
        {
            switch (outputKind)
            {
                case OutputKind.ConsoleApplication:
                case OutputKind.DynamicallyLinkedLibrary:
                case OutputKind.NetModule:
                case OutputKind.WindowsRuntimeMetadata:
                    return Subsystem.WindowsCui;

                case OutputKind.WindowsRuntimeApplication:
                case OutputKind.WindowsApplication:
                    return Subsystem.WindowsGui;

                default:
                    throw ExceptionUtilities.UnexpectedValue(outputKind);
            }
        }

        /// <summary>
1979 1980 1981 1982 1983
        /// The value is not used by Windows loader, but the OS appcompat infrastructure uses it to identify apps.
        /// It is useful for us to have a mechanism to identify the compiler that produced the binary.
        /// This is the appropriate value to use for that. That is what it was invented for.
        /// We don't want to have the high bit set for this in case some users perform a signed comparison to
        /// determine if the value is less than some version. The C++ linker is at 0x0B.
1984 1985 1986
        /// We'll start our numbering at 0x30 for C#, 0x50 for VB.
        /// </summary>
        internal abstract byte LinkerMajorVersion { get; }
T
Tomas Matousek 已提交
1987

1988
        internal bool HasStrongName
T
Tomas Matousek 已提交
1989 1990 1991
        {
            get
            {
1992 1993 1994 1995 1996 1997 1998 1999 2000 2001
                return !IsDelaySigned
                    && Options.OutputKind != OutputKind.NetModule
                    && StrongNameKeys.CanProvideStrongName;
            }
        }

        internal bool IsRealSigned
        {
            get
            {
2002
                // A module cannot be signed. The native compiler allowed one to create a netmodule with an AssemblyKeyFile
2003
                // or Container attribute (or specify a key via the cmd line). When the module was linked into an assembly,
B
bkoelman 已提交
2004
                // alink would sign the assembly. So rather than give an error we just don't sign when outputting a module.
T
Tomas Matousek 已提交
2005

2006
                return !IsDelaySigned
A
Andy Gocke 已提交
2007
                    && !Options.PublicSign
T
Tomas Matousek 已提交
2008 2009 2010 2011 2012 2013 2014 2015
                    && Options.OutputKind != OutputKind.NetModule
                    && StrongNameKeys.CanSign;
            }
        }

        /// <summary>
        /// Return true if the compilation contains any code or types.
        /// </summary>
2016
        internal abstract bool HasCodeToEmit();
T
Tomas Matousek 已提交
2017

2018
        internal abstract bool IsDelaySigned { get; }
T
Tomas Matousek 已提交
2019 2020 2021 2022
        internal abstract StrongNameKeys StrongNameKeys { get; }

        internal abstract CommonPEModuleBuilder CreateModuleBuilder(
            EmitOptions emitOptions,
2023
            IMethodSymbol debugEntryPoint,
2024
            Stream sourceLinkStream,
2025
            IEnumerable<EmbeddedText> embeddedTexts,
T
Tomas Matousek 已提交
2026 2027 2028
            IEnumerable<ResourceDescription> manifestResources,
            CompilationTestData testData,
            DiagnosticBag diagnostics,
M
Manish Vasani 已提交
2029
            CancellationToken cancellationToken);
T
Tomas Matousek 已提交
2030

C
Charles Stoner 已提交
2031 2032 2033 2034 2035
        /// <summary>
        /// Report declaration diagnostics and compile and synthesize method bodies.
        /// </summary>
        /// <returns>True if successful.</returns>
        internal abstract bool CompileMethods(
T
Tomas Matousek 已提交
2036
            CommonPEModuleBuilder moduleBuilder,
2037
            bool emittingPdb,
2038 2039
            bool emitMetadataOnly,
            bool emitTestCoverageData,
T
Tomas Matousek 已提交
2040 2041
            DiagnosticBag diagnostics,
            Predicate<ISymbol> filterOpt,
M
Manish Vasani 已提交
2042
            CancellationToken cancellationToken);
T
Tomas Matousek 已提交
2043

2044
        internal bool CreateDebugDocuments(DebugDocumentsBuilder documentsBuilder, IEnumerable<EmbeddedText> embeddedTexts, DiagnosticBag diagnostics)
2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061
        {
            // Check that all syntax trees are debuggable:
            bool allTreesDebuggable = true;
            foreach (var tree in SyntaxTrees)
            {
                if (!string.IsNullOrEmpty(tree.FilePath) && tree.GetText().Encoding == null)
                {
                    diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_EncodinglessSyntaxTree, tree.GetRoot().GetLocation()));
                    allTreesDebuggable = false;
                }
            }

            if (!allTreesDebuggable)
            {
                return false;
            }

2062 2063
            // Add debug documents for all embedded text first. This ensures that embedding
            // takes priority over the syntax tree pass, which will not embed.
2064
            if (!embeddedTexts.IsEmpty())
2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087
            {
                var embeddedDocuments = ArrayBuilder<Cci.DebugSourceDocument>.GetInstance();

                foreach (var text in embeddedTexts)
                {
                    Debug.Assert(!string.IsNullOrEmpty(text.FilePath));
                    string normalizedPath = documentsBuilder.NormalizeDebugDocumentPath(text.FilePath, basePath: null);
                    var existingDoc = documentsBuilder.TryGetDebugDocumentForNormalizedPath(normalizedPath);
                    if (existingDoc == null)
                    {
                        var document = new Cci.DebugSourceDocument(
                            normalizedPath,
                            DebugSourceDocumentLanguageId,
                            () => text.GetDebugSourceInfo());

                        documentsBuilder.AddDebugDocument(document);
                        embeddedDocuments.Add(document);
                    }
                }

                documentsBuilder.EmbeddedDocuments = embeddedDocuments.ToImmutableAndFree();
            }

2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099
            // Add debug documents for all trees with distinct paths.
            foreach (var tree in 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 = documentsBuilder.NormalizeDebugDocumentPath(tree.FilePath, basePath: null);
                    var existingDoc = documentsBuilder.TryGetDebugDocumentForNormalizedPath(normalizedPath);
                    if (existingDoc == null)
                    {
                        documentsBuilder.AddDebugDocument(new Cci.DebugSourceDocument(
2100 2101
                            normalizedPath,
                            DebugSourceDocumentLanguageId,
2102
                            () => tree.GetDebugSourceInfo()));
2103 2104 2105 2106
                    }
                }
            }

2107
            // Add debug documents for all pragmas.
2108 2109
            // 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.
2110
            // Therefore we need to add these in a separate pass after documents for syntax trees were added.
2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122
            foreach (var tree in SyntaxTrees)
            {
                AddDebugSourceDocumentsForChecksumDirectives(documentsBuilder, tree, diagnostics);
            }

            return true;
        }

        internal abstract Guid DebugSourceDocumentLanguageId { get; }

        internal abstract void AddDebugSourceDocumentsForChecksumDirectives(DebugDocumentsBuilder documentsBuilder, SyntaxTree tree, DiagnosticBag diagnostics);

C
Charles Stoner 已提交
2123 2124 2125 2126 2127 2128 2129 2130
        /// <summary>
        /// Update resources and generate XML documentation comments.
        /// </summary>
        /// <returns>True if successful.</returns>
        internal abstract bool GenerateResourcesAndDocumentationComments(
            CommonPEModuleBuilder moduleBeingBuilt,
            Stream xmlDocumentationStream,
            Stream win32ResourcesStream,
2131
            string outputNameOverride,
C
Charles Stoner 已提交
2132
            DiagnosticBag diagnostics,
M
Manish Vasani 已提交
2133
            CancellationToken cancellationToken);
C
Charles Stoner 已提交
2134

2135 2136 2137
        /// <summary>
        /// Reports all unused imports/usings so far (and thus it must be called as a last step of Emit)
        /// </summary>
C
Charles Stoner 已提交
2138 2139 2140 2141 2142
        internal abstract void ReportUnusedImports(
            SyntaxTree filterTree,
            DiagnosticBag diagnostics,
            CancellationToken cancellationToken);

2143 2144 2145
        /// <summary>
        /// Signals the event queue, if any, that we are done compiling.
        /// There should not be more compiling actions after this step.
2146
        /// NOTE: once we signal about completion to analyzers they will cancel and thus in some cases we
2147 2148 2149 2150 2151 2152 2153
        ///       may be effectively cutting off some diagnostics.
        ///       It is not clear if behavior is desirable.
        ///       See: https://github.com/dotnet/roslyn/issues/11470
        /// </summary>
        /// <param name="filterTree">What tree to complete. null means complete all trees. </param>
        internal abstract void CompleteTrees(SyntaxTree filterTree);

T
Tomas Matousek 已提交
2154 2155
        internal bool Compile(
            CommonPEModuleBuilder moduleBuilder,
2156
            bool emittingPdb,
T
Tomas Matousek 已提交
2157 2158 2159 2160 2161 2162
            DiagnosticBag diagnostics,
            Predicate<ISymbol> filterOpt,
            CancellationToken cancellationToken)
        {
            try
            {
C
Charles Stoner 已提交
2163
                return CompileMethods(
T
Tomas Matousek 已提交
2164
                    moduleBuilder,
2165
                    emittingPdb,
2166 2167 2168 2169 2170
                    emitMetadataOnly: false,
                    emitTestCoverageData: false,
                    diagnostics: diagnostics,
                    filterOpt: filterOpt,
                    cancellationToken: cancellationToken);
T
Tomas Matousek 已提交
2171 2172 2173 2174 2175 2176 2177 2178 2179
            }
            finally
            {
                moduleBuilder.CompilationFinished();
            }
        }

        internal void EnsureAnonymousTypeTemplates(CancellationToken cancellationToken)
        {
2180 2181
            Debug.Assert(IsSubmission);

T
Tomas Matousek 已提交
2182 2183 2184 2185 2186 2187 2188 2189
            if (this.GetSubmissionSlotIndex() >= 0 && HasCodeToEmit())
            {
                if (!this.CommonAnonymousTypeManager.AreTemplatesSealed)
                {
                    var discardedDiagnostics = DiagnosticBag.GetInstance();

                    var moduleBeingBuilt = this.CreateModuleBuilder(
                        emitOptions: EmitOptions.Default,
2190
                        debugEntryPoint: null,
T
Tomas Matousek 已提交
2191
                        manifestResources: null,
2192
                        sourceLinkStream: null,
2193
                        embeddedTexts: null,
T
Tomas Matousek 已提交
2194 2195 2196 2197 2198 2199 2200 2201 2202
                        testData: null,
                        diagnostics: discardedDiagnostics,
                        cancellationToken: cancellationToken);

                    if (moduleBeingBuilt != null)
                    {
                        Compile(
                            moduleBeingBuilt,
                            diagnostics: discardedDiagnostics,
C
Charles Stoner 已提交
2203
                            emittingPdb: false,
T
Tomas Matousek 已提交
2204 2205 2206 2207 2208 2209 2210 2211 2212
                            filterOpt: null,
                            cancellationToken: cancellationToken);
                    }

                    discardedDiagnostics.Free();
                }

                Debug.Assert(this.CommonAnonymousTypeManager.AreTemplatesSealed);
            }
V
Vladimir Reshetnikov 已提交
2213
            else
T
Tomas Matousek 已提交
2214
            {
2215
                this.ScriptCompilationInfo.PreviousScriptCompilation?.EnsureAnonymousTypeTemplates(cancellationToken);
T
Tomas Matousek 已提交
2216 2217 2218
            }
        }

2219
        // 1.0 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230
        [EditorBrowsable(EditorBrowsableState.Never)]
        public EmitResult Emit(
            Stream peStream,
            Stream pdbStream,
            Stream xmlDocumentationStream,
            Stream win32Resources,
            IEnumerable<ResourceDescription> manifestResources,
            EmitOptions options,
            CancellationToken cancellationToken)
        {
            return Emit(
2231
                peStream,
2232 2233 2234 2235 2236
                pdbStream,
                xmlDocumentationStream,
                win32Resources,
                manifestResources,
                options,
2237 2238 2239
                default(IMethodSymbol),
                default(Stream),
                default(IEnumerable<EmbeddedText>),
2240 2241 2242
                cancellationToken);
        }

2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263
        // 1.3 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
        [EditorBrowsable(EditorBrowsableState.Never)]
        public EmitResult Emit(
            Stream peStream,
            Stream pdbStream,
            Stream xmlDocumentationStream,
            Stream win32Resources,
            IEnumerable<ResourceDescription> manifestResources,
            EmitOptions options,
            IMethodSymbol debugEntryPoint,
            CancellationToken cancellationToken)
        {
            return Emit(
                peStream,
                pdbStream,
                xmlDocumentationStream,
                win32Resources,
                manifestResources,
                options,
                debugEntryPoint,
                default(Stream),
2264
                default(IEnumerable<EmbeddedText>),
2265 2266 2267
                cancellationToken);
        }

2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290
        // 2.0 BACKCOMPAT OVERLOAD -- DO NOT TOUCH
        public EmitResult Emit(
            Stream peStream,
            Stream pdbStream,
            Stream xmlDocumentationStream,
            Stream win32Resources,
            IEnumerable<ResourceDescription> manifestResources,
            EmitOptions options,
            IMethodSymbol debugEntryPoint,
            Stream sourceLinkStream,
            IEnumerable<EmbeddedText> embeddedTexts,
            CancellationToken cancellationToken)
        {
            return Emit(
                peStream,
                pdbStream,
                xmlDocumentationStream,
                win32Resources,
                manifestResources,
                options,
                debugEntryPoint,
                sourceLinkStream,
                embeddedTexts,
2291
                metadataPEStream: null,
2292 2293 2294
                cancellationToken: cancellationToken);
        }

2295 2296 2297 2298
        /// <summary>
        /// Emit the IL for the compiled source code into the specified stream.
        /// </summary>
        /// <param name="peStream">Stream to which the compilation will be written.</param>
2299
        /// <param name="metadataPEStream">Stream to which the metadata-only output will be written.</param>
2300 2301
        /// <param name="pdbStream">Stream to which the compilation's debug info will be written.  Null to forego PDB generation.</param>
        /// <param name="xmlDocumentationStream">Stream to which the compilation's XML documentation will be written.  Null to forego XML generation.</param>
2302
        /// <param name="win32Resources">Stream from which the compilation's Win32 resources will be read (in RES format).
2303 2304 2305 2306 2307
        /// Null to indicate that there are none. The RES format begins with a null resource entry.</param>
        /// <param name="manifestResources">List of the compilation's managed resources.  Null to indicate that there are none.</param>
        /// <param name="options">Emit options.</param>
        /// <param name="debugEntryPoint">
        /// Debug entry-point of the assembly. The method token is stored in the generated PDB stream.
2308
        ///
2309 2310
        /// When a program launches with a debugger attached the debugger places the first breakpoint to the start of the debug entry-point method.
        /// The CLR starts executing the static Main method of <see cref="CompilationOptions.MainTypeName"/> type. When the first breakpoint is hit
2311
        /// the debugger steps thru the code statement by statement until user code is reached, skipping methods marked by <see cref="DebuggerHiddenAttribute"/>,
2312
        /// and taking other debugging attributes into consideration.
2313
        ///
2314 2315 2316
        /// By default both entry points in an executable program (<see cref="OutputKind.ConsoleApplication"/>, <see cref="OutputKind.WindowsApplication"/>, <see cref="OutputKind.WindowsRuntimeApplication"/>)
        /// are the same method (Main). A non-executable program has no entry point. Runtimes that implement a custom loader may specify debug entry-point
        /// to force the debugger to skip over complex custom loader logic executing at the beginning of the .exe and thus improve debugging experience.
2317 2318
        ///
        /// Unlike ordinary entry-point which is limited to a non-generic static method of specific signature, there are no restrictions on the <paramref name="debugEntryPoint"/>
2319 2320
        /// method other than having a method body (extern, interface, or abstract methods are not allowed).
        /// </param>
2321 2322 2323
        /// <param name="sourceLinkStream">
        /// Stream containing information linking the compilation to a source control.
        /// </param>
2324 2325 2326 2327
        /// <param name="embeddedTexts">
        /// Texts to embed in the PDB.
        /// Only supported when emitting Portable PDBs.
        /// </param>
2328
        /// <param name="cancellationToken">To cancel the emit process.</param>
T
Tomas Matousek 已提交
2329 2330 2331 2332 2333 2334 2335
        public EmitResult Emit(
            Stream peStream,
            Stream pdbStream = null,
            Stream xmlDocumentationStream = null,
            Stream win32Resources = null,
            IEnumerable<ResourceDescription> manifestResources = null,
            EmitOptions options = null,
2336
            IMethodSymbol debugEntryPoint = null,
2337
            Stream sourceLinkStream = null,
2338
            IEnumerable<EmbeddedText> embeddedTexts = null,
2339
            Stream metadataPEStream = null,
T
Tomas Matousek 已提交
2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (peStream == null)
            {
                throw new ArgumentNullException(nameof(peStream));
            }

            if (!peStream.CanWrite)
            {
                throw new ArgumentException(CodeAnalysisResources.StreamMustSupportWrite, nameof(peStream));
            }

2352
            if (pdbStream != null)
T
Tomas Matousek 已提交
2353
            {
2354 2355 2356 2357 2358 2359 2360 2361 2362
                if (options?.DebugInformationFormat == DebugInformationFormat.Embedded)
                {
                    throw new ArgumentException(CodeAnalysisResources.PdbStreamUnexpectedWhenEmbedding, nameof(pdbStream));
                }

                if (!pdbStream.CanWrite)
                {
                    throw new ArgumentException(CodeAnalysisResources.StreamMustSupportWrite, nameof(pdbStream));
                }
2363 2364 2365 2366 2367 2368 2369

                if (options?.EmitMetadataOnly == true)
                {
                    throw new ArgumentException(CodeAnalysisResources.PdbStreamUnexpectedWhenEmittingMetadataOnly, nameof(pdbStream));
                }
            }

2370
            if (metadataPEStream != null && options?.EmitMetadataOnly == true)
2371
            {
2372 2373 2374
                throw new ArgumentException(CodeAnalysisResources.MetadataPeStreamUnexpectedWhenEmittingMetadataOnly, nameof(metadataPEStream));
            }

2375 2376 2377 2378 2379
            if (metadataPEStream != null && options?.IncludePrivateMembers == true)
            {
                throw new ArgumentException(CodeAnalysisResources.IncludingPrivateMembersUnexpectedWhenEmittingToMetadataPeStream, nameof(metadataPEStream));
            }

2380
            if (metadataPEStream == null && options?.EmitMetadataOnly == false)
2381
            {
2382 2383
                // EmitOptions used to default to IncludePrivateMembers=false, so to preserve binary compatibility we silently correct that unless emitting regular assemblies
                options = options.WithIncludePrivateMembers(true);
2384 2385
            }

2386 2387 2388 2389
            if (options?.DebugInformationFormat == DebugInformationFormat.Embedded &&
                options?.EmitMetadataOnly == true)
            {
                throw new ArgumentException(CodeAnalysisResources.EmbeddingPdbUnexpectedWhenEmittingMetadata, nameof(metadataPEStream));
2390 2391 2392 2393
            }

            if (this.Options.OutputKind == OutputKind.NetModule)
            {
2394
                if (metadataPEStream != null)
2395
                {
2396
                    throw new ArgumentException(CodeAnalysisResources.CannotTargetNetModuleWhenEmittingRefAssembly, nameof(metadataPEStream));
2397 2398 2399 2400 2401
                }
                else if (options?.EmitMetadataOnly == true)
                {
                    throw new ArgumentException(CodeAnalysisResources.CannotTargetNetModuleWhenEmittingRefAssembly, nameof(options.EmitMetadataOnly));
                }
T
Tomas Matousek 已提交
2402 2403
            }

2404 2405 2406 2407 2408 2409 2410 2411
            if (win32Resources != null)
            {
                if (!win32Resources.CanRead || !win32Resources.CanSeek)
                {
                    throw new ArgumentException(CodeAnalysisResources.StreamMustSupportReadAndSeek, nameof(win32Resources));
                }
            }

2412
            if (sourceLinkStream != null && !sourceLinkStream.CanRead)
2413
            {
2414
                throw new ArgumentException(CodeAnalysisResources.StreamMustSupportRead, nameof(sourceLinkStream));
2415
            }
2416

2417 2418 2419
            if (embeddedTexts != null &&
                !embeddedTexts.IsEmpty() &&
                pdbStream == null &&
2420
                options?.DebugInformationFormat != DebugInformationFormat.Embedded)
2421
            {
2422
                throw new ArgumentException(CodeAnalysisResources.EmbeddedTextsRequirePdb, nameof(embeddedTexts));
2423
            }
2424

T
Tomas Matousek 已提交
2425
            return Emit(
J
Jared Parsons 已提交
2426
                peStream,
2427
                metadataPEStream,
J
Jared Parsons 已提交
2428
                pdbStream,
2429 2430 2431 2432
                xmlDocumentationStream,
                win32Resources,
                manifestResources,
                options,
2433
                debugEntryPoint,
2434
                sourceLinkStream,
2435
                embeddedTexts,
J
Jared Parsons 已提交
2436
                testData: null,
T
Tomas Matousek 已提交
2437 2438 2439
                cancellationToken: cancellationToken);
        }

2440 2441 2442 2443 2444 2445
        /// <summary>
        /// This overload is only intended to be directly called by tests that want to pass <paramref name="testData"/>.
        /// The map is used for storing a list of methods and their associated IL.
        /// </summary>
        internal EmitResult Emit(
            Stream peStream,
2446
            Stream metadataPEStream,
2447 2448 2449 2450 2451
            Stream pdbStream,
            Stream xmlDocumentationStream,
            Stream win32Resources,
            IEnumerable<ResourceDescription> manifestResources,
            EmitOptions options,
2452
            IMethodSymbol debugEntryPoint,
2453
            Stream sourceLinkStream,
2454
            IEnumerable<EmbeddedText> embeddedTexts,
2455 2456 2457
            CompilationTestData testData,
            CancellationToken cancellationToken)
        {
2458 2459
            options = options ?? EmitOptions.Default.WithIncludePrivateMembers(metadataPEStream == null);
            bool embedPdb = options.DebugInformationFormat == DebugInformationFormat.Embedded;
2460
            Debug.Assert(!embedPdb || pdbStream == null);
2461
            Debug.Assert(metadataPEStream == null || !options.IncludePrivateMembers); // you may not use a secondary stream and include private members together
2462

C
Charles Stoner 已提交
2463 2464 2465 2466
            var diagnostics = DiagnosticBag.GetInstance();

            var moduleBeingBuilt = CheckOptionsAndCreateModuleBuilder(
                diagnostics,
2467 2468
                manifestResources,
                options,
2469
                debugEntryPoint,
2470
                sourceLinkStream,
2471
                embeddedTexts,
2472 2473
                testData,
                cancellationToken);
C
Charles Stoner 已提交
2474 2475 2476 2477 2478 2479 2480 2481 2482

            bool success = false;

            if (moduleBeingBuilt != null)
            {
                try
                {
                    success = CompileMethods(
                        moduleBeingBuilt,
2483
                        emittingPdb: pdbStream != null || embedPdb,
2484 2485
                        emitMetadataOnly: options.EmitMetadataOnly,
                        emitTestCoverageData: options.EmitTestCoverageData,
2486
                        diagnostics: diagnostics,
C
Charles Stoner 已提交
2487 2488 2489
                        filterOpt: null,
                        cancellationToken: cancellationToken);

2490
                    if (!options.EmitMetadataOnly)
C
Charles Stoner 已提交
2491
                    {
C
Charles Stoner 已提交
2492
                        if (!GenerateResourcesAndDocumentationComments(
C
Charles Stoner 已提交
2493 2494 2495
                            moduleBeingBuilt,
                            xmlDocumentationStream,
                            win32Resources,
2496
                            options.OutputNameOverride,
C
Charles Stoner 已提交
2497
                            diagnostics,
C
Charles Stoner 已提交
2498 2499 2500 2501
                            cancellationToken))
                        {
                            success = false;
                        }
C
Charles Stoner 已提交
2502 2503 2504 2505 2506

                        if (success)
                        {
                            ReportUnusedImports(null, diagnostics, cancellationToken);
                        }
D
dotnet-bot 已提交
2507
                    }
C
Charles Stoner 已提交
2508 2509 2510 2511 2512 2513
                }
                finally
                {
                    moduleBeingBuilt.CompilationFinished();
                }

2514
                RSAParameters? privateKeyOpt = null;
J
Jared Parsons 已提交
2515
                if (Options.StrongNameProvider != null && SignUsingBuilder && !Options.PublicSign)
2516 2517 2518 2519
                {
                    privateKeyOpt = StrongNameKeys.PrivateKey;
                }

C
Charles Stoner 已提交
2520 2521 2522 2523 2524
                if (success)
                {
                    success = SerializeToPeStream(
                        moduleBeingBuilt,
                        new SimpleEmitStreamProvider(peStream),
2525
                        (metadataPEStream != null) ? new SimpleEmitStreamProvider(metadataPEStream) : null,
C
Charles Stoner 已提交
2526 2527 2528
                        (pdbStream != null) ? new SimpleEmitStreamProvider(pdbStream) : null,
                        testData?.SymWriterFactory,
                        diagnostics,
2529 2530 2531
                        metadataOnly: options.EmitMetadataOnly,
                        includePrivateMembers: options.IncludePrivateMembers,
                        emitTestCoverageData: options.EmitTestCoverageData,
2532
                        pePdbFilePath: options.PdbFilePath,
2533
                        privateKeyOpt: privateKeyOpt,
C
Charles Stoner 已提交
2534 2535 2536 2537 2538
                        cancellationToken: cancellationToken);
                }
            }

            return new EmitResult(success, diagnostics.ToReadOnlyAndFree());
2539 2540
        }

T
Tomas Matousek 已提交
2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622
        /// <summary>
        /// Emit the differences between the compilation and the previous generation
        /// for Edit and Continue. The differences are expressed as added and changed
        /// symbols, and are emitted as metadata, IL, and PDB deltas. A representation
        /// of the current compilation is returned as an EmitBaseline for use in a
        /// subsequent Edit and Continue.
        /// </summary>
        public EmitDifferenceResult EmitDifference(
            EmitBaseline baseline,
            IEnumerable<SemanticEdit> edits,
            Stream metadataStream,
            Stream ilStream,
            Stream pdbStream,
            ICollection<MethodDefinitionHandle> updatedMethods,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            return EmitDifference(baseline, edits, s => false, metadataStream, ilStream, pdbStream, updatedMethods, cancellationToken);
        }

        /// <summary>
        /// Emit the differences between the compilation and the previous generation
        /// for Edit and Continue. The differences are expressed as added and changed
        /// symbols, and are emitted as metadata, IL, and PDB deltas. A representation
        /// of the current compilation is returned as an EmitBaseline for use in a
        /// subsequent Edit and Continue.
        /// </summary>
        public EmitDifferenceResult EmitDifference(
            EmitBaseline baseline,
            IEnumerable<SemanticEdit> edits,
            Func<ISymbol, bool> isAddedSymbol,
            Stream metadataStream,
            Stream ilStream,
            Stream pdbStream,
            ICollection<MethodDefinitionHandle> updatedMethods,
            CancellationToken cancellationToken = default(CancellationToken))
        {
            if (baseline == null)
            {
                throw new ArgumentNullException(nameof(baseline));
            }

            // TODO: check if baseline is an assembly manifest module/netmodule
            // Do we support EnC on netmodules?

            if (edits == null)
            {
                throw new ArgumentNullException(nameof(edits));
            }

            if (isAddedSymbol == null)
            {
                throw new ArgumentNullException(nameof(isAddedSymbol));
            }

            if (metadataStream == null)
            {
                throw new ArgumentNullException(nameof(metadataStream));
            }

            if (ilStream == null)
            {
                throw new ArgumentNullException(nameof(ilStream));
            }

            if (pdbStream == null)
            {
                throw new ArgumentNullException(nameof(pdbStream));
            }

            return this.EmitDifference(baseline, edits, isAddedSymbol, metadataStream, ilStream, pdbStream, updatedMethods, null, cancellationToken);
        }

        internal abstract EmitDifferenceResult EmitDifference(
            EmitBaseline baseline,
            IEnumerable<SemanticEdit> edits,
            Func<ISymbol, bool> isAddedSymbol,
            Stream metadataStream,
            Stream ilStream,
            Stream pdbStream,
            ICollection<MethodDefinitionHandle> updatedMethodHandles,
            CompilationTestData testData,
            CancellationToken cancellationToken);
2623

C
Charles Stoner 已提交
2624 2625 2626 2627 2628 2629
        /// <summary>
        /// Check compilation options and create <see cref="CommonPEModuleBuilder"/>.
        /// </summary>
        /// <returns><see cref="CommonPEModuleBuilder"/> if successful.</returns>
        internal CommonPEModuleBuilder CheckOptionsAndCreateModuleBuilder(
            DiagnosticBag diagnostics,
2630 2631
            IEnumerable<ResourceDescription> manifestResources,
            EmitOptions options,
2632
            IMethodSymbol debugEntryPoint,
2633
            Stream sourceLinkStream,
2634
            IEnumerable<EmbeddedText> embeddedTexts,
2635
            CompilationTestData testData,
M
Manish Vasani 已提交
2636
            CancellationToken cancellationToken)
2637
        {
2638
            options.ValidateOptions(diagnostics, MessageProvider, Options.Deterministic);
T
Tomas Matousek 已提交
2639

2640 2641 2642 2643 2644
            if (debugEntryPoint != null)
            {
                ValidateDebugEntryPoint(debugEntryPoint, diagnostics);
            }

2645 2646 2647
            if (Options.OutputKind == OutputKind.NetModule && manifestResources != null)
            {
                foreach (ResourceDescription res in manifestResources)
T
Tomas Matousek 已提交
2648
                {
2649
                    if (res.FileName != null)
T
Tomas Matousek 已提交
2650
                    {
2651 2652
                        // Modules can have only embedded resources, not linked ones.
                        diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_ResourceInModule, Location.None));
T
Tomas Matousek 已提交
2653 2654
                    }
                }
2655
            }
T
Tomas Matousek 已提交
2656

2657
            if (CommonCompiler.HasUnsuppressedErrors(diagnostics))
2658
            {
C
Charles Stoner 已提交
2659
                return null;
2660
            }
T
Tomas Matousek 已提交
2661

2662 2663 2664 2665 2666 2667
            // 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())
            {
                // Still report diagnostics since downstream submissions will assume there are no errors.
                diagnostics.AddRange(this.GetDiagnostics());
C
Charles Stoner 已提交
2668
                return null;
2669 2670
            }

C
Charles Stoner 已提交
2671
            return this.CreateModuleBuilder(
2672
                options,
2673
                debugEntryPoint,
2674
                sourceLinkStream,
2675
                embeddedTexts,
2676 2677 2678
                manifestResources,
                testData,
                diagnostics,
M
Manish Vasani 已提交
2679
                cancellationToken);
T
Tomas Matousek 已提交
2680 2681
        }

2682 2683
        internal abstract void ValidateDebugEntryPoint(IMethodSymbol debugEntryPoint, DiagnosticBag diagnostics);

2684
        internal bool IsEmitDeterministic => this.Options.Deterministic;
T
Tomas Matousek 已提交
2685

2686 2687
        internal bool SerializeToPeStream(
            CommonPEModuleBuilder moduleBeingBuilt,
J
Jared Parsons 已提交
2688
            EmitStreamProvider peStreamProvider,
2689
            EmitStreamProvider metadataPEStreamProvider,
2690
            EmitStreamProvider pdbStreamProvider,
2691
            Func<ISymWriterMetadataProvider, SymUnmanagedWriter> testSymWriterFactory,
2692 2693
            DiagnosticBag diagnostics,
            bool metadataOnly,
2694 2695
            bool includePrivateMembers,
            bool emitTestCoverageData,
2696
            string pePdbFilePath,
2697
            RSAParameters? privateKeyOpt,
2698 2699
            CancellationToken cancellationToken)
        {
2700
            cancellationToken.ThrowIfCancellationRequested();
T
Tomas Matousek 已提交
2701

2702 2703 2704
            Cci.PdbWriter nativePdbWriter = null;
            DiagnosticBag metadataDiagnostics = null;
            DiagnosticBag pdbBag = null;
T
Tomas Matousek 已提交
2705

T
Tomas Matousek 已提交
2706
            bool deterministic = IsEmitDeterministic;
2707 2708

            // PDB Stream provider should not be given if PDB is to be embedded into the PE file:
2709
            Debug.Assert(moduleBeingBuilt.DebugInformationFormat != DebugInformationFormat.Embedded || pdbStreamProvider == null);
2710

2711
            if (moduleBeingBuilt.DebugInformationFormat == DebugInformationFormat.Embedded || pdbStreamProvider != null)
2712 2713 2714
            {
                pePdbFilePath = pePdbFilePath ?? FileNameUtilities.ChangeExtension(SourceModule.Name, "pdb");
            }
2715 2716 2717 2718
            else
            {
                pePdbFilePath = null;
            }
2719 2720 2721

            if (moduleBeingBuilt.DebugInformationFormat == DebugInformationFormat.Embedded && !string.IsNullOrEmpty(pePdbFilePath))
            {
2722
                pePdbFilePath = PathUtilities.GetFileName(pePdbFilePath);
2723
            }
2724

2725 2726
            EmitStream emitPeStream = null;
            EmitStream emitMetadataStream = null;
2727 2728
            try
            {
2729
                var signKind = IsRealSigned
2730
                    ? (SignUsingBuilder ? EmitStreamSignKind.SignedWithBuilder : EmitStreamSignKind.SignedWithFile)
2731 2732 2733 2734 2735
                    : EmitStreamSignKind.None;
                emitPeStream = new EmitStream(peStreamProvider, signKind, Options.StrongNameProvider);
                emitMetadataStream = metadataPEStreamProvider == null
                    ? null
                    : new EmitStream(metadataPEStreamProvider, signKind, Options.StrongNameProvider);
2736 2737
                metadataDiagnostics = DiagnosticBag.GetInstance();

2738
                if (moduleBeingBuilt.DebugInformationFormat == DebugInformationFormat.Pdb && pdbStreamProvider != null)
T
Tomas Matousek 已提交
2739
                {
2740 2741 2742
                    // The algorithm must be specified for deterministic builds (checked earlier).
                    Debug.Assert(!deterministic || moduleBeingBuilt.PdbChecksumAlgorithm.Name != null);

2743
                    // The calls ISymUnmanagedWriter2.GetDebugInfo require a file name in order to succeed.  This is
2744 2745
                    // frequently used during PDB writing.  Ensure a name is provided here in the case we were given
                    // only a Stream value.
2746
                    nativePdbWriter = new Cci.PdbWriter(pePdbFilePath, testSymWriterFactory, deterministic ? moduleBeingBuilt.PdbChecksumAlgorithm : default);
2747 2748
                }

2749 2750 2751
                Func<Stream> getPortablePdbStream =
                    moduleBeingBuilt.DebugInformationFormat != DebugInformationFormat.PortablePdb || pdbStreamProvider == null
                    ? null
D
dotnet-bot 已提交
2752
                    : (Func<Stream>)(() => ConditionalGetOrCreateStream(pdbStreamProvider, metadataDiagnostics));
2753

2754 2755
                try
                {
2756
                    if (SerializePeToStream(
2757 2758
                        moduleBeingBuilt,
                        metadataDiagnostics,
2759
                        MessageProvider,
2760 2761
                        emitPeStream.GetCreateStreamFunc(metadataDiagnostics),
                        emitMetadataStream?.GetCreateStreamFunc(metadataDiagnostics),
2762
                        getPortablePdbStream,
2763
                        nativePdbWriter,
2764
                        pePdbFilePath,
2765
                        metadataOnly,
2766
                        includePrivateMembers,
2767
                        deterministic,
2768
                        emitTestCoverageData,
2769
                        privateKeyOpt,
2770
                        cancellationToken))
T
Tomas Matousek 已提交
2771
                    {
2772
                        if (nativePdbWriter != null)
2773
                        {
2774 2775
                            var nativePdbStream = pdbStreamProvider.GetOrCreateStream(metadataDiagnostics);
                            Debug.Assert(nativePdbStream != null || metadataDiagnostics.HasAnyErrors());
2776

2777
                            if (nativePdbStream != null)
2778
                            {
2779
                                nativePdbWriter.WriteTo(nativePdbStream);
2780 2781
                            }
                        }
T
Tomas Matousek 已提交
2782
                    }
2783
                }
2784
                catch (SymUnmanagedWriterException ex)
2785 2786 2787 2788
                {
                    diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PdbWritingFailed, Location.None, ex.Message));
                    return false;
                }
2789 2790
                catch (Cci.PeWritingException e)
                {
2791
                    diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PeWritingFailure, Location.None, e.InnerException.ToString()));
2792
                    return false;
2793
                }
2794 2795 2796 2797 2798 2799 2800 2801 2802 2803
                catch (ResourceException e)
                {
                    diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_CantReadResource, Location.None, e.Message, e.InnerException.Message));
                    return false;
                }
                catch (PermissionSetFileReadException e)
                {
                    diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PermissionSetAttributeFileReadError, Location.None, e.FileName, e.PropertyName, e.Message));
                    return false;
                }
T
Tomas Matousek 已提交
2804

2805
                // translate metadata errors.
M
Manish Vasani 已提交
2806
                if (!FilterAndAppendAndFreeDiagnostics(diagnostics, ref metadataDiagnostics))
2807 2808 2809
                {
                    return false;
                }
T
Tomas Matousek 已提交
2810

J
Jared Parsons 已提交
2811 2812 2813
                return
                    emitPeStream.Complete(StrongNameKeys, MessageProvider, diagnostics) &&
                    (emitMetadataStream?.Complete(StrongNameKeys, MessageProvider, diagnostics) ?? true);
T
Tomas Matousek 已提交
2814
            }
2815 2816
            finally
            {
2817
                nativePdbWriter?.Dispose();
J
Jared Parsons 已提交
2818 2819
                emitPeStream?.Close();
                emitMetadataStream?.Close();
2820 2821 2822
                pdbBag?.Free();
                metadataDiagnostics?.Free();
            }
T
Tomas Matousek 已提交
2823 2824
        }

2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836
        private static Stream ConditionalGetOrCreateStream(EmitStreamProvider metadataPEStreamProvider, DiagnosticBag metadataDiagnostics)
        {
            if (metadataDiagnostics.HasAnyErrors())
            {
                return null;
            }

            var auxStream = metadataPEStreamProvider.GetOrCreateStream(metadataDiagnostics);
            Debug.Assert(auxStream != null || metadataDiagnostics.HasAnyErrors());
            return auxStream;
        }

2837
        internal static bool SerializePeToStream(
2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849
            CommonPEModuleBuilder moduleBeingBuilt,
            DiagnosticBag metadataDiagnostics,
            CommonMessageProvider messageProvider,
            Func<Stream> getPeStream,
            Func<Stream> getMetadataPeStreamOpt,
            Func<Stream> getPortablePdbStreamOpt,
            Cci.PdbWriter nativePdbWriterOpt,
            string pdbPathOpt,
            bool metadataOnly,
            bool includePrivateMembers,
            bool isDeterministic,
            bool emitTestCoverageData,
2850
            RSAParameters? privateKeyOpt,
2851
            CancellationToken cancellationToken)
2852
        {
2853 2854 2855
            bool emitSecondaryAssembly = getMetadataPeStreamOpt != null;

            bool includePrivateMembersOnPrimaryOutput = metadataOnly ? includePrivateMembers : true;
2856
            bool deterministicPrimaryOutput = (metadataOnly && !includePrivateMembers) || isDeterministic;
2857
            if (!Cci.PeWriter.WritePeToStream(
2858
                new EmitContext(moduleBeingBuilt, null, metadataDiagnostics, metadataOnly, includePrivateMembersOnPrimaryOutput),
2859 2860 2861 2862 2863 2864
                messageProvider,
                getPeStream,
                getPortablePdbStreamOpt,
                nativePdbWriterOpt,
                pdbPathOpt,
                metadataOnly,
2865
                deterministicPrimaryOutput,
2866
                emitTestCoverageData,
2867
                privateKeyOpt,
2868 2869 2870 2871 2872 2873
                cancellationToken))
            {
                return false;
            }

            // produce the secondary output (ref assembly) if needed
2874
            if (emitSecondaryAssembly)
2875 2876
            {
                Debug.Assert(!metadataOnly);
2877
                Debug.Assert(!includePrivateMembers);
2878 2879

                if (!Cci.PeWriter.WritePeToStream(
2880
                    new EmitContext(moduleBeingBuilt, null, metadataDiagnostics, metadataOnly: true, includePrivateMembers: false),
2881 2882 2883 2884 2885 2886
                    messageProvider,
                    getMetadataPeStreamOpt,
                    getPortablePdbStreamOpt: null,
                    nativePdbWriterOpt: null,
                    pdbPathOpt: null,
                    metadataOnly: true,
2887
                    isDeterministic: true,
2888
                    emitTestCoverageData: false,
2889
                    privateKeyOpt: privateKeyOpt,
2890 2891 2892 2893 2894 2895 2896 2897 2898
                    cancellationToken: cancellationToken))
                {
                    return false;
                }
            }

            return true;
        }

2899 2900 2901 2902 2903 2904 2905 2906 2907 2908
        internal EmitBaseline SerializeToDeltaStreams(
            CommonPEModuleBuilder moduleBeingBuilt,
            EmitBaseline baseline,
            DefinitionMap definitionMap,
            SymbolChanges changes,
            Stream metadataStream,
            Stream ilStream,
            Stream pdbStream,
            ICollection<MethodDefinitionHandle> updatedMethods,
            DiagnosticBag diagnostics,
2909
            Func<ISymWriterMetadataProvider, SymUnmanagedWriter> testSymWriterFactory,
2910
            string pdbFilePath,
2911 2912
            CancellationToken cancellationToken)
        {
2913
            var nativePdbWriterOpt = (moduleBeingBuilt.DebugInformationFormat != DebugInformationFormat.Pdb) ? null :
2914
                new Cci.PdbWriter(
2915
                    pdbFilePath ?? FileNameUtilities.ChangeExtension(SourceModule.Name, "pdb"),
2916
                    testSymWriterFactory,
2917
                    hashAlgorithmNameOpt: default);
2918 2919

            using (nativePdbWriterOpt)
2920
            {
2921
                var context = new EmitContext(moduleBeingBuilt, null, diagnostics, metadataOnly: false, includePrivateMembers: true);
2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934
                var encId = Guid.NewGuid();

                try
                {
                    var writer = new DeltaMetadataWriter(
                        context,
                        MessageProvider,
                        baseline,
                        encId,
                        definitionMap,
                        changes,
                        cancellationToken);

2935 2936
                    writer.WriteMetadataAndIL(
                        nativePdbWriterOpt,
2937 2938
                        metadataStream,
                        ilStream,
2939
                        (nativePdbWriterOpt == null) ? pdbStream : null,
2940
                        out MetadataSizes metadataSizes);
2941

2942 2943
                    writer.GetMethodTokens(updatedMethods);

2944
                    nativePdbWriterOpt?.WriteTo(pdbStream);
2945

2946 2947
                    return diagnostics.HasAnyErrors() ? null : writer.GetDelta(baseline, this, encId, metadataSizes);
                }
2948
                catch (SymUnmanagedWriterException e)
2949 2950 2951 2952
                {
                    diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PdbWritingFailed, Location.None, e.Message));
                    return null;
                }
2953 2954 2955 2956 2957
                catch (Cci.PeWritingException e)
                {
                    diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PeWritingFailure, Location.None, e.InnerException.ToString()));
                    return null;
                }
2958 2959 2960 2961 2962 2963 2964 2965
                catch (PermissionSetFileReadException e)
                {
                    diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_PermissionSetAttributeFileReadError, Location.None, e.FileName, e.PropertyName, e.Message));
                    return null;
                }
            }
        }

T
Tomas Matousek 已提交
2966 2967 2968
        internal string Feature(string p)
        {
            string v;
2969
            return _features.TryGetValue(p, out v) ? v : null;
T
Tomas Matousek 已提交
2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991
        }

        #endregion

        private ConcurrentDictionary<SyntaxTree, SmallConcurrentSetOfInts> _lazyTreeToUsedImportDirectivesMap;
        private static readonly Func<SyntaxTree, SmallConcurrentSetOfInts> s_createSetCallback = t => new SmallConcurrentSetOfInts();

        private ConcurrentDictionary<SyntaxTree, SmallConcurrentSetOfInts> TreeToUsedImportDirectivesMap
        {
            get
            {
                return LazyInitializer.EnsureInitialized(ref _lazyTreeToUsedImportDirectivesMap);
            }
        }

        internal void MarkImportDirectiveAsUsed(SyntaxNode node)
        {
            MarkImportDirectiveAsUsed(node.SyntaxTree, node.Span.Start);
        }

        internal void MarkImportDirectiveAsUsed(SyntaxTree syntaxTree, int position)
        {
2992 2993
            // Optimization: Don't initialize TreeToUsedImportDirectivesMap in submissions.
            if (!IsSubmission && syntaxTree != null)
T
Tomas Matousek 已提交
2994 2995 2996 2997 2998 2999 3000 3001
            {
                var set = TreeToUsedImportDirectivesMap.GetOrAdd(syntaxTree, s_createSetCallback);
                set.Add(position);
            }
        }

        internal bool IsImportDirectiveUsed(SyntaxTree syntaxTree, int position)
        {
3002 3003 3004 3005 3006
            if (IsSubmission)
            {
                // Since usings apply to subsequent submissions, we have to assume they are used.
                return true;
            }
T
Tomas Matousek 已提交
3007

3008
            SmallConcurrentSetOfInts usedImports;
T
Tomas Matousek 已提交
3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028
            return syntaxTree != null &&
                TreeToUsedImportDirectivesMap.TryGetValue(syntaxTree, out usedImports) &&
                usedImports.Contains(position);
        }

        /// <summary>
        /// The compiler needs to define an ordering among different partial class in different syntax trees
        /// in some cases, because emit order for fields in structures, for example, is semantically important.
        /// This function defines an ordering among syntax trees in this compilation.
        /// </summary>
        internal int CompareSyntaxTreeOrdering(SyntaxTree tree1, SyntaxTree tree2)
        {
            if (tree1 == tree2)
            {
                return 0;
            }

            Debug.Assert(this.ContainsSyntaxTree(tree1));
            Debug.Assert(this.ContainsSyntaxTree(tree2));

3029
            return this.GetSyntaxTreeOrdinal(tree1) - this.GetSyntaxTreeOrdinal(tree2);
T
Tomas Matousek 已提交
3030 3031
        }

3032
        internal abstract int GetSyntaxTreeOrdinal(SyntaxTree tree);
T
Tomas Matousek 已提交
3033 3034

        /// <summary>
3035
        /// Compare two source locations, using their containing trees, and then by Span.First within a tree.
T
Tomas Matousek 已提交
3036 3037 3038 3039
        /// Can be used to get a total ordering on declarations, for example.
        /// </summary>
        internal abstract int CompareSourceLocations(Location loc1, Location loc2);

3040 3041 3042 3043 3044 3045
        /// <summary>
        /// Compare two source locations, using their containing trees, and then by Span.First within a tree.
        /// Can be used to get a total ordering on declarations, for example.
        /// </summary>
        internal abstract int CompareSourceLocations(SyntaxReference loc1, SyntaxReference loc2);

T
Tomas Matousek 已提交
3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 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
        /// <summary>
        /// Return the lexically first of two locations.
        /// </summary>
        internal TLocation FirstSourceLocation<TLocation>(TLocation first, TLocation second)
            where TLocation : Location
        {
            if (CompareSourceLocations(first, second) <= 0)
            {
                return first;
            }
            else
            {
                return second;
            }
        }

        /// <summary>
        /// Return the lexically first of multiple locations.
        /// </summary>
        internal TLocation FirstSourceLocation<TLocation>(ImmutableArray<TLocation> locations)
            where TLocation : Location
        {
            if (locations.IsEmpty)
            {
                return null;
            }

            var result = locations[0];

            for (int i = 1; i < locations.Length; i++)
            {
                result = FirstSourceLocation(result, locations[i]);
            }

            return result;
        }

        #region Logging Helpers

        // Following helpers are used when logging ETW events. These helpers are invoked only if we are running
        // under an ETW listener that has requested 'verbose' logging. In other words, these helpers will never
        // be invoked in the 'normal' case (i.e. when the code is running on user's machine and no ETW listener
        // is involved).

        // Note: Most of the below helpers are unused at the moment - but we would like to keep them around in
        // case we decide we need more verbose logging in certain cases for debugging.
        internal string GetMessage(CompilationStage stage)
        {
            return string.Format("{0} ({1})", this.AssemblyName, stage.ToString());
        }

        internal string GetMessage(ITypeSymbol source, ITypeSymbol destination)
        {
            if (source == null || destination == null) return this.AssemblyName;
            return string.Format("{0}: {1} {2} -> {3} {4}", this.AssemblyName, source.TypeKind.ToString(), source.Name, destination.TypeKind.ToString(), destination.Name);
        }

        #endregion

        #region Declaration Name Queries

        /// <summary>
        /// Return true if there is a source declaration symbol name that meets given predicate.
        /// </summary>
        public abstract bool ContainsSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken));

        /// <summary>
        /// Return source declaration symbols whose name meets given predicate.
        /// </summary>
        public abstract IEnumerable<ISymbol> GetSymbolsWithName(Func<string, bool> predicate, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken));

3117
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
3118
        /// <summary>
3119
        /// Return true if there is a source declaration symbol name that matches the provided name.
3120 3121 3122
        /// This may be faster than <see cref="ContainsSymbolsWithName(Func{string, bool},
        /// SymbolFilter, CancellationToken)"/> when predicate is just a simple string check.
        /// <paramref name="name"/> is case sensitive or not depending on the target language.
3123
        /// </summary>
3124
        public abstract bool ContainsSymbolsWithName(string name, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken));
3125 3126

        /// <summary>
C
Cyrus Najmabadi 已提交
3127
        /// Return source declaration symbols whose name matches the provided name.  This may be
3128 3129 3130
        /// faster than <see cref="GetSymbolsWithName(Func{string, bool}, SymbolFilter,
        /// CancellationToken)"/> when predicate is just a simple string check.  <paramref
        /// name="name"/> is case sensitive or not depending on the target language.
3131
        /// </summary>
3132 3133
        public abstract IEnumerable<ISymbol> GetSymbolsWithName(string name, SymbolFilter filter = SymbolFilter.TypeAndMember, CancellationToken cancellationToken = default(CancellationToken));
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
3134

T
Tomas Matousek 已提交
3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171
        #endregion

        internal void MakeMemberMissing(WellKnownMember member)
        {
            MakeMemberMissing((int)member);
        }

        internal void MakeMemberMissing(SpecialMember member)
        {
            MakeMemberMissing(-(int)member - 1);
        }

        internal bool IsMemberMissing(WellKnownMember member)
        {
            return IsMemberMissing((int)member);
        }

        internal bool IsMemberMissing(SpecialMember member)
        {
            return IsMemberMissing(-(int)member - 1);
        }

        private void MakeMemberMissing(int member)
        {
            if (_lazyMakeMemberMissingMap == null)
            {
                _lazyMakeMemberMissingMap = new SmallDictionary<int, bool>();
            }

            _lazyMakeMemberMissingMap[member] = true;
        }

        private bool IsMemberMissing(int member)
        {
            return _lazyMakeMemberMissingMap != null && _lazyMakeMemberMissingMap.ContainsKey(member);
        }

3172 3173 3174 3175 3176
        internal void MakeTypeMissing(SpecialType type)
        {
            MakeTypeMissing((int)type);
        }

T
Tomas Matousek 已提交
3177
        internal void MakeTypeMissing(WellKnownType type)
3178 3179 3180 3181 3182
        {
            MakeTypeMissing((int)type);
        }

        private void MakeTypeMissing(int type)
T
Tomas Matousek 已提交
3183 3184 3185 3186 3187 3188 3189 3190 3191
        {
            if (_lazyMakeWellKnownTypeMissingMap == null)
            {
                _lazyMakeWellKnownTypeMissingMap = new SmallDictionary<int, bool>();
            }

            _lazyMakeWellKnownTypeMissingMap[(int)type] = true;
        }

3192 3193 3194 3195 3196
        internal bool IsTypeMissing(SpecialType type)
        {
            return IsTypeMissing((int)type);
        }

T
Tomas Matousek 已提交
3197
        internal bool IsTypeMissing(WellKnownType type)
3198 3199 3200 3201 3202
        {
            return IsTypeMissing((int)type);
        }

        private bool IsTypeMissing(int type)
T
Tomas Matousek 已提交
3203 3204 3205
        {
            return _lazyMakeWellKnownTypeMissingMap != null && _lazyMakeWellKnownTypeMissingMap.ContainsKey((int)type);
        }
3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217

        /// <summary>
        /// Given a <see cref="Diagnostic"/> reporting unreferenced <see cref="AssemblyIdentity"/>s, returns
        /// the actual <see cref="AssemblyIdentity"/> instances that were not referenced.
        /// </summary>
        public ImmutableArray<AssemblyIdentity> GetUnreferencedAssemblyIdentities(Diagnostic diagnostic)
        {
            if (diagnostic == null)
            {
                throw new ArgumentNullException(nameof(diagnostic));
            }

3218
            if (!IsUnreferencedAssemblyIdentityDiagnosticCode(diagnostic.Code))
3219
            {
C
CyrusNajmabadi 已提交
3220
                return ImmutableArray<AssemblyIdentity>.Empty;
3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234
            }

            var builder = ArrayBuilder<AssemblyIdentity>.GetInstance();

            foreach (var argument in diagnostic.Arguments)
            {
                if (argument is AssemblyIdentity id)
                {
                    builder.Add(id);
                }
            }

            return builder.ToImmutableAndFree();
        }
C
CyrusNajmabadi 已提交
3235

3236
        internal abstract bool IsUnreferencedAssemblyIdentityDiagnosticCode(int code);
3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265

        /// <summary>
        /// Returns the required language version found in a <see cref="Diagnostic"/>, if any is found.
        /// Returns null if none is found.
        /// </summary>
        public static string GetRequiredLanguageVersion(Diagnostic diagnostic)
        {
            if (diagnostic == null)
            {
                throw new ArgumentNullException(nameof(diagnostic));
            }

            bool found = false;
            string foundVersion = null;
            if (diagnostic.Arguments != null)
            {
                foreach (var argument in diagnostic.Arguments)
                {
                    if (argument is RequiredLanguageVersion versionDiagnostic)
                    {
                        Debug.Assert(!found); // only one required language version in a given diagnostic
                        found = true;
                        foundVersion = versionDiagnostic.ToString();
                    }
                }
            }

            return foundVersion;
        }
T
Tomas Matousek 已提交
3266
    }
T
Tomas Matousek 已提交
3267
}