CommonReferenceManager.Resolution.cs 46.3 KB
Newer Older
1 2 3 4 5 6 7
// 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.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
8
using System.Reflection;
9
using System.Runtime.CompilerServices;
10 11
using System.Runtime.InteropServices;
using Microsoft.CodeAnalysis.Collections;
12 13 14 15 16 17 18 19 20 21 22 23 24
using Roslyn.Utilities;

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

    /// <summary>
    /// The base class for language specific assembly managers.
    /// </summary>
    /// <typeparam name="TCompilation">Language specific representation for a compilation</typeparam>
    /// <typeparam name="TAssemblySymbol">Language specific representation for an assembly symbol.</typeparam>
    internal abstract partial class CommonReferenceManager<TCompilation, TAssemblySymbol>
        where TCompilation : Compilation
25
        where TAssemblySymbol : class, IAssemblySymbol
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
    {
        protected abstract CommonMessageProvider MessageProvider { get; }

        protected abstract AssemblyData CreateAssemblyDataForFile(
            PEAssembly assembly,
            WeakList<IAssemblySymbol> cachedSymbols,
            DocumentationProvider documentationProvider,
            string sourceAssemblySimpleName,
            MetadataImportOptions importOptions,
            bool embedInteropTypes);

        protected abstract AssemblyData CreateAssemblyDataForCompilation(
            CompilationReference compilationReference);

        /// <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 abstract bool CheckPropertiesConsistency(MetadataReference primaryReference, MetadataReference duplicateReference, DiagnosticBag diagnostics);

        /// <summary>
        /// Called to compare two weakly named identities with the same name.
        /// </summary>
        protected abstract bool WeakIdentityPropertiesEquivalent(AssemblyIdentity identity1, AssemblyIdentity identity2);

        [DebuggerDisplay("{GetDebuggerDisplay(), nq}")]
        protected struct ResolvedReference
        {
            private readonly MetadataImageKind _kind;
            private readonly int _index;
57 58
            private readonly ImmutableArray<string> _aliasesOpt;
            private readonly ImmutableArray<string> _recursiveAliasesOpt;
59

60 61 62
            // uninitialized aliases
            public ResolvedReference(int index, MetadataImageKind kind)
            {
T
Tomas Matousek 已提交
63 64 65
                Debug.Assert(index >= 0);
                _index = index + 1;
                _kind = kind;
66 67 68 69
            }

            // initialized aliases
            public ResolvedReference(int index, MetadataImageKind kind, ImmutableArray<string> aliasesOpt, ImmutableArray<string> recursiveAliasesOpt)
T
Tomas Matousek 已提交
70
                : this(index, kind)
71
            {
T
Tomas Matousek 已提交
72 73
                // We have to have non-default aliases (empty are ok). We can have both recursive and non-recursive aliases if two references were merged.
                Debug.Assert(!aliasesOpt.IsDefault || !recursiveAliasesOpt.IsDefault);
74

75 76
                _aliasesOpt = aliasesOpt;
                _recursiveAliasesOpt = recursiveAliasesOpt;
77 78
            }

79 80 81 82
            private bool IsUninitialized => _aliasesOpt.IsDefault && _recursiveAliasesOpt.IsDefault;

            /// <summary>
            /// Aliases that should be applied to the referenced assembly. 
T
Tomas Matousek 已提交
83
            /// Empty array means {"global"} (all namespaces and types in the global namespace of the assembly are accessible without qualification).
84 85 86
            /// Null if not applicable (the reference only has recursive aliases).
            /// </summary>
            public ImmutableArray<string> AliasesOpt
87 88 89
            {
                get
                {
90 91 92 93 94 95 96
                    Debug.Assert(!IsUninitialized);
                    return _aliasesOpt;
                }
            }

            /// <summary>
            /// Aliases that should be applied recursively to all dependent assemblies. 
T
Tomas Matousek 已提交
97
            /// Empty array means {"global"} (all namespaces and types in the global namespace of the assembly are accessible without qualification).
98 99 100 101 102 103 104 105
            /// Null if not applicable (the reference only has simple aliases).
            /// </summary>
            public ImmutableArray<string> RecursiveAliasesOpt
            {
                get
                {
                    Debug.Assert(!IsUninitialized);
                    return _recursiveAliasesOpt;
106 107 108
                }
            }

109 110 111
            /// <summary>
            /// default(<see cref="ResolvedReference"/>) is considered skipped.
            /// </summary>
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
            public bool IsSkipped
            {
                get
                {
                    return _index == 0;
                }
            }

            public MetadataImageKind Kind
            {
                get
                {
                    Debug.Assert(!IsSkipped);
                    return _kind;
                }
            }

129
            /// <summary>
T
Tomas Matousek 已提交
130
            /// Index into an array of assemblies (not including the assembly being built) or an array of modules, depending on <see cref="Kind"/>.
131
            /// </summary>
132 133 134 135 136 137 138 139 140 141 142
            public int Index
            {
                get
                {
                    Debug.Assert(!IsSkipped);
                    return _index - 1;
                }
            }

            private string GetDebuggerDisplay()
            {
143 144 145 146 147 148
                return IsSkipped ? "<skipped>" : $"{(_kind == MetadataImageKind.Assembly ? "A" : "M")}[{Index}]:{DisplayAliases(_aliasesOpt, "aliases")}{DisplayAliases(_recursiveAliasesOpt, "recursive-aliases")}";
            }

            private static string DisplayAliases(ImmutableArray<string> aliasesOpt, string name)
            {
                return aliasesOpt.IsDefault ? "" : $" {name} = '{string.Join("','", aliasesOpt)}'";
149 150 151
            }
        }

152
        protected struct ReferencedAssemblyIdentity
153 154
        {
            public readonly AssemblyIdentity Identity;
155
            public readonly MetadataReference Reference;
156

157
            /// <summary>
T
Tomas Matousek 已提交
158 159
            /// non-negative: Index into the array of all (explicitly and implicitly) referenced assemblies.
            /// negative: ExplicitlyReferencedAssemblies.Count + RelativeAssemblyIndex is an index into the array of assemblies.
160 161 162
            /// </summary>
            public readonly int RelativeAssemblyIndex;

C
CyrusNajmabadi 已提交
163
            public int GetAssemblyIndex(int explicitlyReferencedAssemblyCount) =>
164 165 166
                RelativeAssemblyIndex >= 0 ? RelativeAssemblyIndex : explicitlyReferencedAssemblyCount + RelativeAssemblyIndex;

            public ReferencedAssemblyIdentity(AssemblyIdentity identity, MetadataReference reference, int relativeAssemblyIndex)
167 168
            {
                Identity = identity;
169 170
                Reference = reference;
                RelativeAssemblyIndex = relativeAssemblyIndex;
171 172 173 174 175 176 177
            }
        }

        /// <summary>
        /// Resolves given metadata references to assemblies and modules.
        /// </summary>
        /// <param name="compilation">The compilation whose references are being resolved.</param>
178 179 180 181
        /// <param name="assemblyReferencesBySimpleName">
        /// Used to filter out assemblies that have the same strong or weak identity.
        /// Maps simple name to a list of identities. The highest version of each name is the first.
        /// </param>
182
        /// <param name="references">List where to store resolved references. References from #r directives will follow references passed to the compilation constructor.</param>
C
Charles Stoner 已提交
183
        /// <param name="boundReferenceDirectiveMap">Maps #r values to successfully resolved metadata references. Does not contain values that failed to resolve.</param>
184 185 186 187 188 189 190 191 192
        /// <param name="boundReferenceDirectives">Unique metadata references resolved from #r directives.</param>
        /// <param name="assemblies">List where to store information about resolved assemblies to.</param>
        /// <param name="modules">List where to store information about resolved modules to.</param>
        /// <param name="diagnostics">Diagnostic bag where to report resolution errors.</param>
        /// <returns>
        /// Maps index to <paramref name="references"/> to an index of a resolved assembly or module in <paramref name="assemblies"/> or <paramref name="modules"/>, respectively.
        ///</returns>
        protected ImmutableArray<ResolvedReference> ResolveMetadataReferences(
            TCompilation compilation,
193
            [Out] Dictionary<string, List<ReferencedAssemblyIdentity>> assemblyReferencesBySimpleName,
194
            out ImmutableArray<MetadataReference> references,
195
            out IDictionary<ValueTuple<string, string>, MetadataReference> boundReferenceDirectiveMap,
196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212
            out ImmutableArray<MetadataReference> boundReferenceDirectives,
            out ImmutableArray<AssemblyData> assemblies,
            out ImmutableArray<PEModule> modules,
            DiagnosticBag diagnostics)
        {
            // Locations of all #r directives in the order they are listed in the references list.
            ImmutableArray<Location> referenceDirectiveLocations;
            GetCompilationReferences(compilation, diagnostics, out references, out boundReferenceDirectiveMap, out referenceDirectiveLocations);

            // References originating from #r directives precede references supplied as arguments of the compilation.
            int referenceCount = references.Length;
            int referenceDirectiveCount = (referenceDirectiveLocations != null ? referenceDirectiveLocations.Length : 0);

            var referenceMap = new ResolvedReference[referenceCount];

            // Maps references that were added to the reference set (i.e. not filtered out as duplicates) to a set of names that 
            // can be used to alias these references. Duplicate assemblies contribute their aliases into this set.
213
            Dictionary<MetadataReference, MergedAliases> lazyAliasMap = null;
214 215 216

            // Used to filter out duplicate references that reference the same file (resolve to the same full normalized path).
            var boundReferences = new Dictionary<MetadataReference, MetadataReference>(MetadataReferenceEqualityComparer.Instance);
C
CyrusNajmabadi 已提交
217

218
            ArrayBuilder<MetadataReference> uniqueDirectiveReferences = (referenceDirectiveLocations != null) ? ArrayBuilder<MetadataReference>.GetInstance() : null;
219 220 221
            var assembliesBuilder = ArrayBuilder<AssemblyData>.GetInstance();
            ArrayBuilder<PEModule> lazyModulesBuilder = null;

222
            bool supersedeLowerVersions = compilation.Options.ReferencesSupersedeLowerVersions;
223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241

            // When duplicate references with conflicting EmbedInteropTypes flag are encountered,
            // VB uses the flag from the last one, C# reports an error. We need to enumerate in reverse order
            // so that we find the one that matters first.
            for (int referenceIndex = referenceCount - 1; referenceIndex >= 0; referenceIndex--)
            {
                var boundReference = references[referenceIndex];
                if (boundReference == null)
                {
                    continue;
                }

                // add bound reference if it doesn't exist yet, merging aliases:
                MetadataReference existingReference;
                if (boundReferences.TryGetValue(boundReference, out existingReference))
                {
                    // merge properties of compilation-based references if the underlying compilations are the same
                    if ((object)boundReference != existingReference)
                    {
242
                        MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap);
243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
                    }

                    continue;
                }

                boundReferences.Add(boundReference, boundReference);

                Location location;
                if (referenceIndex < referenceDirectiveCount)
                {
                    location = referenceDirectiveLocations[referenceIndex];
                    uniqueDirectiveReferences.Add(boundReference);
                }
                else
                {
                    location = Location.None;
                }

                // compilation reference

                var compilationReference = boundReference as CompilationReference;
                if (compilationReference != null)
                {
                    switch (compilationReference.Properties.Kind)
                    {
B
beep boop 已提交
268 269
                        case MetadataImageKind.Assembly:
                            existingReference = TryAddAssembly(
C
CyrusNajmabadi 已提交
270
                                compilationReference.Compilation.Assembly.Identity,
B
beep boop 已提交
271
                                boundReference,
272
                                -assembliesBuilder.Count - 1,
B
beep boop 已提交
273 274
                                diagnostics,
                                location,
275 276
                                assemblyReferencesBySimpleName,
                                supersedeLowerVersions);
277

B
beep boop 已提交
278 279
                            if (existingReference != null)
                            {
280
                                MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap);
B
beep boop 已提交
281 282
                                continue;
                            }
283

B
beep boop 已提交
284 285 286 287 288
                            // Note, if SourceAssemblySymbol hasn't been created for 
                            // compilationAssembly.Compilation yet, we want this to happen 
                            // right now. Conveniently, this constructor will trigger creation of the 
                            // SourceAssemblySymbol.
                            var asmData = CreateAssemblyDataForCompilation(compilationReference);
289
                            AddAssembly(asmData, referenceIndex, referenceMap, assembliesBuilder);
B
beep boop 已提交
290 291 292 293
                            break;

                        default:
                            throw ExceptionUtilities.UnexpectedValue(compilationReference.Properties.Kind);
294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310
                    }

                    continue;
                }

                // PE reference

                var peReference = (PortableExecutableReference)boundReference;
                Metadata metadata = GetMetadata(peReference, MessageProvider, location, diagnostics);
                Debug.Assert(metadata != null || diagnostics.HasAnyErrors());

                if (metadata != null)
                {
                    Debug.Assert(metadata != null);

                    switch (peReference.Properties.Kind)
                    {
B
beep boop 已提交
311 312 313
                        case MetadataImageKind.Assembly:
                            var assemblyMetadata = (AssemblyMetadata)metadata;
                            WeakList<IAssemblySymbol> cachedSymbols = assemblyMetadata.CachedSymbols;
314

B
beep boop 已提交
315
                            if (assemblyMetadata.IsValidAssembly())
316
                            {
B
beep boop 已提交
317 318
                                PEAssembly assembly = assemblyMetadata.GetAssembly();
                                existingReference = TryAddAssembly(
C
CyrusNajmabadi 已提交
319 320
                                    assembly.Identity,
                                    peReference,
321
                                    -assembliesBuilder.Count - 1,
B
beep boop 已提交
322 323
                                    diagnostics,
                                    location,
324 325
                                    assemblyReferencesBySimpleName,
                                    supersedeLowerVersions);
B
beep boop 已提交
326 327 328

                                if (existingReference != null)
                                {
329
                                    MergeReferenceProperties(existingReference, boundReference, diagnostics, ref lazyAliasMap);
B
beep boop 已提交
330 331 332 333 334 335 336 337 338 339 340
                                    continue;
                                }

                                var asmData = CreateAssemblyDataForFile(
                                    assembly,
                                    cachedSymbols,
                                    peReference.DocumentationProvider,
                                    SimpleAssemblyName,
                                    compilation.Options.MetadataImportOptions,
                                    peReference.Properties.EmbedInteropTypes);

341
                                AddAssembly(asmData, referenceIndex, referenceMap, assembliesBuilder);
B
beep boop 已提交
342 343 344 345
                            }
                            else
                            {
                                diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotAssembly, location, peReference.Display));
346 347
                            }

B
beep boop 已提交
348 349 350
                            // asmData keeps strong ref after this point
                            GC.KeepAlive(assemblyMetadata);
                            break;
351

B
beep boop 已提交
352 353 354
                        case MetadataImageKind.Module:
                            var moduleMetadata = (ModuleMetadata)metadata;
                            if (moduleMetadata.Module.IsLinkedModule)
355
                            {
B
beep boop 已提交
356 357 358 359 360 361 362
                                // We don't support netmodules since some checks in the compiler need information from the full PE image
                                // (Machine, Bit32Required, PE image hash).
                                if (!moduleMetadata.Module.IsEntireImageAvailable)
                                {
                                    diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_LinkedNetmoduleMetadataMustProvideFullPEImage, location, peReference.Display));
                                }

