using System; using System.Diagnostics.CodeAnalysis; using System.Security; using System.Text.RegularExpressions; using Microsoft.CodeAnalysis; namespace ComputeSharp.D2D1.SourceGenerators.Helpers; /// /// A helper class to parse D2D metadata values. /// internal static class D2D1EffectMetadataParser { /// /// A instance to find all newlines. /// private static readonly Regex NewLinesRegex = new("[\r\n\v]", RegexOptions.Compiled); /// /// Checks whether a given value contains a valid effect display name. /// /// The input object to inspect. /// Whether contains a valid effect display name. public static bool IsValidEffectDisplayName(AttributeData attributeData) { if (attributeData.ConstructorArguments is [{ Value: string { Length: > 0 } value }]) { // Remove new lines (the values cannot span multiple lines in XML) string singleLineValue = NewLinesRegex.Replace(value, string.Empty); // Trim directly and check that (no need to escape, as that wouldn't change things) return singleLineValue.AsSpan().Trim().Length > 0; } return false; } /// /// Tries to get the defined effect display name for a given attribute. /// /// The input object to inspect. /// The resulting defined effect display name, if found. /// Whether or not a defined effect display name could be found. public static bool TryGetEffectDisplayName(AttributeData attributeData, [NotNullWhen(true)] out string? effectDisplayName) { // Check that the attribute is [D2DEffectDisplayName] and with a valid parameter if (attributeData.ConstructorArguments is [{ Value: string { Length: > 0 } value }]) { // Remove new lines (the values cannot span multiple lines in XML) string singleLineValue = NewLinesRegex.Replace(value, string.Empty); // Make sure to escape any invalid XML characters string escapedValue = SecurityElement.Escape(singleLineValue); // Trim the display name as well if (escapedValue.AsSpan().Trim() is { Length: > 0 } trimmedValue) { effectDisplayName = trimmedValue.ToString(); return true; } } effectDisplayName = default; return false; } }