using System.Collections.Immutable;
using System.Linq;
using System.Text;
using Microsoft.CodeAnalysis;
namespace ComputeSharp.SourceGeneration.Extensions;
///
/// Extension methods for types.
///
internal static class ISymbolExtensions
{
///
/// A custom instance with fully qualified style, without global::.
///
public static readonly SymbolDisplayFormat FullyQualifiedWithoutGlobalFormat = new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers);
///
/// A custom instance with fully qualified style, without global:: and parameters.
///
private static readonly SymbolDisplayFormat FullyQualifiedWithoutGlobalAndParametersFormat = new(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces,
genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers,
memberOptions: SymbolDisplayMemberOptions.IncludeContainingType,
parameterOptions: SymbolDisplayParameterOptions.None);
///
/// Gets the fully qualified name for a given symbol.
///
/// The input instance.
/// The fully qualified name for .
public static string GetFullyQualifiedName(this ISymbol symbol)
{
return symbol.ToDisplayString(FullyQualifiedWithoutGlobalFormat);
}
///
/// Checks whether or not a given type symbol has a specified full name.
///
/// The input instance to check.
/// The full name to check.
/// Whether has a full name equals to .
public static bool HasFullyQualifiedName(this ISymbol symbol, string name)
{
return symbol.ToDisplayString(FullyQualifiedWithoutGlobalFormat) == name;
}
///
/// Gets a valid filename for a given instance.
///
/// The input instance.
/// The full metadata name for that is also a valid filename.
public static string GetFullMetadataName(this ITypeSymbol symbol)
{
static StringBuilder BuildFrom(ISymbol? symbol, StringBuilder builder)
{
return symbol switch
{
INamespaceSymbol ns when ns.IsGlobalNamespace => builder,
INamespaceSymbol ns when ns.ContainingNamespace is { IsGlobalNamespace: false }
=> BuildFrom(ns.ContainingNamespace, builder.Insert(0, $".{ns.MetadataName}")),
ITypeSymbol ts when ts.ContainingType is ISymbol containingType
=> BuildFrom(containingType, builder.Insert(0, $"+{ts.MetadataName}")),
ITypeSymbol ts when ts.ContainingNamespace is ISymbol containingNamespace and not INamespaceSymbol { IsGlobalNamespace: true }
=> BuildFrom(containingNamespace, builder.Insert(0, $".{ts.MetadataName}")),
ISymbol => BuildFrom(symbol.ContainingSymbol, builder.Insert(0, symbol.MetadataName)),
_ => builder
};
}
return BuildFrom(symbol, new StringBuilder(256)).ToString();
}
///
/// Gets the full metadata name for a given instance.
///
/// The input instance.
/// Whether or not to also include parameter types.
/// The full metadata name for .
public static string GetFullMetadataName(this IMethodSymbol symbol, bool includeParameters = false)
{
if (includeParameters)
{
var parameters = string.Join(", ", symbol.Parameters.Select(static p => ((INamedTypeSymbol)p.Type).GetFullMetadataName()));
return $"{symbol.ToDisplayString(FullyQualifiedWithoutGlobalAndParametersFormat)}({parameters})";
}
return symbol.ToDisplayString(FullyQualifiedWithoutGlobalAndParametersFormat);
}
///
/// Gets the full metadata name for a given instance.
///
/// The input instance.
/// The full metadata name for .
public static string GetFullMetadataName(this IPropertySymbol symbol)
{
string declaringTypeName = symbol.ContainingType.GetFullMetadataName();
if (symbol.IsIndexer)
{
var parameters = string.Join(", ", symbol.Parameters.Select(static p => ((INamedTypeSymbol)p.Type).GetFullMetadataName()));
return $"{declaringTypeName}.this[{parameters}]";
}
return $"{declaringTypeName}.{symbol.Name}";
}
///
/// Gets the full metadata name for a given instance.
///
/// The input instance.
/// The full metadata name for .
public static string GetFullMetadataName(this IFieldSymbol symbol)
{
return $"{symbol.ContainingType.GetFullMetadataName()}.{symbol.Name}";
}
///
/// Gets a valid filename for a target symbol and generator type.
///
/// The symbol being processed.
/// A filename in the form "<SYMBOL_FULLNAME>"
public static string GetGeneratedFileName(this INamedTypeSymbol symbol)
{
return symbol.GetFullMetadataName().Replace('`', '-').Replace('+', '.');
}
///
/// Checks whether or not a given symbol has an attribute with the specified full name.
///
/// The input instance to check.
/// The attribute name to look for.
/// Whether or not has an attribute with the specified name.
public static bool HasAttributeWithFullyQualifiedName(this ISymbol symbol, string name)
{
ImmutableArray attributes = symbol.GetAttributes();
foreach (AttributeData attribute in attributes)
{
if (attribute.AttributeClass?.HasFullyQualifiedName(name) == true)
{
return true;
}
}
return false;
}
///
/// Tries to get an attribute with the specified full metadata name.
///
/// The input instance to check.
/// The attribute name to look for.
/// The resulting attribute data, if found.
/// Whether or not has an attribute with the specified name.
public static bool TryGetAttributeWithFullMetadataName(this ISymbol symbol, string name, out AttributeData? attributeData)
{
ImmutableArray attributes = symbol.GetAttributes();
foreach (AttributeData attribute in attributes)
{
if (attribute.AttributeClass?.GetFullMetadataName() == name)
{
attributeData = attribute;
return true;
}
}
attributeData = null;
return false;
}
///
/// Calculates the effective accessibility for a given symbol.
///
/// The instance to check.
/// The effective accessibility for .
public static Accessibility GetEffectiveAccessibility(this ISymbol symbol)
{
// Start by assuming it's visible
Accessibility visibility = Accessibility.Public;
// Handle special cases
switch (symbol.Kind)
{
case SymbolKind.Alias: return Accessibility.Private;
case SymbolKind.Parameter: return GetEffectiveAccessibility(symbol.ContainingSymbol);
case SymbolKind.TypeParameter: return Accessibility.Private;
}
// Traverse the symbol hierarchy to determine the effective accessibility
while (symbol is not null && symbol.Kind != SymbolKind.Namespace)
{
switch (symbol.DeclaredAccessibility)
{
case Accessibility.NotApplicable:
case Accessibility.Private:
return Accessibility.Private;
case Accessibility.Internal:
case Accessibility.ProtectedAndInternal:
visibility = Accessibility.Internal;
break;
}
symbol = symbol.ContainingSymbol;
}
return visibility;
}
///
/// Checks whether or not a given symbol can be accessed from a specified assembly.
///
/// The input instance to check.
/// The assembly to check the accessibility of for.
/// Whether can access .
public static bool CanBeAccessedFrom(this ISymbol symbol, IAssemblySymbol assembly)
{
Accessibility accessibility = symbol.GetEffectiveAccessibility();
return
accessibility == Accessibility.Public ||
accessibility == Accessibility.Internal && symbol.ContainingAssembly.GivesAccessTo(assembly);
}
}