363
                                AddModule(moduleMetadata.Module, referenceIndex, referenceMap, ref lazyModulesBuilder);
364
                            }
B
beep boop 已提交
365 366 367 368 369
                            else
                            {
                                diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotModule, location, peReference.Display));
                            }
                            break;
370

B
beep boop 已提交
371 372
                        default:
                            throw ExceptionUtilities.UnexpectedValue(peReference.Properties.Kind);
373 374 375 376 377 378 379 380 381 382 383 384 385 386
                    }
                }
            }

            if (uniqueDirectiveReferences != null)
            {
                uniqueDirectiveReferences.ReverseContents();
                boundReferenceDirectives = uniqueDirectiveReferences.ToImmutableAndFree();
            }
            else
            {
                boundReferenceDirectives = ImmutableArray<MetadataReference>.Empty;
            }

387 388 389 390 391 392 393
            // We enumerated references in reverse order in the above code
            // and thus assemblies and modules in the builders are reversed.
            // Fix up all the indices and reverse the builder content now to get 
            // the ordering matching the references.
            // 
            // Also fills in aliases.

394 395 396 397
            for (int i = 0; i < referenceMap.Length; i++)
            {
                if (!referenceMap[i].IsSkipped)
                {
398
                    int count = (referenceMap[i].Kind == MetadataImageKind.Assembly) ? assembliesBuilder.Count : lazyModulesBuilder?.Count ?? 0;
399

400
                    int reversedIndex = count - 1 - referenceMap[i].Index;
401
                    referenceMap[i] = GetResolvedReferenceAndFreePropertyMapEntry(references[i], reversedIndex, referenceMap[i].Kind, lazyAliasMap);
402 403 404
                }
            }

