Skip to content

Commit c4d9041

Browse files
committed
Add Compilation.TryBuildNamedTypeSymbolMap extension
1 parent 01efc75 commit c4d9041

File tree

1 file changed

+37
-0
lines changed

1 file changed

+37
-0
lines changed

src/CommunityToolkit.Mvvm.SourceGenerators/Extensions/CompilationExtensions.cs

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22
// The .NET Foundation licenses this file to you under the MIT license.
33
// See the LICENSE file in the project root for more information.
44

5+
using System;
6+
using System.Collections.Generic;
7+
using System.Collections.Immutable;
8+
using System.Diagnostics.CodeAnalysis;
59
using Microsoft.CodeAnalysis;
610
using Microsoft.CodeAnalysis.CSharp;
711

@@ -87,4 +91,37 @@ public static bool HasAccessibleTypeWithMetadataName(this Compilation compilatio
8791

8892
return false;
8993
}
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+
}
90127
}

0 commit comments

Comments
 (0)