use super::{apply, Edit, LineIndex};
use crate::compiler::ast::{MacroDef, Node};
use crate::{CompileOptions, Diagnostic, Span};
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub enum TimbreTarget {
Macro(String),
Track(String),
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Timbre {
pub target: TimbreTarget,
pub tone: Option<u8>,
pub params: Vec<(String, u32)>,
pub macros: Vec<String>,
}
pub fn timbres(src: &str, opts: &CompileOptions<'_>) -> Vec<Timbre> {
let (ast, _) = crate::parse_with_options(src, opts);
let mut out = Vec::new();
for m in &ast.macros {
if is_timbre_macro(m) {
let mut t = empty(TimbreTarget::Macro(m.name.clone()));
collect(&m.nodes, &ast.macros, &mut t, 0);
out.push(t);
}
}
for tr in &ast.tracks {
let mut t = empty(TimbreTarget::Track(tr.name.clone()));
collect(head(&tr.nodes), &ast.macros, &mut t, 0);
out.push(t);
}
out
}
pub fn set_timbre_params(
src: &str,
target: &TimbreTarget,
changes: &[(&str, u32)],
opts: &CompileOptions<'_>,
) -> Result<String, Vec<Diagnostic>> {
let (ast, index) = parse_checked(src, opts)?;
let place = locate(&ast, target).ok_or_else(Vec::new)?;
let mut edits = Vec::new();
let mut appended = String::new();
for &(name, value) in changes {
let text = format!("%{name}={value}");
let found = place.nodes.iter().rev().find_map(|n| match n {
Node::Param {
name: n,
ramp: None,
span,
..
} if n == name && span.source == 0 => Some(*span),
_ => None,
});
match found {
Some(span) => edits.push(Edit {
at: index.range(span),
text,
}),
None => {
appended.push(' ');
appended.push_str(&text);
}
}
}
if !appended.is_empty() {
let at = place.end(&index);
edits.push(Edit {
at: at..at,
text: appended,
});
}
finish(&index, edits, opts)
}
pub fn replace_timbre(
src: &str,
target: &TimbreTarget,
body: &str,
opts: &CompileOptions<'_>,
) -> Result<String, Vec<Diagnostic>> {
let (ast, index) = parse_checked(src, opts)?;
let place = locate(&ast, target).ok_or_else(Vec::new)?;
let spans: Vec<Span> = place.nodes.iter().filter_map(timbre_span).collect();
let mut edits = Vec::new();
if spans.is_empty() {
let at = place.end(&index);
edits.push(Edit {
at: at..at,
text: format!(" {}", body.trim()),
});
} else {
{
for (i, span) in spans.iter().enumerate() {
let r = index.range(*span);
let end = if index.chars.get(r.end) == Some(&' ') {
r.end + 1
} else {
r.end
};
let text = if i == 0 {
let mut t = body.trim().to_string();
if end > r.end {
t.push(' ');
}
t
} else {
String::new()
};
edits.push(Edit {
at: r.start..end,
text,
});
}
}
let last = edits.len() - 1;
if last > 0 && index.range(spans[last]).end == edits[last].at.end {
let mut c = last;
while c > 0 && edits[c - 1].at.end == edits[c].at.start {
c -= 1;
}
if c == 0 {
if edits[0].text.ends_with(' ') {
edits[0].text.pop();
}
} else if index.chars.get(edits[c].at.start - 1) == Some(&' ') {
edits[c].at.start -= 1;
}
}
}
finish(&index, edits, opts)
}
struct Place<'a> {
nodes: &'a [Node],
anchor: Span,
}
impl Place<'_> {
fn end(&self, index: &LineIndex) -> usize {
match self.nodes.iter().filter_map(timbre_span).next_back() {
Some(span) => index.range(span).end,
None => index.range(self.anchor).end,
}
}
}
fn locate<'a>(ast: &'a crate::Ast, target: &TimbreTarget) -> Option<Place<'a>> {
match target {
TimbreTarget::Macro(name) => {
let m = ast.macros.iter().find(|m| &m.name == name)?;
if !is_timbre_macro(m) {
return None;
}
Some(Place {
nodes: &m.nodes,
anchor: m.span,
})
}
TimbreTarget::Track(name) => {
let t = ast.tracks.iter().find(|t| &t.name == name)?;
if t.span.source != 0 {
return None;
}
Some(Place {
nodes: head(&t.nodes),
anchor: t.span,
})
}
}
}
fn timbre_span(n: &Node) -> Option<Span> {
let span = match n {
Node::Tone { span, .. }
| Node::MacroRef { span, .. }
| Node::Param {
span, ramp: None, ..
} => *span,
_ => return None,
};
(span.source == 0).then_some(span)
}
fn head(nodes: &[Node]) -> &[Node] {
let end = nodes
.iter()
.position(|n| {
matches!(
n,
Node::Note { .. }
| Node::Rest { .. }
| Node::Extend { .. }
| Node::Tie { .. }
| Node::Chord { .. }
| Node::Portamento { .. }
| Node::Loop { .. }
| Node::Shot { .. }
| Node::LoopPoint { .. }
| Node::Error { .. }
| Node::Param { ramp: Some(_), .. }
)
})
.unwrap_or(nodes.len());
&nodes[..end]
}
fn is_timbre_macro(m: &MacroDef) -> bool {
m.span.source == 0
&& head(&m.nodes).len() == m.nodes.len()
&& m.nodes
.iter()
.any(|n| matches!(n, Node::Tone { .. } | Node::Param { .. }))
}
fn empty(target: TimbreTarget) -> Timbre {
Timbre {
target,
tone: None,
params: Vec::new(),
macros: Vec::new(),
}
}
fn collect(nodes: &[Node], macros: &[MacroDef], t: &mut Timbre, depth: u8) {
for n in nodes {
match n {
Node::Tone { value, .. } => t.tone = Some(*value),
Node::Param {
name,
value,
ramp: None,
..
} => match t.params.iter_mut().find(|(k, _)| k == name) {
Some(p) => p.1 = *value,
None => t.params.push((name.clone(), *value)),
},
Node::MacroRef { name, .. } => {
if depth == 0 {
t.macros.push(name.clone());
}
if depth < 8 {
if let Some(m) = macros.iter().find(|m| &m.name == name) {
collect(head(&m.nodes), macros, t, depth + 1);
}
}
}
_ => {}
}
}
}
fn parse_checked(
src: &str,
opts: &CompileOptions<'_>,
) -> Result<(crate::Ast, LineIndex), Vec<Diagnostic>> {
let (song, diags) = crate::compile_with(src, opts);
if song.is_none() {
return Err(diags.into_iter().filter(|d| d.is_error()).collect());
}
let (ast, _) = crate::parse_with_options(src, opts);
Ok((ast, LineIndex::new(src)))
}
fn finish(
index: &LineIndex,
edits: Vec<Edit>,
opts: &CompileOptions<'_>,
) -> Result<String, Vec<Diagnostic>> {
let text = apply(&index.chars, edits);
let (song, diags) = crate::compile_with(&text, opts);
if song.is_none() {
return Err(diags.into_iter().filter(|d| d.is_error()).collect());
}
Ok(text)
}