405 406
            assembliesBuilder.ReverseContents();
            assemblies = assembliesBuilder.ToImmutableAndFree();
C
CyrusNajmabadi 已提交
407

408
            if (lazyModulesBuilder == null)
409 410 411 412 413
            {
                modules = ImmutableArray<PEModule>.Empty;
            }
            else
            {
414 415
                lazyModulesBuilder.ReverseContents();
                modules = lazyModulesBuilder.ToImmutableAndFree();
416 417 418 419 420
            }

            return ImmutableArray.CreateRange(referenceMap);
        }

421
        private static ResolvedReference GetResolvedReferenceAndFreePropertyMapEntry(MetadataReference reference, int index, MetadataImageKind kind, Dictionary<MetadataReference, MergedAliases> propertyMapOpt)
422
        {
423 424 425 426 427 428 429 430
            ImmutableArray<string> aliasesOpt, recursiveAliasesOpt;

            MergedAliases mergedProperties;
            if (propertyMapOpt != null && propertyMapOpt.TryGetValue(reference, out mergedProperties))
            {
                aliasesOpt = mergedProperties.AliasesOpt?.ToImmutableAndFree() ?? default(ImmutableArray<string>);
                recursiveAliasesOpt = mergedProperties.RecursiveAliasesOpt?.ToImmutableAndFree() ?? default(ImmutableArray<string>);
            }
T
Tomas Matousek 已提交
431
            else if (reference.Properties.HasRecursiveAliases)
432
            {
433 434 435 436 437 438 439
                aliasesOpt = default(ImmutableArray<string>);
                recursiveAliasesOpt = reference.Properties.Aliases;
            }
            else
            {
                aliasesOpt = reference.Properties.Aliases;
                recursiveAliasesOpt = default(ImmutableArray<string>);
440 441
            }

442
            return new ResolvedReference(index, kind, aliasesOpt, recursiveAliasesOpt);
443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
        }

        /// <summary>
        /// Creates or gets metadata for PE reference.
        /// </summary>
        /// <remarks>
        /// If any of the following exceptions: <see cref="BadImageFormatException"/>, <see cref="FileNotFoundException"/>, <see cref="IOException"/>,
        /// are thrown while reading the metadata file, the exception is caught and an appropriate diagnostic stored in <paramref name="diagnostics"/>.
        /// </remarks>
        private Metadata GetMetadata(PortableExecutableReference peReference, CommonMessageProvider messageProvider, Location location, DiagnosticBag diagnostics)
        {
            Metadata existingMetadata;

            lock (ObservedMetadata)
            {
                if (TryGetObservedMetadata(peReference, diagnostics, out existingMetadata))
                {
                    return existingMetadata;
                }
            }

V
Vladimir Reshetnikov 已提交
464
            Metadata newMetadata;
465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
            Diagnostic newDiagnostic = null;
            try
            {
                newMetadata = peReference.GetMetadata();

                // make sure basic structure of the PE image is valid:
                var assemblyMetadata = newMetadata as AssemblyMetadata;
                if (assemblyMetadata != null)
                {
                    bool dummy = assemblyMetadata.IsValidAssembly();
                }
                else
                {
                    bool dummy = ((ModuleMetadata)newMetadata).Module.IsLinkedModule;
                }
            }
481
            catch (Exception e) when (e is BadImageFormatException || e is IOException)
482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501
            {
                newDiagnostic = PortableExecutableReference.ExceptionToDiagnostic(e, messageProvider, location, peReference.Display, peReference.Properties.Kind);
                newMetadata = null;
            }

            lock (ObservedMetadata)
            {
                if (TryGetObservedMetadata(peReference, diagnostics, out existingMetadata))
                {
                    return existingMetadata;
                }

                if (newDiagnostic != null)
                {
                    diagnostics.Add(newDiagnostic);
                }

                ObservedMetadata.Add(peReference, (MetadataOrDiagnostic)newMetadata ?? newDiagnostic);
                return newMetadata;
            }
502
        }
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567

        private bool TryGetObservedMetadata(PortableExecutableReference peReference, DiagnosticBag diagnostics, out Metadata metadata)
        {
            MetadataOrDiagnostic existing;
            if (ObservedMetadata.TryGetValue(peReference, out existing))
            {
                Debug.Assert(existing is Metadata || existing is Diagnostic);

                metadata = existing as Metadata;
                if (metadata == null)
                {
                    diagnostics.Add((Diagnostic)existing);
                }

                return true;
            }

            metadata = null;
            return false;
        }

        /// <summary>
        /// Determines whether references are the same. Compilation references are the same if they refer to the same compilation.
        /// Otherwise, references are represented by their object identities.
        /// </summary>
        internal sealed class MetadataReferenceEqualityComparer : IEqualityComparer<MetadataReference>
        {
            internal static readonly MetadataReferenceEqualityComparer Instance = new MetadataReferenceEqualityComparer();

            public bool Equals(MetadataReference x, MetadataReference y)
            {
                if (ReferenceEquals(x, y))
                {
                    return true;
                }

                var cx = x as CompilationReference;
                if (cx != null)
                {
                    var cy = y as CompilationReference;
                    if (cy != null)
                    {
                        return (object)cx.Compilation == cy.Compilation;
                    }
                }

                return false;
            }

            public int GetHashCode(MetadataReference reference)
            {
                var compilationReference = reference as CompilationReference;
                if (compilationReference != null)
                {
                    return RuntimeHelpers.GetHashCode(compilationReference.Compilation);
                }

                return RuntimeHelpers.GetHashCode(reference);
            }
        }

        /// <summary>
        /// Merges aliases of the first observed reference (<paramref name="primaryReference"/>) with aliases specified for an equivalent reference (<paramref name="newReference"/>).
        /// Empty alias list is considered to be the same as a list containing "global", since in both cases C# allows unqualified access to the symbols.
        /// </summary>
