using System;
using ComputeSharp.SourceGeneration.Extensions;
using ComputeSharp.SourceGeneration.Helpers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using static Microsoft.CodeAnalysis.CSharp.SyntaxFactory;
using static Microsoft.CodeAnalysis.SymbolDisplayTypeQualificationStyle;
namespace ComputeSharp.SourceGeneration.Models;
///
/// A model describing the hierarchy info for a specific type.
///
/// The fully qualified metadata name for the current type.
/// Gets the namespace for the current type.
/// Gets the sequence of type definitions containing the current type.
internal sealed partial record HierarchyInfo(string FullyQualifiedMetadataName, string Namespace, EquatableArray Hierarchy)
{
///
/// Creates a new instance from a given .
///
/// The input instance to gather info for.
/// A instance describing .
public static HierarchyInfo From(INamedTypeSymbol typeSymbol)
{
using ImmutableArrayBuilder hierarchy = new();
for (INamedTypeSymbol? parent = typeSymbol;
parent is not null;
parent = parent.ContainingType)
{
hierarchy.Add(new TypeInfo(
parent.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat),
parent.TypeKind,
parent.IsRecord));
}
return new(
typeSymbol.GetFullyQualifiedMetadataName(),
typeSymbol.ContainingNamespace.ToDisplayString(new(typeQualificationStyle: NameAndContainingTypesAndNamespaces)),
hierarchy.ToImmutable());
}
///
/// Writes syntax for the current hierarchy into a target writer.
///
/// The type of state to pass to callbacks.
/// The input state to pass to callbacks.
/// The target instance to write text to.
/// A list of base types to add to the generated type, if any.
/// The callbacks to use to write members into the declared type.
public void WriteSyntax(
T state,
IndentedTextWriter writer,
ReadOnlySpan baseTypes,
ReadOnlySpan> memberCallbacks)
{
// Write the generated file header
writer.WriteLine("// ");
writer.WriteLine("#pragma warning disable");
writer.WriteLine();
// Declare the namespace, if needed
if (Namespace.Length > 0)
{
writer.WriteLine($"namespace {Namespace}");
writer.WriteLine("{");
writer.IncreaseIndent();
}
// Declare all the opening types until the inner-most one
for (int i = Hierarchy.Length - 1; i >= 0; i--)
{
writer.WriteLine($$"""/// """);
writer.Write($$"""partial {{Hierarchy[i].GetTypeKeyword()}} {{Hierarchy[i].QualifiedName}}""");
// Add any base types, if needed
if (i == 0 && !baseTypes.IsEmpty)
{
writer.Write(" : ");
writer.WriteInitializationExpressions(baseTypes, static (item, writer) => writer.Write(item));
writer.WriteLine();
}
else
{
writer.WriteLine();
}
writer.WriteLine($$"""{""");
writer.IncreaseIndent();
}
// Generate all nested members
writer.WriteLineSeparatedMembers(memberCallbacks, (callback, writer) => callback(state, writer));
// Close all scopes and reduce the indentation
for (int i = 0; i < Hierarchy.Length; i++)
{
writer.DecreaseIndent();
writer.WriteLine("}");
}
// Close the namespace scope as well, if needed
if (Namespace.Length > 0)
{
writer.DecreaseIndent();
writer.WriteLine("}");
}
}
///
/// Gets the fully qualified type name for the current instance.
///
/// The fully qualified type name for the current instance.
public string GetFullyQualifiedTypeName()
{
using ImmutableArrayBuilder fullyQualifiedTypeName = new();
fullyQualifiedTypeName.AddRange("global::".AsSpan());
fullyQualifiedTypeName.AddRange(Namespace.AsSpan());
for (int i = Hierarchy.Length - 1; i >= 0; i--)
{
fullyQualifiedTypeName.Add('.');
fullyQualifiedTypeName.AddRange(Hierarchy[i].QualifiedName.AsSpan());
}
return fullyQualifiedTypeName.ToString();
}
///
/// Creates a instance for the current hierarchy.
///
/// The member declarations to add to the generated type.
/// A instance for the current hierarchy.
public CompilationUnitSyntax GetSyntax(params MemberDeclarationSyntax[] memberDeclarations)
{
return GetSyntax(memberDeclarations, Array.Empty());
}
///
/// Creates a instance for the current hierarchy.
///
/// The member declarations to add to the generated type.
/// Additional top-level member declarations, if any.
/// A instance for the current hierarchy.
public CompilationUnitSyntax GetSyntax(MemberDeclarationSyntax[] memberDeclarations, params MemberDeclarationSyntax[] additionalMemberDeclarations)
{
// Create the partial type declaration with for the current hierarchy.
// This code produces a type declaration as follows:
//
// partial
// {
//
// }
TypeDeclarationSyntax typeDeclarationSyntax =
Hierarchy[0].GetSyntax()
.AddModifiers(Token(SyntaxKind.PartialKeyword))
.AddMembers(memberDeclarations);
// Add all parent types in ascending order, if any
foreach (TypeInfo parentType in Hierarchy.AsSpan().Slice(1))
{
typeDeclarationSyntax =
parentType.GetSyntax()
.AddModifiers(Token(SyntaxKind.PartialKeyword))
.AddMembers(typeDeclarationSyntax);
}
// Prepare the leading trivia for the generated compilation unit.
// This will produce code as follows:
//
// //
// #pragma warning disable
SyntaxTriviaList syntaxTriviaList = TriviaList(
Comment("// "),
Trivia(PragmaWarningDirectiveTrivia(Token(SyntaxKind.DisableKeyword), true)));
CompilationUnitSyntax compilationUnitSyntax;
if (Namespace is "")
{
// If there is no namespace, attach the pragma directly to the declared type,
// and skip the namespace declaration. This will produce code as follows:
//
//
//
compilationUnitSyntax =
CompilationUnit()
.AddMembers(typeDeclarationSyntax.WithLeadingTrivia(syntaxTriviaList));
}
else
{
// Create the compilation unit with disabled warnings, target namespace and generated type.
// This will produce code as follows:
//
//
// namespace ;
//
//
compilationUnitSyntax =
CompilationUnit().AddMembers(
FileScopedNamespaceDeclaration(IdentifierName(Namespace))
.WithLeadingTrivia(syntaxTriviaList)
.AddMembers(typeDeclarationSyntax));
}
// Add any additional members, if any
if (additionalMemberDeclarations.Length > 0)
{
compilationUnitSyntax = compilationUnitSyntax.AddMembers(additionalMemberDeclarations);
}
// Normalize and return the tree
return compilationUnitSyntax.NormalizeWhitespace(eol: "\n");
}
}