You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
51 lines
1.9 KiB
51 lines
1.9 KiB
using System.Linq; |
|
using System.Text; |
|
using Microsoft.CodeAnalysis; |
|
using Microsoft.CodeAnalysis.CSharp; |
|
|
|
namespace gaemstone.SourceGen.Utility; |
|
|
|
public static class SymbolExtensions |
|
{ |
|
public static string GetFullName(this ISymbol symbol, bool metadata = false) |
|
{ |
|
var builder = new StringBuilder(); |
|
AppendFullName(symbol, builder, metadata); |
|
return builder.ToString(); |
|
} |
|
|
|
public static void AppendFullName(this ISymbol symbol, StringBuilder builder, bool metadata = false) |
|
{ |
|
if ((symbol.ContainingSymbol is ISymbol parent) |
|
&& ((parent as INamespaceSymbol)?.IsGlobalNamespace != true)) |
|
{ |
|
AppendFullName(parent, builder, metadata); |
|
builder.Append(((parent is ITypeSymbol) && metadata) ? '+' : '.'); |
|
} |
|
|
|
if (!metadata && (symbol is INamedTypeSymbol typeSymbol) && typeSymbol.IsGenericType) { |
|
var length = symbol.MetadataName.IndexOf('`'); |
|
builder.Append(symbol.MetadataName, 0, length); |
|
builder.Append('<'); |
|
foreach (var genericType in typeSymbol.TypeArguments) { |
|
AppendFullName(genericType, builder, true); |
|
builder.Append(','); |
|
} |
|
builder.Length--; // Remove the last ',' character. |
|
builder.Append('>'); |
|
} else builder.Append(symbol.MetadataName); |
|
} |
|
|
|
public static string? GetNamespace(this ISymbol symbol) |
|
=> symbol.ContainingNamespace?.GetFullName(); |
|
|
|
public static bool HasAttribute(this ISymbol symbol, string attrMetadataName) |
|
=> symbol.GetAttributes().Any(attr => attr.AttributeClass!.GetFullName(true) == attrMetadataName); |
|
|
|
public static AttributeData? GetAttribute(this ISymbol symbol, string attrMetadataName) |
|
=> symbol.GetAttributes().FirstOrDefault(attr => attr.AttributeClass!.GetFullName(true) == attrMetadataName); |
|
|
|
public static string ToStringLiteral(this string? input) |
|
=> (input != null) ? SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, |
|
SyntaxFactory.Literal(input)).ToFullString() : "null"; |
|
}
|
|
|