568
        private void MergeReferenceProperties(MetadataReference primaryReference, MetadataReference newReference, DiagnosticBag diagnostics, ref Dictionary<MetadataReference, MergedAliases> lazyAliasMap)
569 570 571 572 573 574
        {
            if (!CheckPropertiesConsistency(newReference, primaryReference, diagnostics))
            {
                return;
            }

575
            if (lazyAliasMap == null)
576
            {
577
                lazyAliasMap = new Dictionary<MetadataReference, MergedAliases>();
578 579
            }

580 581
            MergedAliases mergedAliases;
            if (!lazyAliasMap.TryGetValue(primaryReference, out mergedAliases))
582
            {
583 584 585
                mergedAliases = new MergedAliases();
                lazyAliasMap.Add(primaryReference, mergedAliases);
                mergedAliases.Merge(primaryReference);
586 587
            }

588
            mergedAliases.Merge(newReference);
589 590 591 592 593
        }

        /// <remarks>
        /// Caller is responsible for freeing any allocated ArrayBuilders.
        /// </remarks>
594
        private static void AddAssembly(AssemblyData data, int referenceIndex, ResolvedReference[] referenceMap, ArrayBuilder<AssemblyData> assemblies)
595
        {
596
            // aliases will be filled in later:
597
            referenceMap[referenceIndex] = new ResolvedReference(assemblies.Count, MetadataImageKind.Assembly);
598 599 600 601 602 603 604 605 606 607 608 609 610
            assemblies.Add(data);
        }

        /// <remarks>
        /// Caller is responsible for freeing any allocated ArrayBuilders.
        /// </remarks>
        private static void AddModule(PEModule module, int referenceIndex, ResolvedReference[] referenceMap, ref ArrayBuilder<PEModule> modules)
        {
            if (modules == null)
            {
                modules = ArrayBuilder<PEModule>.GetInstance();
            }

611
            referenceMap[referenceIndex] = new ResolvedReference(modules.Count, MetadataImageKind.Module);
612 613 614
            modules.Add(module);
        }

