|
2 | 2 | // The .NET Foundation licenses this file to you under the MIT license.
|
3 | 3 | // See the LICENSE file in the project root for more information.
|
4 | 4 |
|
| 5 | +using System; |
| 6 | +using System.Collections.Generic; |
| 7 | +using System.Collections.Immutable; |
| 8 | +using System.Diagnostics.CodeAnalysis; |
5 | 9 | using Microsoft.CodeAnalysis;
|
6 | 10 | using Microsoft.CodeAnalysis.CSharp;
|
7 | 11 |
|
@@ -87,4 +91,37 @@ public static bool HasAccessibleTypeWithMetadataName(this Compilation compilatio
|
87 | 91 |
|
88 | 92 | return false;
|
89 | 93 | }
|
| 94 | + |
| 95 | + /// <summary> |
| 96 | + /// Tries to build a map of <see cref="INamedTypeSymbol"/> instances form the input mapping of names. |
| 97 | + /// </summary> |
| 98 | + /// <typeparam name="T">The type of keys for each symbol.</typeparam> |
| 99 | + /// <param name="compilation">The <see cref="Compilation"/> to consider for analysis.</param> |
| 100 | + /// <param name="typeNames">The input mapping of <typeparamref name="T"/> keys to fully qualified type names.</param> |
| 101 | + /// <param name="typeSymbols">The resulting mapping of <typeparamref name="T"/> keys to resolved <see cref="INamedTypeSymbol"/> instances.</param> |
| 102 | + /// <returns>Whether all requested <see cref="INamedTypeSymbol"/> instances could be resolved.</returns> |
| 103 | + public static bool TryBuildNamedTypeSymbolMap<T>( |
| 104 | + this Compilation compilation, |
| 105 | + IEnumerable<KeyValuePair<T, string>> typeNames, |
| 106 | + [NotNullWhen(true)] out ImmutableDictionary<T, INamedTypeSymbol>? typeSymbols) |
| 107 | + where T : IEquatable<T> |
| 108 | + { |
| 109 | + ImmutableDictionary<T, INamedTypeSymbol>.Builder builder = ImmutableDictionary.CreateBuilder<T, INamedTypeSymbol>(); |
| 110 | + |
| 111 | + foreach (KeyValuePair<T, string> pair in typeNames) |
| 112 | + { |
| 113 | + if (compilation.GetTypeByMetadataName(pair.Value) is not INamedTypeSymbol attributeSymbol) |
| 114 | + { |
| 115 | + typeSymbols = null; |
| 116 | + |
| 117 | + return false; |
| 118 | + } |
| 119 | + |
| 120 | + builder.Add(pair.Key, attributeSymbol); |
| 121 | + } |
| 122 | + |
| 123 | + typeSymbols = builder.ToImmutable(); |
| 124 | + |
| 125 | + return true; |
| 126 | + } |
90 | 127 | }
|
0 commit comments