using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using ComputeSharp.D2D1.SourceGenerators.Models;
using ComputeSharp.SourceGeneration.Extensions;
using Microsoft.CodeAnalysis;
using static ComputeSharp.D2D1.SourceGenerators.Diagnostics.DiagnosticDescriptors;
namespace ComputeSharp.D2D1.SourceGenerators;
///
partial class ID2D1ShaderGenerator
{
///
/// A helper with all logic to generate the LoadInputDescriptions method.
///
private static partial class LoadInputDescriptions
{
///
/// Extracts the input descriptions for the current shader.
///
/// The input instance to process.
/// The produced input descriptions for the shader.
/// The collection of produced instances.
public static void GetInfo(
INamedTypeSymbol structDeclarationSymbol,
out ImmutableArray inputDescriptions,
out ImmutableArray diagnostics)
{
int inputCount = 0;
ImmutableArray.Builder inputDescriptionsBuilder = ImmutableArray.CreateBuilder();
ImmutableArray.Builder diagnosticsBuilder = ImmutableArray.CreateBuilder();
foreach (AttributeData attributeData in structDeclarationSymbol.GetAttributes())
{
switch (attributeData.AttributeClass?.GetFullMetadataName())
{
case "ComputeSharp.D2D1.D2DInputCountAttribute":
inputCount = (int)attributeData.ConstructorArguments[0].Value!;
break;
case "ComputeSharp.D2D1.D2DInputDescriptionAttribute":
if (attributeData.ConstructorArguments.Length == 2)
{
int index = (int)attributeData.ConstructorArguments[0].Value!;
D2D1Filter filter = (D2D1Filter)attributeData.ConstructorArguments[1].Value!;
_ = attributeData.TryGetNamedArgument("LevelOfDetailCount", out int levelOfDetailCount);
inputDescriptionsBuilder.Add(new InputDescription((uint)index, filter, levelOfDetailCount));
}
break;
default:
break;
}
}
inputDescriptions = ImmutableArray.Empty;
// Validate the input count (ignore if invalid, this will be validated by GetInputType() generator)
if (inputCount is not (>= 0 and <= 8))
{
goto End;
}
// All simple indices must be in range
if (inputDescriptionsBuilder.Any(description => description.Index >= inputCount))
{
diagnosticsBuilder.Add(OutOfRangeInputDescriptionIndex, structDeclarationSymbol, structDeclarationSymbol);
goto End;
}
HashSet inputDescriptionIndices = new(inputDescriptionsBuilder.Select(description => description.Index));
// All input description indices must be unique
if (inputDescriptionIndices.Count != inputDescriptionsBuilder.Count)
{
diagnosticsBuilder.Add(RepeatedD2DInputDescriptionIndices, structDeclarationSymbol, structDeclarationSymbol);
goto End;
}
inputDescriptions = inputDescriptionsBuilder.ToImmutable();
End:
diagnostics = diagnosticsBuilder.ToImmutable();
}
}
}