T
Tomas Matousek 已提交
615 616 617 618 619 620 621
        /// <summary>
        /// Returns null if an assembly of an equivalent identity has not been added previously, otherwise returns the reference that added it.
        /// Two identities are considered equivalent if
        /// - both assembly names are strong (have keys) and are either equal or FX unified 
        /// - both assembly names are weak (no keys) and have the same simple name.
        /// </summary>
        private MetadataReference TryAddAssembly(
C
CyrusNajmabadi 已提交
622 623 624 625
            AssemblyIdentity identity,
            MetadataReference reference,
            int assemblyIndex,
            DiagnosticBag diagnostics,
T
Tomas Matousek 已提交
626
            Location location,
627 628
            Dictionary<string, List<ReferencedAssemblyIdentity>> referencesBySimpleName,
            bool supersedeLowerVersions)
629
        {
630
            var referencedAssembly = new ReferencedAssemblyIdentity(identity, reference, assemblyIndex);
631 632

            List<ReferencedAssemblyIdentity> sameSimpleNameIdentities;
633 634 635 636 637
            if (!referencesBySimpleName.TryGetValue(identity.Name, out sameSimpleNameIdentities))
            {
                referencesBySimpleName.Add(identity.Name, new List<ReferencedAssemblyIdentity> { referencedAssembly });
                return null;
            }
C
CyrusNajmabadi 已提交
638

639
            if (supersedeLowerVersions)
640
            {
641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659
                foreach (var other in sameSimpleNameIdentities)
                {
                    if (identity.Version == other.Identity.Version)
                    {
                        return other.Reference;
                    }
                }

                // Keep all versions of the assembly and the first identity in the list the one with the highest version:
                if (sameSimpleNameIdentities[0].Identity.Version > identity.Version)
                {
                    sameSimpleNameIdentities.Add(referencedAssembly);
                }
                else
                {
                    sameSimpleNameIdentities.Add(sameSimpleNameIdentities[0]);
                    sameSimpleNameIdentities[0] = referencedAssembly;
                }

660 661 662 663 664 665 666 667
                return null;
            }

            ReferencedAssemblyIdentity equivalent = default(ReferencedAssemblyIdentity);
            if (identity.IsStrongName)
            {
                foreach (var other in sameSimpleNameIdentities)
                {
668 669
                    // Only compare strong with strong (weak is never equivalent to strong and vice versa).
                    // In order to eliminate duplicate references we need to try to match their identities in both directions since 
670
                    // ReferenceMatchesDefinition is not necessarily symmetric.
671
                    // (e.g. System.Numerics.Vectors, Version=4.1+ matches System.Numerics.Vectors, Version=4.0, but not the other way around.)
C
CyrusNajmabadi 已提交
672
                    if (other.Identity.IsStrongName &&
673 674
                        IdentityComparer.ReferenceMatchesDefinition(identity, other.Identity) &&
                        IdentityComparer.ReferenceMatchesDefinition(other.Identity, identity))
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695
                    {
                        equivalent = other;
                        break;
                    }
                }
            }
            else
            {
                foreach (var other in sameSimpleNameIdentities)
                {
                    // only compare weak with weak
                    if (!other.Identity.IsStrongName && WeakIdentityPropertiesEquivalent(identity, other.Identity))
                    {
                        equivalent = other;
                        break;
                    }
                }
            }

            if (equivalent.Identity == null)
            {
696
                sameSimpleNameIdentities.Add(referencedAssembly);
697 698 699 700 701 702 703 704 705
                return null;
            }

            // equivalent found - ignore and/or report an error:

            if (identity.IsStrongName)
            {
                Debug.Assert(equivalent.Identity.IsStrongName);

C
Charles Stoner 已提交
706
                // versions might have been unified for a Framework assembly:
707 708 709 710 711 712 713
                if (identity != equivalent.Identity)
                {
                    // Dev12 C# reports an error
                    // Dev12 VB keeps both references in the compilation and reports an ambiguity error when a symbol is used.
                    // BREAKING CHANGE in VB: we report an error for both languages

                    // Multiple assemblies with equivalent identity have been imported: '{0}' and '{1}'. Remove one of the duplicate references.
714
                    MessageProvider.ReportDuplicateMetadataReferenceStrong(diagnostics, location, reference, identity, equivalent.Reference, equivalent.Identity);
715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734
                }
                // If the versions match exactly we ignore duplicates w/o reporting errors while 
                // Dev12 C# reports:
                //   error CS1703: An assembly with the same identity '{0}' has already been imported. Try removing one of the duplicate references.
                // Dev12 VB reports:
                //   Fatal error BC2000 : compiler initialization failed unexpectedly: Project already has a reference to assembly System. 
                //   A second reference to 'D:\Temp\System.dll' cannot be added.
            }
            else
            {
                Debug.Assert(!equivalent.Identity.IsStrongName);

                // Dev12 reports an error for all weak-named assemblies, even if the versions are the same.
                // We treat assemblies with the same name and version equal even if they don't have a strong name.
                // This change allows us to de-duplicate #r references based on identities rather than full paths,
                // and is closer to platforms that don't support strong names and consider name and version enough
                // to identify an assembly. An identity without version is considered to have version 0.0.0.0.

                if (identity != equivalent.Identity)
                {
735
                    MessageProvider.ReportDuplicateMetadataReferenceWeak(diagnostics, location, reference, identity, equivalent.Reference, equivalent.Identity);
736 737 738
                }
            }

739 740
            Debug.Assert(equivalent.Reference != null);
            return equivalent.Reference;
741 742 743 744 745 746
        }

        protected void GetCompilationReferences(
            TCompilation compilation,
            DiagnosticBag diagnostics,
            out ImmutableArray<MetadataReference> references,
747
            out IDictionary<ValueTuple<string, string>, MetadataReference> boundReferenceDirectives,
748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765
            out ImmutableArray<Location> referenceDirectiveLocations)
        {
            boundReferenceDirectives = null;

            ArrayBuilder<MetadataReference> referencesBuilder = ArrayBuilder<MetadataReference>.GetInstance();
            ArrayBuilder<Location> referenceDirectiveLocationsBuilder = null;

            try
            {
                foreach (var referenceDirective in compilation.ReferenceDirectives)
                {
                    if (compilation.Options.MetadataReferenceResolver == null)
                    {
                        diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataReferencesNotSupported, referenceDirective.Location));
                        break;
                    }

                    // we already successfully bound #r with the same value:
766
                    if (boundReferenceDirectives != null && boundReferenceDirectives.ContainsKey(ValueTuple.Create(referenceDirective.Location.SourceTree.FilePath, referenceDirective.File)))
767 768 769 770 771 772 773 774 775 776 777 778 779
                    {
                        continue;
                    }

                    MetadataReference boundReference = ResolveReferenceDirective(referenceDirective.File, referenceDirective.Location, compilation);
                    if (boundReference == null)
                    {
                        diagnostics.Add(MessageProvider.CreateDiagnostic(MessageProvider.ERR_MetadataFileNotFound, referenceDirective.Location, referenceDirective.File));
                        continue;
                    }

                    if (boundReferenceDirectives == null)
                    {
780
                        boundReferenceDirectives = new Dictionary<ValueTuple<string, string>, MetadataReference>();
781 782 783 784 785
                        referenceDirectiveLocationsBuilder = ArrayBuilder<Location>.GetInstance();
                    }

                    referencesBuilder.Add(boundReference);
                    referenceDirectiveLocationsBuilder.Add(referenceDirective.Location);
786
                    boundReferenceDirectives.Add(ValueTuple.Create(referenceDirective.Location.SourceTree.FilePath, referenceDirective.File), boundReference);
787 788 789 790 791
                }

                // add external reference at the end, so that they are processed first:
                referencesBuilder.AddRange(compilation.ExternalReferences);

