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

using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
7

8
using Microsoft.CodeAnalysis.CSharp.Emit;
P
Pilchie 已提交
9
using Microsoft.CodeAnalysis.CSharp.Symbols;
10
using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE;
11
using Microsoft.CodeAnalysis.CSharp.Symbols.Retargeting;
12
using Microsoft.CodeAnalysis.Collections;
P
Pilchie 已提交
13 14 15 16 17 18 19 20 21 22 23 24 25 26 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 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CSharp
{
    using MetadataOrDiagnostic = System.Object;

    public partial class CSharpCompilation
    {
        /// <summary>
        /// ReferenceManager encapsulates functionality to create an underlying SourceAssemblySymbol 
        /// (with underlying ModuleSymbols) for Compilation and AssemblySymbols for referenced
        /// assemblies (with underlying ModuleSymbols) all properly linked together based on
        /// reference resolution between them.
        /// 
        /// ReferenceManager is also responsible for reuse of metadata readers for imported modules
        /// and assemblies as well as existing AssemblySymbols for referenced assemblies. In order
        /// to do that, it maintains global cache for metadata readers and AssemblySymbols
        /// associated with them. The cache uses WeakReferences to refer to the metadata readers and
        /// AssemblySymbols to allow memory and resources being reclaimed once they are no longer
        /// used. The tricky part about reusing existing AssemblySymbols is to find a set of
        /// AssemblySymbols that are created for the referenced assemblies, which (the
        /// AssemblySymbols from the set) are linked in a way, consistent with the reference
        /// resolution between the referenced assemblies.
        /// 
        /// When existing Compilation is used as a metadata reference, there are scenarios when its
        /// underlying SourceAssemblySymbol cannot be used to provide symbols in context of the new
        /// Compilation. Consider classic multi-targeting scenario: compilation C1 references v1 of
        /// Lib.dll and compilation C2 references C1 and v2 of Lib.dll. In this case,
        /// SourceAssemblySymbol for C1 is linked to AssemblySymbol for v1 of Lib.dll. However,
        /// given the set of references for C2, the same reference for C1 should be resolved against
        /// v2 of Lib.dll. In other words, in context of C2, all types from v1 of Lib.dll leaking
        /// through C1 (through method signatures, etc.) must be retargeted to the types from v2 of
        /// Lib.dll. In this case, ReferenceManager creates a special RetargetingAssemblySymbol for
        /// C1, which is responsible for the type retargeting. The RetargetingAssemblySymbols could
        /// also be reused for different Compilations, ReferenceManager maintains a cache of
        /// RetargetingAssemblySymbols (WeakReferences) for each Compilation.
        /// 
        /// The only public entry point of this class is CreateSourceAssembly() method.
        /// </summary>
        internal sealed class ReferenceManager : CommonReferenceManager<CSharpCompilation, AssemblySymbol>
        {
            public ReferenceManager(string simpleAssemblyName, AssemblyIdentityComparer identityComparer, Dictionary<MetadataReference, MetadataOrDiagnostic> observedMetadata)
                : base(simpleAssemblyName, identityComparer, observedMetadata)
            {
            }

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

            protected override AssemblyData CreateAssemblyDataForFile(
                PEAssembly assembly,
                WeakList<IAssemblySymbol> cachedSymbols,
                DocumentationProvider documentationProvider,
                string sourceAssemblySimpleName,
                MetadataImportOptions importOptions,
                bool embedInteropTypes)
            {
                return new AssemblyDataForFile(
                    assembly,
                    cachedSymbols,
                    embedInteropTypes,
                    documentationProvider,
                    sourceAssemblySimpleName,
                    importOptions);
            }

            protected override AssemblyData CreateAssemblyDataForCompilation(CompilationReference compilationReference)
            {
                var csReference = compilationReference as CSharpCompilationReference;
                if (csReference == null)
                {
                    throw new NotSupportedException(string.Format(CSharpResources.CantReferenceCompilationOf, compilationReference.GetType(), "C#"));
                }

                var result = new AssemblyDataForCompilation(csReference.Compilation, csReference.Properties.EmbedInteropTypes);
90
                Debug.Assert((object)csReference.Compilation._lazyAssemblySymbol != null);
P
Pilchie 已提交
91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168
                return result;
            }

            /// <summary>
            /// Checks if the properties of <paramref name="duplicateReference"/> are compatible with properties of <paramref name="primaryReference"/>.
            /// Reports inconsistencies to the given diagnostic bag.
            /// </summary>
            /// <returns>True if the properties are compatible and hence merged, false if the duplicate reference should not merge it's properties with primary reference.</returns>
            protected override bool CheckPropertiesConsistency(MetadataReference primaryReference, MetadataReference duplicateReference, DiagnosticBag diagnostics)
            {
                if (primaryReference.Properties.EmbedInteropTypes != duplicateReference.Properties.EmbedInteropTypes)
                {
                    diagnostics.Add(ErrorCode.ERR_AssemblySpecifiedForLinkAndRef, NoLocation.Singleton, duplicateReference.Display, primaryReference.Display);
                    return false;
                }

                return true;
            }

            /// <summary>
            /// C# only considers culture when comparing weak identities.
            /// It ignores versions of weak identities and reports an error if there are two weak assembly 
            /// references passed to a compilation that have the same simple name.
            /// </summary>
            protected override bool WeakIdentityPropertiesEquivalent(AssemblyIdentity identity1, AssemblyIdentity identity2)
            {
                Debug.Assert(AssemblyIdentityComparer.SimpleNameComparer.Equals(identity1.Name, identity2.Name));
                return AssemblyIdentityComparer.CultureComparer.Equals(identity1.CultureName, identity2.CultureName);
            }

            protected override AssemblySymbol[] GetActualBoundReferencesUsedBy(AssemblySymbol assemblySymbol)
            {
                var refs = new List<AssemblySymbol>();

                foreach (var module in assemblySymbol.Modules)
                {
                    refs.AddRange(module.GetReferencedAssemblySymbols());
                }

                for (int i = 0; i < refs.Count; i++)
                {
                    if (refs[i].IsMissing)
                    {
                        refs[i] = null; // Do not expose missing assembly symbols to ReferenceManager.Binder
                    }
                }

                return refs.ToArray();
            }

            protected override ImmutableArray<AssemblySymbol> GetNoPiaResolutionAssemblies(AssemblySymbol candidateAssembly)
            {
                if (candidateAssembly is SourceAssemblySymbol)
                {
                    // This is an optimization, if candidateAssembly links something or explicitly declares local type, 
                    // common reference binder shouldn't reuse this symbol because candidateAssembly won't be in the 
                    // set returned by GetNoPiaResolutionAssemblies(). This also makes things clearer.
                    return ImmutableArray<AssemblySymbol>.Empty;
                }

                return candidateAssembly.GetNoPiaResolutionAssemblies();
            }

            protected override bool IsLinked(AssemblySymbol candidateAssembly)
            {
                return candidateAssembly.IsLinked;
            }

            protected override AssemblySymbol GetCorLibrary(AssemblySymbol candidateAssembly)
            {
                AssemblySymbol corLibrary = candidateAssembly.CorLibrary;

                // Do not expose missing assembly symbols to ReferenceManager.Binder
                return corLibrary.IsMissing ? null : corLibrary;
            }

            public void CreateSourceAssemblyForCompilation(CSharpCompilation compilation)
            {
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183
                // We are reading the Reference Manager state outside of a lock by accessing 
                // IsBound and HasCircularReference properties.
                // Once isBound flag is flipped the state of the manager is available and doesn't change.
                // 
                // If two threads are building SourceAssemblySymbol and the first just updated 
                // set isBound flag to 1 but not yet set lazySourceAssemblySymbol,
                // the second thread may end up reusing the Reference Manager data the first thread calculated. 
                // That's ok since 
                // 1) the second thread would produce the same data,
                // 2) all results calculated by the second thread will be thrown away since the first thread 
                //    already acquired SymbolCacheAndReferenceManagerStateGuard that is needed to publish the data.

                // The given compilation is the first compilation that shares this manager and its symbols are requested.
                // Perform full reference resolution and binding.
                if (!IsBound && CreateAndSetSourceAssemblyFullBind(compilation))
P
Pilchie 已提交
184
                {
185 186 187 188 189 190 191 192 193 194 195 196 197
                    // we have successfully bound the references for the compilation
                }
                else if (!HasCircularReference)
                {
                    // Another compilation that shares the manager with the given compilation
                    // already bound its references and produced tables that we can use to construct 
                    // source assembly symbol faster. Unless we encountered a circular reference.
                    CreateAndSetSourceAssemblyReuseData(compilation);
                }
                else
                {
                    // We encountered a circular reference while binding the previous compilation.
                    // This compilation can't share bound references with other compilations. Create a new manager.
P
Pilchie 已提交
198

199
                    // NOTE: The CreateSourceAssemblyFullBind is going to replace compilation's reference manager with newManager.
P
Pilchie 已提交
200

201 202
                    var newManager = new ReferenceManager(this.SimpleAssemblyName, this.IdentityComparer, this.ObservedMetadata);
                    var successful = newManager.CreateAndSetSourceAssemblyFullBind(compilation);
P
Pilchie 已提交
203

204 205 206
                    // The new manager isn't shared with any other compilation so there is no other 
                    // thread but the current one could have initialized it.
                    Debug.Assert(successful);
P
Pilchie 已提交
207

208
                    newManager.AssertBound();
P
Pilchie 已提交
209
                }
210 211 212

                AssertBound();
                Debug.Assert((object)compilation._lazyAssemblySymbol != null);
P
Pilchie 已提交
213 214 215 216 217 218
            }

            /// <summary>
            /// Creates a <see cref="PEAssemblySymbol"/> from specified metadata. 
            /// </summary>
            /// <remarks>
219
            /// Used by EnC to create symbols for emit baseline. The PE symbols are used by <see cref="CSharpSymbolMatcher"/>.
P
Pilchie 已提交
220 221 222 223 224 225 226 227 228
            /// 
            /// The assembly references listed in the metadata AssemblyRef table are matched to the resolved references 
            /// stored on this <see cref="ReferenceManager"/>. Each AssemblyRef is matched against the assembly identities
            /// using an exact equality comparison. No unification or further resolution is performed.
            /// </remarks>
            public PEAssemblySymbol CreatePEAssemblyForAssemblyMetadata(AssemblyMetadata metadata, MetadataImportOptions importOptions)
            {
                AssertBound();

229 230 231
                // If the compilation has a reference from metadata to source assembly we can't share the referenced PE symbols.
                Debug.Assert(!HasCircularReference);

P
Pilchie 已提交
232 233 234 235 236 237
                var referencedAssembliesByIdentity = new Dictionary<AssemblyIdentity, AssemblySymbol>();
                foreach (var symbol in this.ReferencedAssemblies)
                {
                    referencedAssembliesByIdentity.Add(symbol.Identity, symbol);
                }

238
                var assembly = metadata.GetAssembly();
P
Pilchie 已提交
239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266
                var peReferences = assembly.AssemblyReferences.SelectAsArray(MapAssemblyIdentityToResolvedSymbol, referencedAssembliesByIdentity);
                var assemblySymbol = new PEAssemblySymbol(assembly, DocumentationProvider.Default, isLinked: false, importOptions: importOptions);

                var unifiedAssemblies = this.UnifiedAssemblies.WhereAsArray(unified => referencedAssembliesByIdentity.ContainsKey(unified.OriginalReference));
                InitializeAssemblyReuseData(assemblySymbol, peReferences, unifiedAssemblies);

                if (assembly.ContainsNoPiaLocalTypes())
                {
                    assemblySymbol.SetNoPiaResolutionAssemblies(this.ReferencedAssemblies);
                }

                return assemblySymbol;
            }

            private static AssemblySymbol MapAssemblyIdentityToResolvedSymbol(AssemblyIdentity identity, Dictionary<AssemblyIdentity, AssemblySymbol> map)
            {
                AssemblySymbol symbol;
                if (map.TryGetValue(identity, out symbol))
                {
                    return symbol;
                }
                return new MissingAssemblySymbol(identity);
            }

            private void CreateAndSetSourceAssemblyReuseData(CSharpCompilation compilation)
            {
                AssertBound();

267
                // If the compilation has a reference from metadata to source assembly we can't share the referenced PE symbols.
P
Pilchie 已提交
268 269 270 271 272
                Debug.Assert(!HasCircularReference);

                string moduleName = compilation.MakeSourceModuleName();
                var assemblySymbol = new SourceAssemblySymbol(compilation, this.SimpleAssemblyName, moduleName, this.ReferencedModules);

273
                InitializeAssemblyReuseData(assemblySymbol, this.ReferencedAssemblies, this.UnifiedAssemblies);
P
Pilchie 已提交
274

275
                if ((object)compilation._lazyAssemblySymbol == null)
P
Pilchie 已提交
276 277 278
                {
                    lock (SymbolCacheAndReferenceManagerStateGuard)
                    {
279
                        if ((object)compilation._lazyAssemblySymbol == null)
P
Pilchie 已提交
280
                        {
281 282
                            compilation._lazyAssemblySymbol = assemblySymbol;
                            Debug.Assert(ReferenceEquals(compilation._referenceManager, this));
P
Pilchie 已提交
283 284 285 286 287 288 289 290 291
                        }
                    }
                }
            }

            private void InitializeAssemblyReuseData(AssemblySymbol assemblySymbol, ImmutableArray<AssemblySymbol> referencedAssemblies, ImmutableArray<UnifiedAssembly<AssemblySymbol>> unifiedAssemblies)
            {
                AssertBound();

292
                assemblySymbol.SetCorLibrary(this.CorLibraryOpt ?? assemblySymbol);
P
Pilchie 已提交
293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309

                var sourceModuleReferences = new ModuleReferences<AssemblySymbol>(referencedAssemblies.SelectAsArray(a => a.Identity), referencedAssemblies, unifiedAssemblies);
                assemblySymbol.Modules[0].SetReferences(sourceModuleReferences);

                var assemblyModules = assemblySymbol.Modules;
                var referencedModulesReferences = this.ReferencedModulesReferences;
                Debug.Assert(assemblyModules.Length == referencedModulesReferences.Length + 1);

                for (int i = 1; i < assemblyModules.Length; i++)
                {
                    assemblyModules[i].SetReferences(referencedModulesReferences[i - 1]);
                }
            }

            // Returns false if another compilation sharing this manager finished binding earlier and we should reuse its results.
            private bool CreateAndSetSourceAssemblyFullBind(CSharpCompilation compilation)
            {
T
Tomas Matousek 已提交
310
                var resolutionDiagnostics = DiagnosticBag.GetInstance();
311 312
                var assemblyReferencesBySimpleName = PooledDictionary<string, List<ReferencedAssemblyIdentity>>.GetInstance();
                bool supersedeLowerVersions = compilation.IsSubmission;
313

P
Pilchie 已提交
314 315
                try
                {
316
                    IDictionary<ValueTuple<string, string>, MetadataReference> boundReferenceDirectiveMap;
T
Tomas Matousek 已提交
317 318 319 320 321 322
                    ImmutableArray<MetadataReference> boundReferenceDirectives;
                    ImmutableArray<AssemblyData> referencedAssemblies;
                    ImmutableArray<PEModule> modules; // To make sure the modules are not collected ahead of time.
                    ImmutableArray<MetadataReference> references;

                    ImmutableArray<ResolvedReference> referenceMap = ResolveMetadataReferences(
P
Pilchie 已提交
323
                        compilation,
324
                        assemblyReferencesBySimpleName,
P
Pilchie 已提交
325 326 327 328 329
                        out references,
                        out boundReferenceDirectiveMap,
                        out boundReferenceDirectives,
                        out referencedAssemblies,
                        out modules,
T
Tomas Matousek 已提交
330 331 332
                        resolutionDiagnostics);

                    var assemblyBeingBuiltData = new AssemblyDataForAssemblyBeingBuilt(new AssemblyIdentity(name: SimpleAssemblyName), referencedAssemblies, modules);
333
                    var explicitAssemblyData = referencedAssemblies.Insert(0, assemblyBeingBuiltData);
T
Tomas Matousek 已提交
334 335 336 337

                    // Let's bind all the references and resolve missing one (if resolver is available)
                    bool hasCircularReference;
                    int corLibraryIndex;
338 339 340 341
                    ImmutableArray<MetadataReference> implicitlyResolvedReferences;
                    ImmutableArray<ResolvedReference> implicitlyResolvedReferenceMap;
                    ImmutableArray<AssemblyData> allAssemblyData;

T
Tomas Matousek 已提交
342
                    BoundInputAssembly[] bindingResult = Bind(
343
                        explicitAssemblyData,
T
Tomas Matousek 已提交
344 345 346
                        modules,
                        references,
                        referenceMap,
T
Tomas Matousek 已提交
347 348
                        compilation.Options.MetadataReferenceResolver,
                        compilation.Options.MetadataImportOptions,
349 350
                        supersedeLowerVersions,
                        assemblyReferencesBySimpleName,
351 352 353
                        out allAssemblyData,
                        out implicitlyResolvedReferences,
                        out implicitlyResolvedReferenceMap,
T
Tomas Matousek 已提交
354 355 356 357 358 359
                        resolutionDiagnostics,
                        out hasCircularReference,
                        out corLibraryIndex);

                    Debug.Assert(bindingResult.Length == allAssemblyData.Length);

360 361 362
                    references = references.AddRange(implicitlyResolvedReferences);
                    referenceMap = referenceMap.AddRange(implicitlyResolvedReferenceMap);

T
Tomas Matousek 已提交
363 364 365
                    Dictionary<MetadataReference, int> referencedAssembliesMap, referencedModulesMap;
                    ImmutableArray<ImmutableArray<string>> aliasesOfReferencedAssemblies;
                    BuildReferencedAssembliesAndModulesMaps(
366
                        bindingResult,
T
Tomas Matousek 已提交
367 368 369
                        references,
                        referenceMap,
                        modules.Length,
370 371 372
                        referencedAssemblies.Length,
                        assemblyReferencesBySimpleName,
                        supersedeLowerVersions,
T
Tomas Matousek 已提交
373 374 375 376 377 378 379 380 381 382 383
                        out referencedAssembliesMap,
                        out referencedModulesMap,
                        out aliasesOfReferencedAssemblies);

                    // Create AssemblySymbols for assemblies that can't use any existing symbols.
                    var newSymbols = new List<int>();

                    for (int i = 1; i < bindingResult.Length; i++)
                    {
                        if ((object)bindingResult[i].AssemblySymbol == null)
                        {
384
                            // symbol hasn't been found in the cache, create a new one
T
Tomas Matousek 已提交
385
                            bindingResult[i].AssemblySymbol = ((AssemblyDataForMetadataOrCompilation)allAssemblyData[i]).CreateAssemblySymbol();
T
Tomas Matousek 已提交
386 387
                            newSymbols.Add(i);
                        }
P
Pilchie 已提交
388

T
Tomas Matousek 已提交
389 390
                        Debug.Assert(allAssemblyData[i].IsLinked == bindingResult[i].AssemblySymbol.IsLinked);
                    }
P
Pilchie 已提交
391

T
Tomas Matousek 已提交
392
                    var assemblySymbol = new SourceAssemblySymbol(compilation, SimpleAssemblyName, compilation.MakeSourceModuleName(), netModules: modules);
P
Pilchie 已提交
393

T
Tomas Matousek 已提交
394
                    AssemblySymbol corLibrary;
P
Pilchie 已提交
395

T
Tomas Matousek 已提交
396
                    if (corLibraryIndex == 0)
P
Pilchie 已提交
397
                    {
T
Tomas Matousek 已提交
398
                        corLibrary = assemblySymbol;
P
Pilchie 已提交
399
                    }
T
Tomas Matousek 已提交
400 401 402 403 404
                    else if (corLibraryIndex > 0)
                    {
                        corLibrary = bindingResult[corLibraryIndex].AssemblySymbol;
                    }
                    else
P
Pilchie 已提交
405
                    {
T
Tomas Matousek 已提交
406
                        corLibrary = MissingCorLibrarySymbol.Instance;
P
Pilchie 已提交
407 408
                    }

T
Tomas Matousek 已提交
409
                    assemblySymbol.SetCorLibrary(corLibrary);
P
Pilchie 已提交
410

T
Tomas Matousek 已提交
411 412 413
                    // Setup bound references for newly created AssemblySymbols
                    // This should be done after we created/found all AssemblySymbols 
                    Dictionary<AssemblyIdentity, MissingAssemblySymbol> missingAssemblies = null;
P
Pilchie 已提交
414

415 416 417
                    // -1 for assembly being built:
                    int totalReferencedAssemblyCount = allAssemblyData.Length - 1;

T
Tomas Matousek 已提交
418 419 420 421 422
                    // Setup bound references for newly created SourceAssemblySymbol
                    ImmutableArray<ModuleReferences<AssemblySymbol>> moduleReferences;
                    SetupReferencesForSourceAssembly(
                        assemblySymbol,
                        modules,
423
                        totalReferencedAssemblyCount,
T
Tomas Matousek 已提交
424 425 426
                        bindingResult,
                        ref missingAssemblies,
                        out moduleReferences);
P
Pilchie 已提交
427

T
Tomas Matousek 已提交
428
                    if (newSymbols.Count > 0)
P
Pilchie 已提交
429
                    {
T
Tomas Matousek 已提交
430 431 432 433 434 435
                        // Only if we detected that a referenced assembly refers to the assembly being built
                        // we allow the references to get a hold of the assembly being built.
                        if (hasCircularReference)
                        {
                            bindingResult[0].AssemblySymbol = assemblySymbol;
                        }
436

T
Tomas Matousek 已提交
437
                        InitializeNewSymbols(newSymbols, assemblySymbol, allAssemblyData, bindingResult, missingAssemblies);
P
Pilchie 已提交
438 439
                    }

T
Tomas Matousek 已提交
440
                    if ((object)compilation._lazyAssemblySymbol == null)
P
Pilchie 已提交
441
                    {
T
Tomas Matousek 已提交
442
                        lock (SymbolCacheAndReferenceManagerStateGuard)
P
Pilchie 已提交
443
                        {
T
Tomas Matousek 已提交
444
                            if ((object)compilation._lazyAssemblySymbol == null)
P
Pilchie 已提交
445
                            {
T
Tomas Matousek 已提交
446 447 448 449 450 451
                                if (IsBound)
                                {
                                    // Another thread has finished constructing AssemblySymbol for another compilation that shares this manager.
                                    // Drop the results and reuse the symbols that were created for the other compilation.
                                    return false;
                                }
P
Pilchie 已提交
452

T
Tomas Matousek 已提交
453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476
                                UpdateSymbolCacheNoLock(newSymbols, allAssemblyData, bindingResult);

                                InitializeNoLock(
                                    referencedAssembliesMap,
                                    referencedModulesMap,
                                    boundReferenceDirectiveMap,
                                    boundReferenceDirectives,
                                    hasCircularReference,
                                    resolutionDiagnostics.ToReadOnly(),
                                    ReferenceEquals(corLibrary, assemblySymbol) ? null : corLibrary,
                                    modules,
                                    moduleReferences,
                                    assemblySymbol.SourceModule.GetReferencedAssemblySymbols(),
                                    aliasesOfReferencedAssemblies,
                                    assemblySymbol.SourceModule.GetUnifiedAssemblies());

                                // Make sure that the given compilation holds on this instance of reference manager.
                                Debug.Assert(ReferenceEquals(compilation._referenceManager, this) || HasCircularReference);
                                compilation._referenceManager = this;

                                // Finally, publish the source symbol after all data have been written.
                                // Once lazyAssemblySymbol is non-null other readers might start reading the data written above.
                                compilation._lazyAssemblySymbol = assemblySymbol;
                            }
P
Pilchie 已提交
477 478 479
                        }
                    }

T
Tomas Matousek 已提交
480 481 482 483 484
                    return true;
                }
                finally
                {
                    resolutionDiagnostics.Free();
485
                    assemblyReferencesBySimpleName.Free();
T
Tomas Matousek 已提交
486
                }
P
Pilchie 已提交
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 515 516 517
            }

            private static void InitializeNewSymbols(
                List<int> newSymbols,
                SourceAssemblySymbol sourceAssembly,
                ImmutableArray<AssemblyData> assemblies,
                BoundInputAssembly[] bindingResult,
                Dictionary<AssemblyIdentity, MissingAssemblySymbol> missingAssemblies)
            {
                Debug.Assert(newSymbols.Count > 0);

                var corLibrary = sourceAssembly.CorLibrary;
                Debug.Assert((object)corLibrary != null);

                foreach (int i in newSymbols)
                {
                    var compilationData = assemblies[i] as AssemblyDataForCompilation;

                    if (compilationData != null)
                    {
                        SetupReferencesForRetargetingAssembly(bindingResult, i, ref missingAssemblies, sourceAssemblyDebugOnly: sourceAssembly);
                    }
                    else
                    {
                        var fileData = (AssemblyDataForFile)assemblies[i];
                        SetupReferencesForFileAssembly(fileData, bindingResult, i, ref missingAssemblies, sourceAssemblyDebugOnly: sourceAssembly);
                    }
                }

                // Setup CorLibrary and NoPia stuff for newly created assemblies

518
                var linkedReferencedAssembliesBuilder = ArrayBuilder<AssemblySymbol>.GetInstance();
P
Pilchie 已提交
519 520 521 522 523 524 525 526 527 528
                var noPiaResolutionAssemblies = sourceAssembly.Modules[0].GetReferencedAssemblySymbols();

                foreach (int i in newSymbols)
                {
                    if (assemblies[i].ContainsNoPiaLocalTypes)
                    {
                        bindingResult[i].AssemblySymbol.SetNoPiaResolutionAssemblies(noPiaResolutionAssemblies);
                    }

                    // Setup linked referenced assemblies.
529
                    linkedReferencedAssembliesBuilder.Clear();
P
Pilchie 已提交
530 531 532

                    if (assemblies[i].IsLinked)
                    {
533
                        linkedReferencedAssembliesBuilder.Add(bindingResult[i].AssemblySymbol);
P
Pilchie 已提交
534 535 536 537 538 539 540
                    }

                    foreach (var referenceBinding in bindingResult[i].ReferenceBinding)
                    {
                        if (referenceBinding.IsBound &&
                            assemblies[referenceBinding.DefinitionIndex].IsLinked)
                        {
541
                            linkedReferencedAssembliesBuilder.Add(
P
Pilchie 已提交
542 543 544 545
                                bindingResult[referenceBinding.DefinitionIndex].AssemblySymbol);
                        }
                    }

546
                    if (linkedReferencedAssembliesBuilder.Count > 0)
P
Pilchie 已提交
547
                    {
548 549
                        linkedReferencedAssembliesBuilder.RemoveDuplicates();
                        bindingResult[i].AssemblySymbol.SetLinkedReferencedAssemblies(linkedReferencedAssembliesBuilder.ToImmutable());
P
Pilchie 已提交
550 551 552 553 554
                    }

                    bindingResult[i].AssemblySymbol.SetCorLibrary(corLibrary);
                }

555 556
                linkedReferencedAssembliesBuilder.Free();

P
Pilchie 已提交
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
                if (missingAssemblies != null)
                {
                    foreach (var missingAssembly in missingAssemblies.Values)
                    {
                        missingAssembly.SetCorLibrary(corLibrary);
                    }
                }
            }

            private static void UpdateSymbolCacheNoLock(List<int> newSymbols, ImmutableArray<AssemblyData> assemblies, BoundInputAssembly[] bindingResult)
            {
                // Add new assembly symbols into the cache
                foreach (int i in newSymbols)
                {
                    var compilationData = assemblies[i] as AssemblyDataForCompilation;

                    if (compilationData != null)
                    {
                        compilationData.Compilation.CacheRetargetingAssemblySymbolNoLock(bindingResult[i].AssemblySymbol);
                    }
                    else
                    {
                        var fileData = (AssemblyDataForFile)assemblies[i];
                        fileData.CachedSymbols.Add((PEAssemblySymbol)bindingResult[i].AssemblySymbol);
                    }
                }
            }

            private static void SetupReferencesForRetargetingAssembly(
                BoundInputAssembly[] bindingResult,
                int bindingIndex,
                ref Dictionary<AssemblyIdentity, MissingAssemblySymbol> missingAssemblies,
                SourceAssemblySymbol sourceAssemblyDebugOnly)
            {
591
                var retargetingAssemblySymbol = (RetargetingAssemblySymbol)bindingResult[bindingIndex].AssemblySymbol;
P
Pilchie 已提交
592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702
                ImmutableArray<ModuleSymbol> modules = retargetingAssemblySymbol.Modules;
                int moduleCount = modules.Length;
                int refsUsed = 0;

                for (int j = 0; j < moduleCount; j++)
                {
                    ImmutableArray<AssemblyIdentity> referencedAssemblies =
                        retargetingAssemblySymbol.UnderlyingAssembly.Modules[j].GetReferencedAssemblies();

                    // For source module skip underlying linked references
                    if (j == 0)
                    {
                        ImmutableArray<AssemblySymbol> underlyingReferencedAssemblySymbols =
                            retargetingAssemblySymbol.UnderlyingAssembly.Modules[0].GetReferencedAssemblySymbols();

                        int linkedUnderlyingReferences = 0;
                        foreach (AssemblySymbol asm in underlyingReferencedAssemblySymbols)
                        {
                            if (asm.IsLinked)
                            {
                                linkedUnderlyingReferences++;
                            }
                        }

                        if (linkedUnderlyingReferences > 0)
                        {
                            var filteredReferencedAssemblies = new AssemblyIdentity[referencedAssemblies.Length - linkedUnderlyingReferences];
                            int newIndex = 0;

                            for (int k = 0; k < underlyingReferencedAssemblySymbols.Length; k++)
                            {
                                if (!underlyingReferencedAssemblySymbols[k].IsLinked)
                                {
                                    filteredReferencedAssemblies[newIndex] = referencedAssemblies[k];
                                    newIndex++;
                                }
                            }

                            Debug.Assert(newIndex == filteredReferencedAssemblies.Length);
                            referencedAssemblies = filteredReferencedAssemblies.AsImmutableOrNull();
                        }
                    }

                    int refsCount = referencedAssemblies.Length;
                    AssemblySymbol[] symbols = new AssemblySymbol[refsCount];
                    ArrayBuilder<UnifiedAssembly<AssemblySymbol>> unifiedAssemblies = null;

                    for (int k = 0; k < refsCount; k++)
                    {
                        var referenceBinding = bindingResult[bindingIndex].ReferenceBinding[refsUsed + k];
                        if (referenceBinding.IsBound)
                        {
                            symbols[k] = GetAssemblyDefinitionSymbol(bindingResult, referenceBinding, ref unifiedAssemblies);
                        }
                        else
                        {
                            symbols[k] = GetOrAddMissingAssemblySymbol(referencedAssemblies[k], ref missingAssemblies);
                        }
                    }

                    var moduleReferences = new ModuleReferences<AssemblySymbol>(referencedAssemblies, symbols.AsImmutableOrNull(), unifiedAssemblies.AsImmutableOrEmpty());
                    modules[j].SetReferences(moduleReferences, sourceAssemblyDebugOnly);

                    refsUsed += refsCount;
                }
            }

            private static void SetupReferencesForFileAssembly(
                AssemblyDataForFile fileData,
                BoundInputAssembly[] bindingResult,
                int bindingIndex,
                ref Dictionary<AssemblyIdentity, MissingAssemblySymbol> missingAssemblies,
                SourceAssemblySymbol sourceAssemblyDebugOnly)
            {
                var portableExecutableAssemblySymbol = (PEAssemblySymbol)bindingResult[bindingIndex].AssemblySymbol;

                ImmutableArray<ModuleSymbol> modules = portableExecutableAssemblySymbol.Modules;
                int moduleCount = modules.Length;
                int refsUsed = 0;

                for (int j = 0; j < moduleCount; j++)
                {
                    int moduleReferenceCount = fileData.Assembly.ModuleReferenceCounts[j];
                    var identities = new AssemblyIdentity[moduleReferenceCount];
                    var symbols = new AssemblySymbol[moduleReferenceCount];

                    fileData.AssemblyReferences.CopyTo(refsUsed, identities, 0, moduleReferenceCount);

                    ArrayBuilder<UnifiedAssembly<AssemblySymbol>> unifiedAssemblies = null;
                    for (int k = 0; k < moduleReferenceCount; k++)
                    {
                        var boundReference = bindingResult[bindingIndex].ReferenceBinding[refsUsed + k];
                        if (boundReference.IsBound)
                        {
                            symbols[k] = GetAssemblyDefinitionSymbol(bindingResult, boundReference, ref unifiedAssemblies);
                        }
                        else
                        {
                            symbols[k] = GetOrAddMissingAssemblySymbol(identities[k], ref missingAssemblies);
                        }
                    }

                    var moduleReferences = new ModuleReferences<AssemblySymbol>(identities.AsImmutableOrNull(), symbols.AsImmutableOrNull(), unifiedAssemblies.AsImmutableOrEmpty());
                    modules[j].SetReferences(moduleReferences, sourceAssemblyDebugOnly);

                    refsUsed += moduleReferenceCount;
                }
            }

            private static void SetupReferencesForSourceAssembly(
                SourceAssemblySymbol sourceAssembly,
T
Tomas Matousek 已提交
703
                ImmutableArray<PEModule> modules,
704
                int totalReferencedAssemblyCount,
P
Pilchie 已提交
705 706 707 708
                BoundInputAssembly[] bindingResult,
                ref Dictionary<AssemblyIdentity, MissingAssemblySymbol> missingAssemblies,
                out ImmutableArray<ModuleReferences<AssemblySymbol>> moduleReferences)
            {
T
Tomas Matousek 已提交
709 710
                var moduleSymbols = sourceAssembly.Modules;
                Debug.Assert(moduleSymbols.Length == 1 + modules.Length);
P
Pilchie 已提交
711

T
Tomas Matousek 已提交
712 713 714 715
                var moduleReferencesBuilder = (moduleSymbols.Length > 1) ? ArrayBuilder<ModuleReferences<AssemblySymbol>>.GetInstance() : null;

                int refsUsed = 0;
                for (int moduleIndex = 0; moduleIndex < moduleSymbols.Length; moduleIndex++)
P
Pilchie 已提交
716
                {
717
                    int refsCount = (moduleIndex == 0) ? totalReferencedAssemblyCount : modules[moduleIndex - 1].ReferencedAssemblies.Length;
T
Tomas Matousek 已提交
718

P
Pilchie 已提交
719 720 721 722 723 724 725 726 727 728 729 730 731 732
                    var identities = new AssemblyIdentity[refsCount];
                    var symbols = new AssemblySymbol[refsCount];

                    ArrayBuilder<UnifiedAssembly<AssemblySymbol>> unifiedAssemblies = null;

                    for (int k = 0; k < refsCount; k++)
                    {
                        var boundReference = bindingResult[0].ReferenceBinding[refsUsed + k];
                        if (boundReference.IsBound)
                        {
                            symbols[k] = GetAssemblyDefinitionSymbol(bindingResult, boundReference, ref unifiedAssemblies);
                        }
                        else
                        {
T
Tomas Matousek 已提交
733
                            symbols[k] = GetOrAddMissingAssemblySymbol(boundReference.ReferenceIdentity, ref missingAssemblies);
P
Pilchie 已提交
734
                        }
T
Tomas Matousek 已提交
735 736

                        identities[k] = boundReference.ReferenceIdentity;
P
Pilchie 已提交
737 738 739 740 741 742 743 744 745 746 747 748
                    }

                    var references = new ModuleReferences<AssemblySymbol>(
                        identities.AsImmutableOrNull(),
                        symbols.AsImmutableOrNull(),
                        unifiedAssemblies.AsImmutableOrEmpty());

                    if (moduleIndex > 0)
                    {
                        moduleReferencesBuilder.Add(references);
                    }

T
Tomas Matousek 已提交
749
                    moduleSymbols[moduleIndex].SetReferences(references, sourceAssembly);
P
Pilchie 已提交
750 751 752 753

                    refsUsed += refsCount;
                }

754
                moduleReferences = moduleReferencesBuilder.ToImmutableOrEmptyAndFree();
P
Pilchie 已提交
755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802
            }

            private static AssemblySymbol GetAssemblyDefinitionSymbol(
                BoundInputAssembly[] bindingResult,
                AssemblyReferenceBinding referenceBinding,
                ref ArrayBuilder<UnifiedAssembly<AssemblySymbol>> unifiedAssemblies)
            {
                Debug.Assert(referenceBinding.IsBound);

                var assembly = bindingResult[referenceBinding.DefinitionIndex].AssemblySymbol;
                Debug.Assert((object)assembly != null);

                if (referenceBinding.VersionDifference != 0)
                {
                    if (unifiedAssemblies == null)
                    {
                        unifiedAssemblies = new ArrayBuilder<UnifiedAssembly<AssemblySymbol>>();
                    }

                    unifiedAssemblies.Add(new UnifiedAssembly<AssemblySymbol>(assembly, referenceBinding.ReferenceIdentity));
                }

                return assembly;
            }

            private static MissingAssemblySymbol GetOrAddMissingAssemblySymbol(
                AssemblyIdentity assemblyIdentity,
                ref Dictionary<AssemblyIdentity, MissingAssemblySymbol> missingAssemblies)
            {
                MissingAssemblySymbol missingAssembly;

                if (missingAssemblies == null)
                {
                    missingAssemblies = new Dictionary<AssemblyIdentity, MissingAssemblySymbol>();
                }
                else if (missingAssemblies.TryGetValue(assemblyIdentity, out missingAssembly))
                {
                    return missingAssembly;
                }

                missingAssembly = new MissingAssemblySymbol(assemblyIdentity);
                missingAssemblies.Add(assemblyIdentity, missingAssembly);

                return missingAssembly;
            }

            private abstract class AssemblyDataForMetadataOrCompilation : AssemblyData
            {
803
                private List<AssemblySymbol> _assemblies;
804 805 806 807 808 809 810 811
                private readonly AssemblyIdentity _identity;
                private readonly ImmutableArray<AssemblyIdentity> _referencedAssemblies;
                private readonly bool _embedInteropTypes;

                protected AssemblyDataForMetadataOrCompilation(
                    AssemblyIdentity identity,
                    ImmutableArray<AssemblyIdentity> referencedAssemblies,
                    bool embedInteropTypes)
P
Pilchie 已提交
812
                {
813 814 815 816 817 818
                    Debug.Assert(identity != null);
                    Debug.Assert(!referencedAssemblies.IsDefault);

                    _embedInteropTypes = embedInteropTypes;
                    _identity = identity;
                    _referencedAssemblies = referencedAssemblies;
P
Pilchie 已提交
819 820
                }

821 822
                internal abstract AssemblySymbol CreateAssemblySymbol();

P
Pilchie 已提交
823 824 825 826
                public override AssemblyIdentity Identity
                {
                    get
                    {
827
                        return _identity;
P
Pilchie 已提交
828 829 830 831 832 833 834
                    }
                }

                public override IEnumerable<AssemblySymbol> AvailableSymbols
                {
                    get
                    {
835
                        if (_assemblies == null)
P
Pilchie 已提交
836
                        {
837
                            _assemblies = new List<AssemblySymbol>();
P
Pilchie 已提交
838 839 840 841

                            // This should be done lazy because while we creating
                            // instances of this type, creation of new SourceAssembly symbols
                            // might change the set of available AssemblySymbols.
842
                            AddAvailableSymbols(_assemblies);
P
Pilchie 已提交
843 844
                        }

845
                        return _assemblies;
P
Pilchie 已提交
846 847 848 849 850 851 852 853 854
                    }
                }

                protected abstract void AddAvailableSymbols(List<AssemblySymbol> assemblies);

                public override ImmutableArray<AssemblyIdentity> AssemblyReferences
                {
                    get
                    {
855
                        return _referencedAssemblies;
P
Pilchie 已提交
856 857 858 859 860 861
                    }
                }

                public override AssemblyReferenceBinding[] BindAssemblyReferences(
                    ImmutableArray<AssemblyData> assemblies, AssemblyIdentityComparer assemblyIdentityComparer)
                {
T
Tomas Matousek 已提交
862
                    return ResolveReferencedAssemblies(_referencedAssemblies, assemblies, definitionStartIndex: 0, assemblyIdentityComparer: assemblyIdentityComparer);
P
Pilchie 已提交
863 864 865 866 867 868
                }

                public sealed override bool IsLinked
                {
                    get
                    {
869
                        return _embedInteropTypes;
P
Pilchie 已提交
870 871 872 873 874 875
                    }
                }
            }

            private sealed class AssemblyDataForFile : AssemblyDataForMetadataOrCompilation
            {
876 877 878 879 880 881 882 883
                public readonly PEAssembly Assembly;

                /// <summary>
                /// Guarded by <see cref="CommonReferenceManager.SymbolCacheAndReferenceManagerStateGuard"/>.
                /// </summary>
                public readonly WeakList<IAssemblySymbol> CachedSymbols;

                public readonly DocumentationProvider DocumentationProvider;
P
Pilchie 已提交
884 885 886 887

                /// <summary>
                /// Import options of the compilation being built.
                /// </summary>
888
                private readonly MetadataImportOptions _compilationImportOptions;
P
Pilchie 已提交
889 890 891 892 893

                // This is the name of the compilation that is being built. 
                // This should be the assembly name w/o the extension. It is
                // used to compute whether or not it is possible that this
                // assembly will give friend access to the compilation.
894
                private readonly string _sourceAssemblySimpleName;
P
Pilchie 已提交
895

896 897
                private bool _internalsVisibleComputed;
                private bool _internalsPotentiallyVisibleToCompilation;
P
Pilchie 已提交
898 899 900 901 902 903 904 905

                public AssemblyDataForFile(
                    PEAssembly assembly,
                    WeakList<IAssemblySymbol> cachedSymbols,
                    bool embedInteropTypes,
                    DocumentationProvider documentationProvider,
                    string sourceAssemblySimpleName,
                    MetadataImportOptions compilationImportOptions)
906
                    : base(assembly.Identity, assembly.AssemblyReferences, embedInteropTypes)
P
Pilchie 已提交
907 908 909 910
                {
                    Debug.Assert(documentationProvider != null);
                    Debug.Assert(cachedSymbols != null);

911 912 913
                    CachedSymbols = cachedSymbols;
                    Assembly = assembly;
                    DocumentationProvider = documentationProvider;
914 915
                    _compilationImportOptions = compilationImportOptions;
                    _sourceAssemblySimpleName = sourceAssemblySimpleName;
P
Pilchie 已提交
916 917
                }

918 919
                internal override AssemblySymbol CreateAssemblySymbol()
                {
920
                    return new PEAssemblySymbol(Assembly, DocumentationProvider, this.IsLinked, this.EffectiveImportOptions);
921 922
                }

P
Pilchie 已提交
923 924 925 926
                internal bool InternalsMayBeVisibleToCompilation
                {
                    get
                    {
927
                        if (!_internalsVisibleComputed)
P
Pilchie 已提交
928
                        {
929
                            _internalsPotentiallyVisibleToCompilation = InternalsMayBeVisibleToAssemblyBeingCompiled(_sourceAssemblySimpleName, Assembly);
930
                            _internalsVisibleComputed = true;
P
Pilchie 已提交
931 932
                        }

933
                        return _internalsPotentiallyVisibleToCompilation;
P
Pilchie 已提交
934 935 936 937 938 939 940 941
                    }
                }

                internal MetadataImportOptions EffectiveImportOptions
                {
                    get
                    {
                        // We need to import internal members if they might be visible to the compilation being compiled:
942
                        if (InternalsMayBeVisibleToCompilation && _compilationImportOptions == MetadataImportOptions.Public)
P
Pilchie 已提交
943 944 945 946
                        {
                            return MetadataImportOptions.Internal;
                        }

947
                        return _compilationImportOptions;
P
Pilchie 已提交
948 949 950 951 952 953 954 955
                    }
                }

                protected override void AddAvailableSymbols(List<AssemblySymbol> assemblies)
                {
                    // accessing cached symbols requires a lock
                    lock (SymbolCacheAndReferenceManagerStateGuard)
                    {
956
                        foreach (var assembly in CachedSymbols)
P
Pilchie 已提交
957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978
                        {
                            var peAssembly = assembly as PEAssemblySymbol;
                            if (IsMatchingAssembly(peAssembly))
                            {
                                assemblies.Add(peAssembly);
                            }
                        }
                    }
                }

                public override bool IsMatchingAssembly(AssemblySymbol candidateAssembly)
                {
                    return IsMatchingAssembly(candidateAssembly as PEAssemblySymbol);
                }

                private bool IsMatchingAssembly(PEAssemblySymbol peAssembly)
                {
                    if ((object)peAssembly == null)
                    {
                        return false;
                    }

979
                    if (!ReferenceEquals(peAssembly.Assembly, Assembly))
P
Pilchie 已提交
980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004
                    {
                        return false;
                    }

                    if (EffectiveImportOptions != peAssembly.PrimaryModule.ImportOptions)
                    {
                        return false;
                    }

                    // TODO (tomat): 
                    // We shouldn't need to compare documentation providers. All symbols in the cachedSymbols list 
                    // should share the same provider - as they share the same metadata.
                    // Removing the Equals call also avoids calling user code while holding a lock.
                    if (!peAssembly.DocumentationProvider.Equals(DocumentationProvider))
                    {
                        return false;
                    }

                    return true;
                }

                public override bool ContainsNoPiaLocalTypes
                {
                    get
                    {
1005
                        return Assembly.ContainsNoPiaLocalTypes();
P
Pilchie 已提交
1006 1007 1008 1009 1010 1011 1012
                    }
                }

                public override bool DeclaresTheObjectClass
                {
                    get
                    {
1013
                        return Assembly.DeclaresTheObjectClass;
P
Pilchie 已提交
1014 1015
                    }
                }
1016 1017

                public override Compilation SourceCompilation => null;
P
Pilchie 已提交
1018 1019 1020 1021
            }

            private sealed class AssemblyDataForCompilation : AssemblyDataForMetadataOrCompilation
            {
1022
                public readonly CSharpCompilation Compilation;
P
Pilchie 已提交
1023 1024

                public AssemblyDataForCompilation(CSharpCompilation compilation, bool embedInteropTypes)
1025
                    : base(compilation.Assembly.Identity, GetReferencedAssemblies(compilation), embedInteropTypes)
P
Pilchie 已提交
1026
                {
1027 1028
                    Compilation = compilation;
                }
P
Pilchie 已提交
1029

1030 1031
                private static ImmutableArray<AssemblyIdentity> GetReferencedAssemblies(CSharpCompilation compilation)
                {
P
Pilchie 已提交
1032
                    // Collect information about references
1033
                    var result = ArrayBuilder<AssemblyIdentity>.GetInstance();
P
Pilchie 已提交
1034

1035
                    var modules = compilation.Assembly.Modules;
P
Pilchie 已提交
1036 1037 1038 1039 1040

                    // Filter out linked assemblies referenced by the source module.
                    var sourceReferencedAssemblies = modules[0].GetReferencedAssemblies();
                    var sourceReferencedAssemblySymbols = modules[0].GetReferencedAssemblySymbols();

1041
                    Debug.Assert(sourceReferencedAssemblies.Length == sourceReferencedAssemblySymbols.Length);
P
Pilchie 已提交
1042

1043
                    for (int i = 0; i < sourceReferencedAssemblies.Length; i++)
P
Pilchie 已提交
1044 1045 1046
                    {
                        if (!sourceReferencedAssemblySymbols[i].IsLinked)
                        {
1047
                            result.Add(sourceReferencedAssemblies[i]);
P
Pilchie 已提交
1048 1049 1050
                        }
                    }

1051
                    for (int i = 1; i < modules.Length; i++)
P
Pilchie 已提交
1052
                    {
1053
                        result.AddRange(modules[i].GetReferencedAssemblies());
P
Pilchie 已提交
1054 1055
                    }

1056
                    return result.ToImmutableAndFree();
P
Pilchie 已提交
1057 1058
                }

1059 1060
                internal override AssemblySymbol CreateAssemblySymbol()
                {
1061
                    return new RetargetingAssemblySymbol(Compilation.SourceAssembly, this.IsLinked);
1062 1063
                }

P
Pilchie 已提交
1064 1065
                protected override void AddAvailableSymbols(List<AssemblySymbol> assemblies)
                {
1066
                    assemblies.Add(Compilation.Assembly);
P
Pilchie 已提交
1067 1068 1069 1070

                    // accessing cached symbols requires a lock
                    lock (SymbolCacheAndReferenceManagerStateGuard)
                    {
1071
                        Compilation.AddRetargetingAssemblySymbolsNoLock(assemblies);
P
Pilchie 已提交
1072 1073 1074 1075 1076
                    }
                }

                public override bool IsMatchingAssembly(AssemblySymbol candidateAssembly)
                {
1077
                    var retargeting = candidateAssembly as RetargetingAssemblySymbol;
P
Pilchie 已提交
1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088
                    AssemblySymbol asm;

                    if ((object)retargeting != null)
                    {
                        asm = retargeting.UnderlyingAssembly;
                    }
                    else
                    {
                        asm = candidateAssembly as SourceAssemblySymbol;
                    }

1089
                    Debug.Assert(!(asm is RetargetingAssemblySymbol));
P
Pilchie 已提交
1090

1091
                    return ReferenceEquals(asm, Compilation.Assembly);
P
Pilchie 已提交
1092 1093 1094 1095 1096 1097
                }

                public override bool ContainsNoPiaLocalTypes
                {
                    get
                    {
1098
                        return Compilation.MightContainNoPiaLocalTypes();
P
Pilchie 已提交
1099 1100 1101 1102 1103 1104 1105
                    }
                }

                public override bool DeclaresTheObjectClass
                {
                    get
                    {
1106
                        return Compilation.DeclaresTheObjectClass;
P
Pilchie 已提交
1107 1108
                    }
                }
1109

1110
                public override Compilation SourceCompilation => Compilation;
P
Pilchie 已提交
1111 1112 1113 1114 1115 1116 1117
            }

            /// <summary>
            /// For testing purposes only.
            /// </summary>
            internal static bool IsSourceAssemblySymbolCreated(CSharpCompilation compilation)
            {
1118
                return (object)compilation._lazyAssemblySymbol != null;
P
Pilchie 已提交
1119 1120 1121 1122 1123 1124 1125
            }

            /// <summary>
            /// For testing purposes only.
            /// </summary>
            internal static bool IsReferenceManagerInitialized(CSharpCompilation compilation)
            {
1126
                return compilation._referenceManager.IsBound;
P
Pilchie 已提交
1127 1128 1129 1130
            }
        }
    }
}