using System.Globalization; using System.Text.RegularExpressions; using static GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition.CompositionValidator; namespace GAJ3T.MusicGen.RiffGrooveBuilder.Core.Composition; public static class DescriptionParser { public static DescriptionParseResult Parse(string? text) { if (string.IsNullOrWhiteSpace(text)) return new(null, [Error("empty_description", "description", "Supply at least one supported setting or role clause.")]); if (text.Length > 16_384) return new(null, [Error("description_too_long", "description", "Limit the description to 16,384 characters.")]); return new Reader(text).Parse(); } private sealed class Reader { private readonly string source; private readonly Match[] tokens; private readonly List errors = []; private readonly Dictionary pitched = []; private readonly Dictionary drums = []; private readonly HashSet roles = []; private int position; private int? tempo; private int? bars; private TimeSignature? meter; private MusicalKey? key; internal Reader(string source) { this.source = source; tokens = Regex.Matches(source, @"[0-9]+(?:\.[0-9]+)*(?:[eE][+-]?[0-9]+)?|[A-Za-z]+|[^\s]", RegexOptions.CultureInvariant | RegexOptions.NonBacktracking).ToArray(); } internal DescriptionParseResult Parse() { Take("generate"); var clauses = 0; while (position < tokens.Length) { while (IsPunctuation(Current)) position++; if (position == tokens.Length) break; if (clauses > 0 && Take("and") && position == tokens.Length) { Unsupported(); break; } var start = position; if (!TrySetting() && !TryPitched() && !TryDrum()) { position = start; Unsupported(); break; } clauses++; if (errors.Count != 0) break; } if (errors.Count != 0) return new(null, errors); if (clauses == 0) return new(null, [Error("empty_description", "description", "Supply at least one supported setting or role clause.", source)]); var defaults = new List(); if (tempo is null) defaults.Add(new("tempoBpm", "120")); if (bars is null) defaults.Add(new("bars", "4")); if (meter is null) defaults.Add(new("meter", "4/4")); if (key is null) defaults.Add(new("key", "E minor")); var actualMeter = meter ?? new(4, 4); errors.AddRange(ValidateSettings(tempo ?? 120, bars ?? 4, actualMeter, key ?? new(4, KeyMode.Minor))); if (roles.Count == 0) { roles.UnionWith([TrackRole.Lead, TrackRole.Bass, TrackRole.Drums]); defaults.Add(new("roles", "lead,bass,drums")); } var patterns = new List(); foreach (var role in new[] { TrackRole.Lead, TrackRole.Bass }) { if (!roles.Contains(role)) continue; pitched.TryGetValue(role, out var raw); var name = role.ToString().ToLowerInvariant(); var pattern = raw?.Pattern ?? (role == TrackRole.Lead ? NotePattern.Eighth : NotePattern.Sustained); if (raw?.Pattern is null) defaults.Add(new($"{name}.pattern", PatternName(pattern))); if (raw?.Articulation is null) defaults.Add(new($"{name}.articulation", "sustain")); defaults.Add(new($"{name}.rootOctave", role == TrackRole.Lead ? "4" : "2")); defaults.Add(new($"{name}.velocity", "96")); patterns.Add(new(role, pattern, raw?.Articulation ?? Articulation.Sustain)); } if (roles.Contains(TrackRole.Drums)) { defaults.Add(new("drums.velocity", "96")); if (drums.Count == 0) { if (actualMeter != new TimeSignature(4, 4)) errors.Add(Error("explicit_drums_required", "drums", "For non-4/4 meters supply explicit kick/snare beats or closed hi-hat subdivision.")); else { drums.Add(DrumVoice.Kick, new(DrumVoice.Kick, [1, 3], null)); drums.Add(DrumVoice.Snare, new(DrumVoice.Snare, [2, 4], null)); drums.Add(DrumVoice.ClosedHiHat, new(DrumVoice.ClosedHiHat, null, NotePattern.Eighth)); defaults.AddRange([ new("drums.kick", "beats 1 and 3"), new("drums.snare", "beats 2 and 4"), new("drums.closedHiHat", "eighth notes")]); } } foreach (var drum in drums.Values) { if (drum.Beats.Any(beat => beat < 1 || beat > actualMeter.Numerator)) errors.Add(Error("invalid_beat", $"drums.{drum.Voice}", "Use numbered denominator-note beats within the meter numerator.")); } } if (errors.Count != 0) return new(null, errors); return new(new ParsedDescription(tempo ?? 120, bars ?? 4, actualMeter, key ?? new(4, KeyMode.Minor), patterns, drums.Values.OrderBy(drum => drum.Voice), defaults), []); } private bool TrySetting() { var start = position; var hasAt = Take("at"); if (IsInteger(Current) && Peek(1) == "bpm") { var value = ReadInteger("tempoBpm"); Take("bpm"); Set(ref tempo, value, "tempoBpm", start); return true; } position = start; if (hasAt) return false; if ((IsInteger(Current) || WordNumber(Current) != 0) && Peek(1) is "bar" or "bars") { var value = WordNumber(Current); if (value == 0) value = ReadInteger("bars"); else position++; position++; Set(ref bars, value, "bars", start); return true; } if (IsInteger(Current) && Peek(1) == "/") { var numerator = ReadInteger("meter.numerator"); position++; var denominator = ReadInteger("meter.denominator"); Set(ref meter, new TimeSignature(numerator, denominator), "meter", start); return true; } Take("in"); if (TryRoot(out var root) && Current is "major" or "minor") { var mode = Take("major") ? KeyMode.Major : KeyMode.Minor; if (mode == KeyMode.Minor) Take("minor"); Set(ref key, new MusicalKey(root, mode), "key", start); return true; } position = start; return false; } private bool TryPitched() { var start = position; var articulation = ReadArticulation(); var pattern = ReadPattern(); var hasPrefix = position != start; if (!ReadRole(out var role)) { position = start; return false; } if (!hasPrefix) { articulation = ReadArticulation(); pattern = ReadPattern(); } var raw = new RawPitched(pattern, articulation); if (pitched.TryGetValue(role, out var previous) && previous != raw) errors.Add(Error("conflicting_clause", role.ToString().ToLowerInvariant(), "Supply one consistent pattern/articulation clause for this role.", Phrase(start))); else pitched[role] = raw; roles.Add(role); return true; } private bool TryDrum() { if (Take("drums")) { roles.Add(TrackRole.Drums); return true; } var start = position; DrumVoice voice; DrumPattern pattern; if (Take("kick")) voice = DrumVoice.Kick; else if (Take("snare")) voice = DrumVoice.Snare; else if (TakePhrase("closed hi hat", true)) { var subdivision = ReadSubdivision(); if (subdivision is null) { errors.Add(Error("invalid_drum_pattern", "drums.closedHiHat", "Specify quarter, eighth or sixteenth notes.", Phrase(start))); return true; } AddDrum(new(DrumVoice.ClosedHiHat, null, subdivision), start); return true; } else return false; if (!Take("on") || !(Take("beats") || Take("beat"))) { errors.Add(Error("invalid_drum_pattern", $"drums.{voice}", "Use 'on beat(s)' followed by numbered beats.", Phrase(start))); return true; } var beats = new List { ReadInteger("drums.beats") }; while (Current == "and" && IsInteger(Peek(1))) { position++; beats.Add(ReadInteger("drums.beats")); } if (beats.Distinct().Count() != beats.Count) errors.Add(Error("duplicate_beat", "drums.beats", "List each numbered beat once.", Phrase(start))); pattern = new(voice, beats.Order(), null); AddDrum(pattern, start); return true; } private void AddDrum(DrumPattern pattern, int start) { if (drums.TryGetValue(pattern.Voice, out var previous) && (previous.Subdivision != pattern.Subdivision || !previous.Beats.SequenceEqual(pattern.Beats))) errors.Add(Error("conflicting_clause", $"drums.{pattern.Voice}", "Supply one consistent placement/subdivision for this drum voice.", Phrase(start))); else drums[pattern.Voice] = pattern; roles.Add(TrackRole.Drums); } private bool ReadRole(out TrackRole role) { role = TrackRole.Lead; if (Take("lead")) { Take("guitar"); return true; } if (Take("guitar")) return true; role = TrackRole.Bass; return Take("bass"); } private Articulation? ReadArticulation() { if (Take("sustain")) return Articulation.Sustain; if (TakePhrase("palm muted", true) || TakePhrase("palm mute", true)) return Articulation.PalmMute; return null; } private NotePattern? ReadPattern() { var pattern = Take("sustained") ? NotePattern.Sustained : ReadSubdivision(); if (pattern is not null) { if (!TakePhrase("root note", true)) TakePhrase("root notes", true); } return pattern; } private NotePattern? ReadSubdivision() { var start = position; NotePattern? result = Take("quarter") ? NotePattern.Quarter : Take("eighth") ? NotePattern.Eighth : Take("sixteenth") ? NotePattern.Sixteenth : null; if (result is null) return null; Take("-"); if (Take("note") || Take("notes")) return result; position = start; return null; } private bool TryRoot(out int pitchClass) { pitchClass = 0; var token = Current; if (token.Length is < 1 or > 2 || token[0] is < 'a' or > 'g' || (token.Length == 2 && token[1] != 'b')) return false; var natural = token[0] switch { 'c' => 0, 'd' => 2, 'e' => 4, 'f' => 5, 'g' => 7, 'a' => 9, _ => 11 }; position++; var accidental = token.Length == 2 ? -1 : Take("#") || Take("♯") ? 1 : Take("♭") ? -1 : 0; pitchClass = (natural + accidental + 12) % 12; return true; } private void Set(ref T? setting, T value, string field, int start) where T : struct { if (setting is not null && !EqualityComparer.Default.Equals(setting.Value, value)) errors.Add(Error("conflicting_setting", field, "Supply this setting once, or repeat the same value.", Phrase(start))); else setting = value; } private int ReadInteger(string field) { if (int.TryParse(Current, NumberStyles.None, CultureInfo.InvariantCulture, out var value)) { position++; return value; } errors.Add(Error("invalid_number", field, "Use an unsigned ASCII integer within Int32 range.", Current)); if (position < tokens.Length) position++; return 0; } private bool Take(string value) { if (Current != value) return false; position++; return true; } private bool TakePhrase(string phrase, bool hyphens) { var start = position; var words = phrase.Split(' '); for (var i = 0; i < words.Length; i++) { if (i != 0 && hyphens) Take("-"); if (Take(words[i])) continue; position = start; return false; } return true; } private string Current => Token(position); private string Peek(int offset) => Token(position + offset); private string Token(int index) => index < tokens.Length ? tokens[index].Value.ToLowerInvariant() : ""; private string Phrase(int start) => source[tokens[start].Index..(position > start ? tokens[position - 1].Index + tokens[position - 1].Length : source.Length)]; private void Unsupported() => errors.Add(Error("unsupported_text", "description", "Use only documented settings, role patterns and drum clauses; remove or rephrase unconsumed instructions.", position < tokens.Length ? source[tokens[position].Index..] : "and")); private static bool IsInteger(string value) => value.Length > 0 && value.All(c => c is >= '0' and <= '9'); private static bool IsPunctuation(string value) => value is "," or ":" or ";" or "."; private static int WordNumber(string value) => value switch { "one" => 1, "two" => 2, "three" => 3, "four" => 4, "five" => 5, "six" => 6, "seven" => 7, "eight" => 8, "nine" => 9, "ten" => 10, "eleven" => 11, "twelve" => 12, "thirteen" => 13, "fourteen" => 14, "fifteen" => 15, "sixteen" => 16, _ => 0 }; private sealed record RawPitched(NotePattern? Pattern, Articulation? Articulation); } private static string PatternName(NotePattern pattern) => pattern switch { NotePattern.Sustained => "sustained", NotePattern.Quarter => "quarter notes", NotePattern.Eighth => "eighth notes", _ => "sixteenth notes" }; }