792 793 794 795 796 797 798
                // Add all explicit references of the previous script compilation.
                var previousScriptCompilation = compilation.ScriptCompilationInfo?.PreviousScriptCompilation;
                if (previousScriptCompilation != null)
                {
                    referencesBuilder.AddRange(previousScriptCompilation.GetBoundReferenceManager().ExplicitReferences);
                }

799 800 801
                if (boundReferenceDirectives == null)
                {
                    // no directive references resolved successfully:
802
                    boundReferenceDirectives = SpecializedCollections.EmptyDictionary<ValueTuple<string, string>, MetadataReference>();
803 804 805
                }

                references = referencesBuilder.ToImmutable();
V
Vladimir Reshetnikov 已提交
806
                referenceDirectiveLocations = referenceDirectiveLocationsBuilder?.ToImmutableAndFree() ?? ImmutableArray<Location>.Empty;
807 808 809 810 811 812 813 814 815 816 817 818
            }
            finally
            {
                // Put this in a finally because we have tests that (intentionally) cause ResolveReferenceDirective to throw and 
                // we don't want to clutter the test output with leak reports.
                referencesBuilder.Free();
            }
        }

        /// <summary>
        /// For each given directive return a bound PE reference, or null if the binding fails.
        /// </summary>
819
        private static PortableExecutableReference ResolveReferenceDirective(string reference, Location location, TCompilation compilation)
