use core::ops::Range;
use crate::compiler::ast::{ChordNote, Node, Pitch};
use crate::{CompileOptions, Diagnostic, Dialect, Span};
mod format;
pub use format::{format, FormatOptions};
mod timbre;
pub use timbre::{replace_timbre, set_timbre_params, timbres, Timbre, TimbreTarget};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Transposed {
pub text: String,
pub notes: usize,
pub skipped_macro_refs: Vec<Span>,
}
pub fn transpose(
src: &str,
range: Range<usize>,
semitones: i32,
opts: &CompileOptions<'_>,
) -> Result<Transposed, 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(src, &opts.dialect);
let dialect = Dialect::builtin(&ast.dialect).unwrap_or(opts.dialect);
let index = LineIndex::new(src);
let mut edits: Vec<Edit> = Vec::new();
let mut notes = 0usize;
let mut skipped = Vec::new();
let ctx = Ctx {
src_chars: &index.chars,
index: &index,
range: &range,
semitones,
dialect: &dialect,
};
for m in &ast.macros {
ctx.walk(&m.nodes, None, &mut edits, &mut notes, &mut skipped);
}
for t in &ast.tracks {
ctx.walk(&t.nodes, None, &mut edits, &mut notes, &mut skipped);
}
if semitones == 0 {
return Ok(Transposed {
text: src.to_string(),
notes,
skipped_macro_refs: skipped,
});
}
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(Transposed {
text,
notes,
skipped_macro_refs: skipped,
})
}
pub fn note_text(
key: u8,
length: Option<u32>,
octave: u8,
dialect: &Dialect,
) -> Option<(String, u8)> {
let k = key as i32;
let target = k / 12 - 1;
if !(0..=9).contains(&target) {
return None;
}
let (up, down) = octave_chars(dialect);
let mut s = String::new();
match target - octave as i32 {
0 => {}
1 => s.push(up),
-1 => s.push(down),
_ => s.push_str(&format!("o{}", target)),
}
s.push_str(NAMES[(k % 12) as usize]);
if let Some(l) = length {
s.push_str(&l.to_string());
}
Some((s, target as u8))
}
pub fn octave_at(src: &str, cursor: usize, opts: &CompileOptions<'_>) -> Option<u8> {
let index = LineIndex::new(src);
let line = index.starts.partition_point(|&s| s <= cursor).max(1) - 1;
let name = *index.chars.get(index.starts[line])?;
if !name.is_ascii_uppercase() {
return None;
}
let (ast, _) = crate::parse_with(src, &opts.dialect);
let mut oct = Octave {
value: 4,
ast: &ast,
index: &index,
cursor,
};
if let Some(t) = ast.tracks.iter().find(|t| t.name == name.to_string()) {
oct.until(&t.nodes);
}
Some(oct.value as u8)
}
struct Octave<'a> {
value: i32,
ast: &'a crate::Ast,
index: &'a LineIndex,
cursor: usize,
}
impl Octave<'_> {
fn until(&mut self, nodes: &[Node]) -> bool {
for n in nodes {
let r = self.index.range(crate::compiler::song::node_span(n));
if r.start >= self.cursor {
return true;
}
if let Node::Loop { body, .. } = n {
if self.cursor < self.end(n) {
return self.until(body);
}
}
self.apply(n, 0);
}
false
}
fn end(&self, n: &Node) -> usize {
let r = self.index.range(crate::compiler::song::node_span(n));
let Node::Loop { body, .. } = n else {
return r.end;
};
let chars = &self.index.chars;
let mut i = body.last().map_or(r.end, |b| self.end(b)).max(r.end);
while i < chars.len() {
match chars[i] {
c if c.is_whitespace() => i += 1,
';' => {
while i < chars.len() && chars[i] != '\n' {
i += 1;
}
}
']' => {
i += 1;
while i < chars.len() && chars[i].is_ascii_digit() {
i += 1;
}
return i;
}
_ => return i,
}
}
i
}
fn apply(&mut self, n: &Node, depth: u8) {
match n {
Node::Octave { value, .. } => self.value = i32::from(*value),
Node::OctaveUp { .. } => self.value += 1,
Node::OctaveDown { .. } => self.value -= 1,
Node::Portamento { shift, .. } => self.value += i32::from(*shift),
Node::Loop {
body,
break_at,
count,
..
} => {
for i in 0..*count {
let last = i + 1 == *count;
let end = if last {
break_at.unwrap_or(body.len())
} else {
body.len()
};
for b in &body[..end] {
self.apply(b, depth);
}
}
}
Node::MacroRef { name, .. } if depth < 8 => {
let ast = self.ast;
if let Some(m) = ast.macros.iter().find(|m| &m.name == name) {
for b in &m.nodes {
self.apply(b, depth + 1);
}
}
}
_ => {}
}
self.value = self.value.clamp(0, 9);
}
}
const NAMES: [&str; 12] = [
"c", "c+", "d", "d+", "e", "f", "f+", "g", "g+", "a", "a+", "b",
];
fn octave_chars(dialect: &Dialect) -> (char, char) {
if dialect.octave_reversed {
('<', '>')
} else {
('>', '<')
}
}
fn shift_pitch(p: &Pitch, semitones: i32) -> (&'static str, i32) {
let n = p.semitone() + semitones;
(NAMES[n.rem_euclid(12) as usize], n.div_euclid(12))
}
struct Edit {
at: Range<usize>,
text: String,
}
struct LineIndex {
chars: Vec<char>,
starts: Vec<usize>,
}
impl LineIndex {
fn new(src: &str) -> Self {
let chars: Vec<char> = src.chars().collect();
let mut starts = vec![0];
for (i, c) in chars.iter().enumerate() {
if *c == '\n' {
starts.push(i + 1);
}
}
LineIndex { chars, starts }
}
fn range(&self, span: Span) -> Range<usize> {
let start = self.starts[(span.line as usize).saturating_sub(1)] + span.col as usize - 1;
start..start + span.len as usize
}
}
struct Ctx<'a> {
src_chars: &'a [char],
index: &'a LineIndex,
range: &'a Range<usize>,
semitones: i32,
dialect: &'a Dialect,
}
struct Group {
carry: i32,
line: u32,
start: usize,
end: usize,
}
impl Ctx<'_> {
fn inside(&self, r: &Range<usize>) -> bool {
self.range.start <= r.start && r.end <= self.range.end
}
fn pitch_part(&self, r: &Range<usize>) -> Range<usize> {
let mut end = r.start + 1;
let mut j = end;
while j < r.end {
match self.src_chars[j] {
'+' | '-' | '#' => {
j += 1;
end = j;
}
c if c.is_whitespace() => j += 1,
_ => break,
}
}
r.start..end
}
fn walk(
&self,
nodes: &[Node],
brk: Option<usize>,
edits: &mut Vec<Edit>,
notes: &mut usize,
skipped: &mut Vec<Span>,
) {
let (up, down) = octave_chars(self.dialect);
let mut group: Option<Group> = None;
let close = |g: Option<Group>, edits: &mut Vec<Edit>| {
if let Some(g) = g {
if g.carry != 0 {
let (open, shut) = if g.carry > 0 { (up, down) } else { (down, up) };
let n = g.carry.unsigned_abs() as usize;
edits.push(Edit {
at: g.start..g.start,
text: open.to_string().repeat(n),
});
edits.push(Edit {
at: g.end..g.end,
text: shut.to_string().repeat(n),
});
}
}
};
for (i, node) in nodes.iter().enumerate() {
if brk == Some(i) {
close(group.take(), edits);
}
match node {
Node::Note { pitch, span, .. } => {
let r = self.index.range(*span);
if !self.inside(&r) {
close(group.take(), edits);
continue;
}
*notes += 1;
let (name, carry) = shift_pitch(pitch, self.semitones);
edits.push(Edit {
at: self.pitch_part(&r),
text: name.to_string(),
});
match &mut group {
Some(g) if g.carry == carry && g.line == span.line => g.end = r.end,
_ => {
close(group.take(), edits);
group = Some(Group {
carry,
line: span.line,
start: r.start,
end: r.end,
});
}
}
}
Node::Extend { span, .. } | Node::Tie { span } => {
if let Some(g) = &mut group {
g.end = self.index.range(*span).end;
}
}
Node::Rest { .. }
| Node::DefaultLength { .. }
| Node::Tempo { .. }
| Node::Volume { .. }
| Node::VolumeRel { .. }
| Node::Transpose { .. }
| Node::Gate { .. }
| Node::GateCut { .. }
| Node::Mark { .. }
| Node::Swing { .. }
| Node::BarCheck { .. }
| Node::Shot { .. }
| Node::Tone { .. }
| Node::Param { .. }
| Node::Envelope { .. }
| Node::Vibrato { .. }
| Node::Detune { .. }
| Node::Arp { .. }
| Node::Duty { .. }
| Node::Wave { .. } => {}
Node::Loop { body, break_at, .. } => {
close(group.take(), edits);
self.walk(body, *break_at, edits, notes, skipped);
}
Node::MacroRef { span, .. } => {
close(group.take(), edits);
if self.inside(&self.index.range(*span)) {
skipped.push(*span);
}
}
Node::Portamento {
from,
to,
shift,
span,
..
} => {
close(group.take(), edits);
let r = self.index.range(*span);
if self.inside(&r) {
*notes += 2;
edits.extend(self.portamento(&r, from, to, *shift, up, down));
}
}
Node::Chord {
notes: chord, span, ..
} => {
close(group.take(), edits);
let r = self.index.range(*span);
if self.inside(&r) {
*notes += chord.len();
edits.extend(self.chord(&r, chord, up, down));
}
}
Node::Octave { .. }
| Node::OctaveUp { .. }
| Node::OctaveDown { .. }
| Node::LoopPoint { .. }
| Node::Error { .. } => close(group.take(), edits),
}
}
close(group, edits);
}
fn chord(&self, r: &Range<usize>, chord: &[ChordNote], up: char, down: char) -> Vec<Edit> {
let close = (r.start + 1..r.end)
.rev()
.find(|&i| self.src_chars[i] == '\'')
.unwrap_or(r.end);
let mut text = String::from("'");
let mut cur = 0i32;
for (i, n) in chord.iter().enumerate() {
let (name, carry) = shift_pitch(&n.pitch, self.semitones);
let want = i32::from(n.octave) + carry;
if i > 0 {
text.push(' ');
}
let c = if want > cur { up } else { down };
for _ in 0..(want - cur).unsigned_abs() {
text.push(c);
}
text.push_str(name);
cur = want;
}
vec![Edit {
at: r.start..close,
text,
}]
}
fn portamento(
&self,
r: &Range<usize>,
from: &Pitch,
to: &Pitch,
shift: i8,
up: char,
down: char,
) -> Vec<Edit> {
let (from_name, fc) = shift_pitch(from, self.semitones);
let (to_name, tc) = shift_pitch(to, self.semitones);
let inner = shift as i32 + tc - fc;
let rep = |n: i32| {
let c = if n > 0 { up } else { down };
c.to_string().repeat(n.unsigned_abs() as usize)
};
let close = (r.start..r.end)
.find(|&i| self.src_chars[i] == '}')
.unwrap_or(r.end);
let mut inside = String::from("{");
inside.push_str(from_name);
inside.push(' ');
inside.push_str(&rep(inner));
inside.push_str(to_name);
vec![
Edit {
at: r.start..r.start,
text: rep(fc),
},
Edit {
at: r.start..close,
text: inside,
},
Edit {
at: r.end..r.end,
text: rep(-tc),
},
]
}
}
fn apply(chars: &[char], mut edits: Vec<Edit>) -> String {
edits.sort_by_key(|e| (e.at.start, e.at.end > e.at.start));
let mut out = String::with_capacity(chars.len() + 16);
let mut pos = 0;
for e in edits {
if e.at.start < pos {
continue;
}
out.extend(&chars[pos..e.at.start]);
out.push_str(&e.text);
pos = e.at.end;
}
out.extend(&chars[pos..]);
out
}