using System.Collections.Immutable;
using System.Linq;
using ComputeSharp.SourceGeneration.Helpers;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.Text;
namespace ComputeSharp.SourceGeneration.Models;
///
/// A model for a serializeable diagnostic info.
///
/// The wrapped instance.
/// The tree to use as location for the diagnostic, if available.
/// The span to use as location for the diagnostic.
/// The diagnostic arguments.
internal sealed record DiagnosticInfo(DiagnosticDescriptor Descriptor, SyntaxTree? SyntaxTree, TextSpan TextSpan, EquatableArray Arguments)
{
///
/// Creates a new instance with the state from this model.
///
/// A new instance with the state from this model.
public Diagnostic ToDiagnostic()
{
if (SyntaxTree is not null)
{
return Diagnostic.Create(Descriptor, Location.Create(SyntaxTree, TextSpan), Arguments.ToArray());
}
return Diagnostic.Create(Descriptor, null, Arguments.ToArray());
}
///
/// Creates a new instance with the specified parameters.
///
/// The input for the diagnostics to create.
/// The source to attach the diagnostics to.
/// The optional arguments for the formatted message to include.
/// A new instance with the specified parameters.
public static DiagnosticInfo Create(DiagnosticDescriptor descriptor, ISymbol symbol, params object[] args)
{
Location location = symbol.Locations.First();
return new(descriptor, location.SourceTree, location.SourceSpan, args.Select(static arg => arg.ToString()).ToImmutableArray());
}
///
/// Creates a new instance with the specified parameters.
///
/// The input for the diagnostics to create.
/// The source to attach the diagnostics to.
/// The optional arguments for the formatted message to include.
/// A new instance with the specified parameters.
public static DiagnosticInfo Create(DiagnosticDescriptor descriptor, SyntaxNode node, params object[] args)
{
Location location = node.GetLocation();
return new(descriptor, location.SourceTree, location.SourceSpan, args.Select(static arg => arg.ToString()).ToImmutableArray());
}
}