820 821 822 823 824 825 826
        {
            var tree = location.SourceTree;
            string basePath = (tree != null && tree.FilePath.Length > 0) ? tree.FilePath : null;

            // checked earlier:
            Debug.Assert(compilation.Options.MetadataReferenceResolver != null);

827
            var references = compilation.Options.MetadataReferenceResolver.ResolveReference(reference, basePath, MetadataReferenceProperties.Assembly.WithRecursiveAliases(true));
828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844
            if (references.IsDefaultOrEmpty)
            {
                return null;
            }

            if (references.Length > 1)
            {
                // TODO: implement
                throw new NotSupportedException();
            }

            return references[0];
        }

        internal static AssemblyReferenceBinding[] ResolveReferencedAssemblies(
            ImmutableArray<AssemblyIdentity> references,
            ImmutableArray<AssemblyData> definitions,
T
Tomas Matousek 已提交
845 846
            int definitionStartIndex,
            AssemblyIdentityComparer assemblyIdentityComparer)
847 848 849 850
        {
            var boundReferences = new AssemblyReferenceBinding[references.Length];
            for (int j = 0; j < references.Length; j++)
            {
T
Tomas Matousek 已提交
851
                boundReferences[j] = ResolveReferencedAssembly(references[j], definitions, definitionStartIndex, assemblyIdentityComparer);
852 853 854 855 856 857 858 859 860
            }

            return boundReferences;
        }

        /// <summary>
        /// Used to match AssemblyRef with AssemblyDef.
        /// </summary>
        /// <param name="definitions">Array of definition identities to match against.</param>
T
Tomas Matousek 已提交
861
        /// <param name="definitionStartIndex">An index of the first definition to consider, <paramref name="definitions"/> preceding this index are ignored.</param>
862 863 864 865 866 867 868 869
        /// <param name="reference">Reference identity to resolve.</param>
        /// <param name="assemblyIdentityComparer">Assembly identity comparer.</param>
        /// <returns>
        /// Returns an index the reference is bound.
        /// </returns>
        internal static AssemblyReferenceBinding ResolveReferencedAssembly(
            AssemblyIdentity reference,
            ImmutableArray<AssemblyData> definitions,
T
Tomas Matousek 已提交
870 871
            int definitionStartIndex,
            AssemblyIdentityComparer assemblyIdentityComparer)
872 873 874 875 876 877 878 879 880
        {
            // Dev11 C# compiler allows the versions to not match exactly, assuming that a newer library may be used instead of an older version.
            // For a given reference it finds a definition with the lowest version that is higher then or equal to the reference version.
            // If match.Version != reference.Version a warning is reported.

            // definition with the lowest version higher than reference version, unless exact version found
            int minHigherVersionDefinition = -1;
            int maxLowerVersionDefinition = -1;

T
Tomas Matousek 已提交
881 882 883 884 885
            // Skip assembly being built for now; it will be considered at the very end:
            bool resolveAgainstAssemblyBeingBuilt = definitionStartIndex == 0;
            definitionStartIndex = Math.Max(definitionStartIndex, 1);

            for (int i = definitionStartIndex; i < definitions.Length; i++)
886 887 888 889 890
            {
                AssemblyIdentity definition = definitions[i].Identity;

                switch (assemblyIdentityComparer.Compare(reference, definition))
                {
B
beep boop 已提交
891 892
                    case AssemblyIdentityComparer.ComparisonResult.NotEquivalent:
                        continue;
893

B
beep boop 已提交
894 895
                    case AssemblyIdentityComparer.ComparisonResult.Equivalent:
                        return new AssemblyReferenceBinding(reference, i);
896

B
beep boop 已提交
897 898
                    case AssemblyIdentityComparer.ComparisonResult.EquivalentIgnoringVersion:
                        if (reference.Version < definition.Version)
899
                        {
B
beep boop 已提交
900 901 902 903 904
                            // Refers to an older assembly than we have
                            if (minHigherVersionDefinition == -1 || definition.Version < definitions[minHigherVersionDefinition].Identity.Version)
                            {
                                minHigherVersionDefinition = i;
                            }
905
                        }
B
beep boop 已提交
906
                        else
907
                        {
B
beep boop 已提交
908 909 910 911 912 913 914
                            Debug.Assert(reference.Version > definition.Version);

                            // Refers to a newer assembly than we have
                            if (maxLowerVersionDefinition == -1 || definition.Version > definitions[maxLowerVersionDefinition].Identity.Version)
                            {
                                maxLowerVersionDefinition = i;
                            }
915 916
                        }

B
beep boop 已提交
917
                        continue;
918 919 920

                    default:
                        throw ExceptionUtilities.Unreachable;
921 922 923 924 925 926 927 928 929 930 931 932 933 934 935
                }
            }

            // we haven't found definition that matches the reference

            if (minHigherVersionDefinition != -1)
            {
                return new AssemblyReferenceBinding(reference, minHigherVersionDefinition, versionDifference: +1);
            }

            if (maxLowerVersionDefinition != -1)
            {
                return new AssemblyReferenceBinding(reference, maxLowerVersionDefinition, versionDifference: -1);
            }

936 937 938 939 940
            // Handle cases where Windows.winmd is a runtime substitute for a
            // reference to a compile-time winmd. This is for scenarios such as a
            // debugger EE which constructs a compilation from the modules of
            // the running process where Windows.winmd loaded at runtime is a
            // substitute for a collection of Windows.*.winmd compile-time references.
941
            if (reference.IsWindowsComponent())
942
            {
T
Tomas Matousek 已提交
943
                for (int i = definitionStartIndex; i < definitions.Length; i++)
944
                {
945
                    if (definitions[i].Identity.IsWindowsRuntime())
946
                    {
947
                        return new AssemblyReferenceBinding(reference, i);
948 949 950 951
                    }
                }
            }

952 953 954 955 956 957 958 959 960
            // In the IDE it is possible the reference we're looking for is a
            // compilation reference to a source assembly. However, if the reference
            // is of ContentType WindowsRuntime then the compilation will never
            // match since all C#/VB WindowsRuntime compilations output .winmdobjs,
            // not .winmds, and the ContentType of a .winmdobj is Default.
            // If this is the case, we want to ignore the ContentType mismatch and
            // allow the compilation to match the reference.
            if (reference.ContentType == AssemblyContentType.WindowsRuntime)
            {
T
Tomas Matousek 已提交
961
                for (int i = definitionStartIndex; i < definitions.Length; i++)
962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977
                {
                    var definition = definitions[i].Identity;
                    var sourceCompilation = definitions[i].SourceCompilation;
                    if (definition.ContentType == AssemblyContentType.Default &&
                        sourceCompilation?.Options.OutputKind == OutputKind.WindowsRuntimeMetadata &&
                        AssemblyIdentityComparer.SimpleNameComparer.Equals(reference.Name, definition.Name) &&
                        reference.Version.Equals(definition.Version) &&
                        reference.IsRetargetable == definition.IsRetargetable &&
                        AssemblyIdentityComparer.CultureComparer.Equals(reference.CultureName, definition.CultureName) &&
                        AssemblyIdentity.KeysEqual(reference, definition))
                    {
                        return new AssemblyReferenceBinding(reference, i);
                    }
                }
            }

978 979 980
            // As in the native compiler (see IMPORTER::MapAssemblyRefToAid), we compare against the
            // compilation (i.e. source) assembly as a last resort.  We follow the native approach of
            // skipping the public key comparison since we have yet to compute it.
T
Tomas Matousek 已提交
981
            if (resolveAgainstAssemblyBeingBuilt &&
982 983 984 985 986 987 988 989 990 991
                AssemblyIdentityComparer.SimpleNameComparer.Equals(reference.Name, definitions[0].Identity.Name))
            {
                Debug.Assert(definitions[0].Identity.PublicKeyToken.IsEmpty);
                return new AssemblyReferenceBinding(reference, 0);
            }

            return new AssemblyReferenceBinding(reference);
        }
    }
}