This commit is contained in:
2026-01-26 12:22:44 +01:00
parent 223679acf8
commit 9e597258e4
14 changed files with 1030 additions and 884 deletions

View File

@@ -94,8 +94,8 @@ fn tokenize(input: &str) -> Vec<Token> {
fn compile(tokens: &[Token], dict: &Dictionary) -> Result<Vec<Op>, String> {
let mut ops = Vec::new();
let mut i = 0;
let mut pipe_parity = false;
let mut list_depth: usize = 0;
let mut pipe_parity = false;
while i < tokens.len() {
match &tokens[i] {
@@ -119,15 +119,6 @@ fn compile(tokens: &[Token], dict: &Dictionary) -> Result<Vec<Op>, String> {
dict.lock().unwrap().insert(name, body);
} else if word == ";" {
return Err("unexpected ;".into());
} else if word == "|" {
if pipe_parity {
ops.push(Op::LocalCycleEnd);
list_depth = list_depth.saturating_sub(1);
} else {
ops.push(Op::ListStart);
list_depth += 1;
}
pipe_parity = !pipe_parity;
} else if word == "if" {
let (then_ops, else_ops, consumed, then_span, else_span) = compile_if(&tokens[i + 1..], dict)?;
i += consumed;
@@ -140,6 +131,13 @@ fn compile(tokens: &[Token], dict: &Dictionary) -> Result<Vec<Op>, String> {
ops.push(Op::Branch(else_ops.len()));
ops.extend(else_ops);
}
} else if word == "|" {
if pipe_parity {
ops.push(Op::InternalCycleEnd);
} else {
ops.push(Op::ListStart);
}
pipe_parity = !pipe_parity;
} else if is_list_start(word) {
ops.push(Op::ListStart);
list_depth += 1;

View File

@@ -6,5 +6,5 @@ mod vm;
mod words;
pub use types::{Dictionary, ExecutionTrace, Rng, SourceSpan, StepContext, Value, Variables};
pub use vm::Forth;
pub use vm::{EmissionCounter, Forth};
pub use words::{Word, WordCompile, WORDS};

View File

@@ -39,6 +39,7 @@ pub enum Op {
NewCmd,
SetParam(String),
Emit,
Silence,
Get,
Set,
GetContext(String),
@@ -56,24 +57,14 @@ pub enum Op {
ListEndCycle,
PCycle,
ListEndPCycle,
At,
Window,
Scale,
Pop,
Subdivide,
SetTempo,
Each,
Every,
Quotation(Vec<Op>, Option<SourceSpan>),
When,
Unless,
Adsr,
Ad,
Stack,
For,
LocalCycleEnd,
Echo,
Necho,
Apply,
Ramp,
Range,
@@ -82,4 +73,9 @@ pub enum Op {
Loop,
Degree(&'static [i64]),
Oct,
InternalCycleEnd,
DivStart,
DivEnd,
StackStart,
EmitN,
}

View File

@@ -48,6 +48,7 @@ pub enum Value {
Str(String, Option<SourceSpan>),
Marker,
Quotation(Vec<Op>, Option<SourceSpan>),
Alternator(Vec<Value>),
}
impl PartialEq for Value {
@@ -58,6 +59,7 @@ impl PartialEq for Value {
(Value::Str(a, _), Value::Str(b, _)) => a == b,
(Value::Marker, Value::Marker) => true,
(Value::Quotation(a, _), Value::Quotation(b, _)) => a == b,
(Value::Alternator(a), Value::Alternator(b)) => a == b,
_ => false,
}
}
@@ -94,6 +96,7 @@ impl Value {
Value::Str(s, _) => !s.is_empty(),
Value::Marker => false,
Value::Quotation(..) => true,
Value::Alternator(items) => !items.is_empty(),
}
}
@@ -108,35 +111,75 @@ impl Value {
Value::Str(s, _) => s.clone(),
Value::Marker => String::new(),
Value::Quotation(..) => String::new(),
Value::Alternator(_) => String::new(),
}
}
pub(super) fn span(&self) -> Option<SourceSpan> {
match self {
Value::Int(_, s) | Value::Float(_, s) | Value::Str(_, s) => *s,
Value::Marker | Value::Quotation(..) => None,
Value::Marker | Value::Quotation(..) | Value::Alternator(_) => None,
}
}
}
#[derive(Clone, Debug, Default)]
pub(super) struct CmdRegister {
sound: Option<String>,
params: Vec<(String, String)>,
sound: Option<Value>,
params: Vec<(String, Value)>,
}
impl CmdRegister {
pub(super) fn set_sound(&mut self, name: String) {
self.sound = Some(name);
pub(super) fn set_sound(&mut self, val: Value) {
self.sound = Some(val);
}
pub(super) fn set_param(&mut self, key: String, value: String) {
self.params.push((key, value));
pub(super) fn set_param(&mut self, key: String, val: Value) {
self.params.push((key, val));
}
pub(super) fn take(&mut self) -> Option<(String, Vec<(String, String)>)> {
let sound = self.sound.take()?;
let params = std::mem::take(&mut self.params);
Some((sound, params))
pub(super) fn snapshot(&self) -> Option<(Value, Vec<(String, Value)>)> {
self.sound.as_ref().map(|s| (s.clone(), self.params.clone()))
}
}
#[derive(Clone, Debug)]
pub(super) struct PendingEmission {
pub sound: String,
pub params: Vec<(String, String)>,
pub slot_index: usize,
}
#[derive(Clone, Debug)]
pub(super) struct ScopeContext {
pub start: f64,
pub duration: f64,
pub weight: f64,
pub slot_count: usize,
pub pending: Vec<PendingEmission>,
pub stacked: bool,
}
impl ScopeContext {
pub fn new(start: f64, duration: f64) -> Self {
Self {
start,
duration,
weight: 1.0,
slot_count: 0,
pending: Vec::new(),
stacked: false,
}
}
pub fn claim_slot(&mut self) -> usize {
if self.stacked {
self.slot_count = 1;
0
} else {
let idx = self.slot_count;
self.slot_count += 1;
idx
}
}
}

View File

@@ -4,22 +4,18 @@ use rand::{Rng as RngTrait, SeedableRng};
use super::compiler::compile_script;
use super::ops::Op;
use super::types::{
CmdRegister, Dictionary, ExecutionTrace, Rng, Stack, StepContext, Value, Variables,
CmdRegister, Dictionary, ExecutionTrace, PendingEmission, Rng, ScopeContext, SourceSpan, Stack,
StepContext, Value, Variables,
};
#[derive(Clone, Debug)]
struct TimeContext {
start: f64,
duration: f64,
subdivisions: Option<Vec<(f64, f64)>>,
iteration_index: Option<usize>,
}
pub type EmissionCounter = std::sync::Arc<std::sync::Mutex<usize>>;
pub struct Forth {
stack: Stack,
vars: Variables,
dict: Dictionary,
rng: Rng,
emission_count: EmissionCounter,
}
impl Forth {
@@ -29,6 +25,22 @@ impl Forth {
vars,
dict,
rng,
emission_count: std::sync::Arc::new(std::sync::Mutex::new(0)),
}
}
pub fn new_with_counter(
vars: Variables,
dict: Dictionary,
rng: Rng,
emission_count: EmissionCounter,
) -> Self {
Self {
stack: std::sync::Arc::new(std::sync::Mutex::new(Vec::new())),
vars,
dict,
rng,
emission_count,
}
}
@@ -77,37 +89,42 @@ impl Forth {
) -> Result<Vec<String>, String> {
let mut stack = self.stack.lock().unwrap();
let mut outputs: Vec<String> = Vec::new();
let mut time_stack: Vec<TimeContext> = vec![TimeContext {
start: 0.0,
duration: ctx.step_duration() * 4.0,
subdivisions: None,
iteration_index: None,
}];
let root_duration = ctx.step_duration() * 4.0;
let mut scope_stack: Vec<ScopeContext> = vec![ScopeContext::new(0.0, root_duration)];
let mut cmd = CmdRegister::default();
let mut emission_count = self.emission_count.lock().unwrap();
self.execute_ops(
ops,
ctx,
&mut stack,
&mut outputs,
&mut time_stack,
&mut scope_stack,
&mut cmd,
trace,
&mut emission_count,
)?;
// Resolve root scope at end of script
if let Some(scope) = scope_stack.pop() {
resolve_scope(&scope, &mut outputs);
}
Ok(outputs)
}
#[allow(clippy::too_many_arguments)]
#[allow(clippy::only_used_in_recursion)]
fn execute_ops(
&self,
ops: &[Op],
ctx: &StepContext,
stack: &mut Vec<Value>,
outputs: &mut Vec<String>,
time_stack: &mut Vec<TimeContext>,
scope_stack: &mut Vec<ScopeContext>,
cmd: &mut CmdRegister,
trace: Option<&mut ExecutionTrace>,
emission_count: &mut usize,
) -> Result<(), String> {
let mut pc = 0;
let trace_cell = std::cell::RefCell::new(trace);
@@ -176,37 +193,30 @@ impl Forth {
Op::Mul => binary_op(stack, |a, b| a * b)?,
Op::Div => binary_op(stack, |a, b| a / b)?,
Op::Mod => {
let b = stack.pop().ok_or("stack underflow")?.as_int()?;
let a = stack.pop().ok_or("stack underflow")?.as_int()?;
stack.push(Value::Int(a % b, None));
let b = stack.pop().ok_or("stack underflow")?;
let a = stack.pop().ok_or("stack underflow")?;
let result = lift_binary(a, b, |x, y| (x as i64 % y as i64) as f64)?;
stack.push(result);
}
Op::Neg => {
let v = stack.pop().ok_or("stack underflow")?;
match v {
Value::Int(i, s) => stack.push(Value::Int(-i, s)),
Value::Float(f, s) => stack.push(Value::Float(-f, s)),
_ => return Err("expected number".into()),
}
stack.push(lift_unary(v, |x| -x)?);
}
Op::Abs => {
let v = stack.pop().ok_or("stack underflow")?;
match v {
Value::Int(i, s) => stack.push(Value::Int(i.abs(), s)),
Value::Float(f, s) => stack.push(Value::Float(f.abs(), s)),
_ => return Err("expected number".into()),
}
stack.push(lift_unary(v, |x| x.abs())?);
}
Op::Floor => {
let v = stack.pop().ok_or("stack underflow")?.as_float()?;
stack.push(Value::Int(v.floor() as i64, None));
let v = stack.pop().ok_or("stack underflow")?;
stack.push(lift_unary(v, |x| x.floor())?);
}
Op::Ceil => {
let v = stack.pop().ok_or("stack underflow")?.as_float()?;
stack.push(Value::Int(v.ceil() as i64, None));
let v = stack.pop().ok_or("stack underflow")?;
stack.push(lift_unary(v, |x| x.ceil())?);
}
Op::Round => {
let v = stack.pop().ok_or("stack underflow")?.as_float()?;
stack.push(Value::Int(v.round() as i64, None));
let v = stack.pop().ok_or("stack underflow")?;
stack.push(lift_unary(v, |x| x.round())?);
}
Op::Min => binary_op(stack, |a, b| a.min(b))?,
Op::Max => binary_op(stack, |a, b| a.max(b))?,
@@ -253,32 +263,61 @@ impl Forth {
}
Op::NewCmd => {
let name = stack.pop().ok_or("stack underflow")?;
let name = name.as_str()?;
cmd.set_sound(name.to_string());
let val = stack.pop().ok_or("stack underflow")?;
cmd.set_sound(val);
}
Op::SetParam(param) => {
let val = stack.pop().ok_or("stack underflow")?;
cmd.set_param(param.clone(), val.to_param_string());
cmd.set_param(param.clone(), val);
}
Op::Emit => {
let (sound, mut params) = cmd.take().ok_or("no sound set")?;
let mut pairs = vec![("sound".into(), sound)];
pairs.append(&mut params);
let time_ctx = time_stack.last().ok_or("time stack underflow")?;
if time_ctx.start > 0.0 {
pairs.push(("delta".into(), time_ctx.start.to_string()));
let (sound_val, params) = cmd.snapshot().ok_or("no sound set")?;
// Resolve alternators using emission count, tracking selected spans
let (resolved_sound, sound_span) =
resolve_value_with_span(&sound_val, *emission_count);
if let Some(span) = sound_span {
if let Some(trace) = trace_cell.borrow_mut().as_mut() {
trace.selected_spans.push(span);
}
}
if !pairs.iter().any(|(k, _)| k == "dur") {
pairs.push(("dur".into(), time_ctx.duration.to_string()));
}
if let Some(idx) = pairs.iter().position(|(k, _)| k == "delaytime") {
let ratio: f64 = pairs[idx].1.parse().unwrap_or(1.0);
pairs[idx].1 = (ratio * time_ctx.duration).to_string();
} else {
pairs.push(("delaytime".into(), time_ctx.duration.to_string()));
}
outputs.push(format_cmd(&pairs));
let sound = resolved_sound.as_str()?.to_string();
let resolved_params: Vec<(String, String)> = params
.iter()
.map(|(k, v)| {
let (resolved, param_span) =
resolve_value_with_span(v, *emission_count);
if let Some(span) = param_span {
if let Some(trace) = trace_cell.borrow_mut().as_mut() {
trace.selected_spans.push(span);
}
}
(k.clone(), resolved.to_param_string())
})
.collect();
let scope = scope_stack.last_mut().ok_or("scope stack underflow")?;
let slot_idx = scope.claim_slot();
scope.pending.push(PendingEmission {
sound,
params: resolved_params,
slot_index: slot_idx,
});
*emission_count += 1;
}
Op::Silence => {
let scope = scope_stack.last_mut().ok_or("scope stack underflow")?;
scope.claim_slot();
}
Op::Scale => {
let factor = stack.pop().ok_or("stack underflow")?.as_float()?;
let scope = scope_stack.last_mut().ok_or("scope stack underflow")?;
scope.weight = factor;
}
Op::Get => {
@@ -359,7 +398,16 @@ impl Forth {
}
}
let mut trace_opt = trace_cell.borrow_mut().take();
self.execute_ops(&quot_ops, ctx, stack, outputs, time_stack, cmd, trace_opt.as_deref_mut())?;
self.execute_ops(
&quot_ops,
ctx,
stack,
outputs,
scope_stack,
cmd,
trace_opt.as_deref_mut(),
emission_count,
)?;
*trace_cell.borrow_mut() = trace_opt;
} else {
stack.push(selected);
@@ -390,7 +438,16 @@ impl Forth {
}
}
let mut trace_opt = trace_cell.borrow_mut().take();
self.execute_ops(&quot_ops, ctx, stack, outputs, time_stack, cmd, trace_opt.as_deref_mut())?;
self.execute_ops(
&quot_ops,
ctx,
stack,
outputs,
scope_stack,
cmd,
trace_opt.as_deref_mut(),
emission_count,
)?;
*trace_cell.borrow_mut() = trace_opt;
} else {
stack.push(selected);
@@ -421,7 +478,16 @@ impl Forth {
}
}
let mut trace_opt = trace_cell.borrow_mut().take();
self.execute_ops(&quot_ops, ctx, stack, outputs, time_stack, cmd, trace_opt.as_deref_mut())?;
self.execute_ops(
&quot_ops,
ctx,
stack,
outputs,
scope_stack,
cmd,
trace_opt.as_deref_mut(),
emission_count,
)?;
*trace_cell.borrow_mut() = trace_opt;
} else {
stack.push(selected);
@@ -441,7 +507,16 @@ impl Forth {
}
}
let mut trace_opt = trace_cell.borrow_mut().take();
self.execute_ops(&quot_ops, ctx, stack, outputs, time_stack, cmd, trace_opt.as_deref_mut())?;
self.execute_ops(
&quot_ops,
ctx,
stack,
outputs,
scope_stack,
cmd,
trace_opt.as_deref_mut(),
emission_count,
)?;
*trace_cell.borrow_mut() = trace_opt;
}
_ => return Err("expected quotation".into()),
@@ -462,7 +537,16 @@ impl Forth {
}
}
let mut trace_opt = trace_cell.borrow_mut().take();
self.execute_ops(&quot_ops, ctx, stack, outputs, time_stack, cmd, trace_opt.as_deref_mut())?;
self.execute_ops(
&quot_ops,
ctx,
stack,
outputs,
scope_stack,
cmd,
trace_opt.as_deref_mut(),
emission_count,
)?;
*trace_cell.borrow_mut() = trace_opt;
}
_ => return Err("expected quotation".into()),
@@ -500,7 +584,16 @@ impl Forth {
}
}
let mut trace_opt = trace_cell.borrow_mut().take();
self.execute_ops(&quot_ops, ctx, stack, outputs, time_stack, cmd, trace_opt.as_deref_mut())?;
self.execute_ops(
&quot_ops,
ctx,
stack,
outputs,
scope_stack,
cmd,
trace_opt.as_deref_mut(),
emission_count,
)?;
*trace_cell.borrow_mut() = trace_opt;
}
_ => return Err("expected quotation".into()),
@@ -520,7 +613,16 @@ impl Forth {
}
}
let mut trace_opt = trace_cell.borrow_mut().take();
self.execute_ops(&quot_ops, ctx, stack, outputs, time_stack, cmd, trace_opt.as_deref_mut())?;
self.execute_ops(
&quot_ops,
ctx,
stack,
outputs,
scope_stack,
cmd,
trace_opt.as_deref_mut(),
emission_count,
)?;
*trace_cell.borrow_mut() = trace_opt;
}
_ => return Err("expected quotation".into()),
@@ -541,102 +643,21 @@ impl Forth {
}
Op::Degree(pattern) => {
let degree = stack.pop().ok_or("stack underflow")?.as_int()?;
let val = stack.pop().ok_or("stack underflow")?;
let len = pattern.len() as i64;
let octave_offset = degree.div_euclid(len);
let idx = degree.rem_euclid(len) as usize;
let midi = 60 + octave_offset * 12 + pattern[idx];
stack.push(Value::Int(midi, None));
let result = lift_unary_int(val, |degree| {
let octave_offset = degree.div_euclid(len);
let idx = degree.rem_euclid(len) as usize;
60 + octave_offset * 12 + pattern[idx]
})?;
stack.push(result);
}
Op::Oct => {
let shift = stack.pop().ok_or("stack underflow")?.as_int()?;
let note = stack.pop().ok_or("stack underflow")?.as_int()?;
stack.push(Value::Int(note + shift * 12, None));
}
Op::At => {
let pos = stack.pop().ok_or("stack underflow")?.as_float()?;
let parent = time_stack.last().ok_or("time stack underflow")?;
let new_start = parent.start + parent.duration * pos;
time_stack.push(TimeContext {
start: new_start,
duration: parent.duration * (1.0 - pos),
subdivisions: None,
iteration_index: parent.iteration_index,
});
}
Op::Window => {
let end = stack.pop().ok_or("stack underflow")?.as_float()?;
let start_pos = stack.pop().ok_or("stack underflow")?.as_float()?;
let parent = time_stack.last().ok_or("time stack underflow")?;
let new_start = parent.start + parent.duration * start_pos;
let new_duration = parent.duration * (end - start_pos);
time_stack.push(TimeContext {
start: new_start,
duration: new_duration,
subdivisions: None,
iteration_index: parent.iteration_index,
});
}
Op::Scale => {
let factor = stack.pop().ok_or("stack underflow")?.as_float()?;
let parent = time_stack.last().ok_or("time stack underflow")?;
time_stack.push(TimeContext {
start: parent.start,
duration: parent.duration * factor,
subdivisions: None,
iteration_index: parent.iteration_index,
});
}
Op::Pop => {
if time_stack.len() <= 1 {
return Err("cannot pop root time context".into());
}
time_stack.pop();
}
Op::Subdivide => {
let n = stack.pop().ok_or("stack underflow")?.as_int()? as usize;
if n == 0 {
return Err("subdivide count must be > 0".into());
}
let time_ctx = time_stack.last_mut().ok_or("time stack underflow")?;
let sub_duration = time_ctx.duration / n as f64;
let mut subs = Vec::with_capacity(n);
for i in 0..n {
subs.push((time_ctx.start + sub_duration * i as f64, sub_duration));
}
time_ctx.subdivisions = Some(subs);
}
Op::Each => {
let (sound, params) = cmd.take().ok_or("no sound set")?;
let time_ctx = time_stack.last().ok_or("time stack underflow")?;
let subs = time_ctx
.subdivisions
.as_ref()
.ok_or("each requires subdivide first")?;
for (sub_start, sub_dur) in subs {
let mut pairs = vec![("sound".into(), sound.clone())];
pairs.extend(params.iter().cloned());
if *sub_start > 0.0 {
pairs.push(("delta".into(), sub_start.to_string()));
}
if !pairs.iter().any(|(k, _)| k == "dur") {
pairs.push(("dur".into(), sub_dur.to_string()));
}
if let Some(idx) = pairs.iter().position(|(k, _)| k == "delaytime") {
let ratio: f64 = pairs[idx].1.parse().unwrap_or(1.0);
pairs[idx].1 = (ratio * sub_dur).to_string();
} else {
pairs.push(("delaytime".into(), sub_dur.to_string()));
}
outputs.push(format_cmd(&pairs));
}
let shift = stack.pop().ok_or("stack underflow")?;
let note = stack.pop().ok_or("stack underflow")?;
let result = lift_binary(note, shift, |n, s| n + s * 12.0)?;
stack.push(result);
}
Op::SetTempo => {
@@ -669,8 +690,8 @@ impl Forth {
Op::Loop => {
let beats = stack.pop().ok_or("stack underflow")?.as_float()?;
let dur = beats * 60.0 / ctx.tempo / ctx.speed;
cmd.set_param("fit".into(), dur.to_string());
cmd.set_param("dur".into(), dur.to_string());
cmd.set_param("fit".into(), Value::Float(dur, None));
cmd.set_param("dur".into(), Value::Float(dur, None));
}
Op::ListStart => {
@@ -720,7 +741,16 @@ impl Forth {
}
}
let mut trace_opt = trace_cell.borrow_mut().take();
self.execute_ops(&quot_ops, ctx, stack, outputs, time_stack, cmd, trace_opt.as_deref_mut())?;
self.execute_ops(
&quot_ops,
ctx,
stack,
outputs,
scope_stack,
cmd,
trace_opt.as_deref_mut(),
emission_count,
)?;
*trace_cell.borrow_mut() = trace_opt;
} else {
stack.push(selected);
@@ -753,7 +783,16 @@ impl Forth {
}
}
let mut trace_opt = trace_cell.borrow_mut().take();
self.execute_ops(&quot_ops, ctx, stack, outputs, time_stack, cmd, trace_opt.as_deref_mut())?;
self.execute_ops(
&quot_ops,
ctx,
stack,
outputs,
scope_stack,
cmd,
trace_opt.as_deref_mut(),
emission_count,
)?;
*trace_cell.borrow_mut() = trace_opt;
} else {
stack.push(selected);
@@ -765,149 +804,18 @@ impl Forth {
let s = stack.pop().ok_or("stack underflow")?;
let d = stack.pop().ok_or("stack underflow")?;
let a = stack.pop().ok_or("stack underflow")?;
cmd.set_param("attack".into(), a.to_param_string());
cmd.set_param("decay".into(), d.to_param_string());
cmd.set_param("sustain".into(), s.to_param_string());
cmd.set_param("release".into(), r.to_param_string());
cmd.set_param("attack".into(), a);
cmd.set_param("decay".into(), d);
cmd.set_param("sustain".into(), s);
cmd.set_param("release".into(), r);
}
Op::Ad => {
let d = stack.pop().ok_or("stack underflow")?;
let a = stack.pop().ok_or("stack underflow")?;
cmd.set_param("attack".into(), a.to_param_string());
cmd.set_param("decay".into(), d.to_param_string());
cmd.set_param("sustain".into(), "0".into());
}
Op::Stack => {
let n = stack.pop().ok_or("stack underflow")?.as_int()? as usize;
if n == 0 {
return Err("stack count must be > 0".into());
}
let time_ctx = time_stack.last_mut().ok_or("time stack underflow")?;
let sub_duration = time_ctx.duration / n as f64;
let mut subs = Vec::with_capacity(n);
for _ in 0..n {
subs.push((time_ctx.start, sub_duration));
}
time_ctx.subdivisions = Some(subs);
}
Op::Echo => {
let n = stack.pop().ok_or("stack underflow")?.as_int()? as usize;
if n == 0 {
return Err("echo count must be > 0".into());
}
let time_ctx = time_stack.last_mut().ok_or("time stack underflow")?;
// Geometric series: d1 * (2 - 2^(1-n)) = total
let d1 = time_ctx.duration / (2.0 - 2.0_f64.powi(1 - n as i32));
let mut subs = Vec::with_capacity(n);
for i in 0..n {
let dur = d1 / 2.0_f64.powi(i as i32);
let start = if i == 0 {
time_ctx.start
} else {
time_ctx.start + d1 * (2.0 - 2.0_f64.powi(1 - i as i32))
};
subs.push((start, dur));
}
time_ctx.subdivisions = Some(subs);
}
Op::Necho => {
let n = stack.pop().ok_or("stack underflow")?.as_int()? as usize;
if n == 0 {
return Err("necho count must be > 0".into());
}
let time_ctx = time_stack.last_mut().ok_or("time stack underflow")?;
// Reverse geometric: d1 + 2*d1 + 4*d1 + ... = d1 * (2^n - 1) = total
let d1 = time_ctx.duration / (2.0_f64.powi(n as i32) - 1.0);
let mut subs = Vec::with_capacity(n);
for i in 0..n {
let dur = d1 * 2.0_f64.powi(i as i32);
let start = if i == 0 {
time_ctx.start
} else {
// Sum of previous durations: d1 * (2^i - 1)
time_ctx.start + d1 * (2.0_f64.powi(i as i32) - 1.0)
};
subs.push((start, dur));
}
time_ctx.subdivisions = Some(subs);
}
Op::For => {
let quot = stack.pop().ok_or("stack underflow")?;
let time_ctx = time_stack.last().ok_or("time stack underflow")?;
let subs = time_ctx
.subdivisions
.clone()
.ok_or("for requires subdivide first")?;
match quot {
Value::Quotation(quot_ops, body_span) => {
if let Some(span) = body_span {
if let Some(trace) = trace_cell.borrow_mut().as_mut() {
trace.executed_spans.push(span);
}
}
for (i, (sub_start, sub_dur)) in subs.iter().enumerate() {
time_stack.push(TimeContext {
start: *sub_start,
duration: *sub_dur,
subdivisions: None,
iteration_index: Some(i),
});
let mut trace_opt = trace_cell.borrow_mut().take();
self.execute_ops(
&quot_ops,
ctx,
stack,
outputs,
time_stack,
cmd,
trace_opt.as_deref_mut(),
)?;
*trace_cell.borrow_mut() = trace_opt;
time_stack.pop();
}
}
_ => return Err("expected quotation".into()),
}
}
Op::LocalCycleEnd => {
let mut values = Vec::new();
while let Some(v) = stack.pop() {
if v.is_marker() {
break;
}
values.push(v);
}
if values.is_empty() {
return Err("empty local cycle list".into());
}
values.reverse();
let time_ctx = time_stack.last().ok_or("time stack underflow")?;
let idx = time_ctx.iteration_index.unwrap_or(0) % values.len();
let selected = values[idx].clone();
if let Some(span) = selected.span() {
if let Some(trace) = trace_cell.borrow_mut().as_mut() {
trace.selected_spans.push(span);
}
}
if let Value::Quotation(quot_ops, body_span) = selected {
if let Some(span) = body_span {
if let Some(trace) = trace_cell.borrow_mut().as_mut() {
trace.executed_spans.push(span);
}
}
let mut trace_opt = trace_cell.borrow_mut().take();
self.execute_ops(&quot_ops, ctx, stack, outputs, time_stack, cmd, trace_opt.as_deref_mut())?;
*trace_cell.borrow_mut() = trace_opt;
} else {
stack.push(selected);
}
cmd.set_param("attack".into(), a);
cmd.set_param("decay".into(), d);
cmd.set_param("sustain".into(), Value::Int(0, None));
}
Op::Apply => {
@@ -920,7 +828,16 @@ impl Forth {
}
}
let mut trace_opt = trace_cell.borrow_mut().take();
self.execute_ops(&quot_ops, ctx, stack, outputs, time_stack, cmd, trace_opt.as_deref_mut())?;
self.execute_ops(
&quot_ops,
ctx,
stack,
outputs,
scope_stack,
cmd,
trace_opt.as_deref_mut(),
emission_count,
)?;
*trace_cell.borrow_mut() = trace_opt;
}
_ => return Err("expected quotation".into()),
@@ -945,6 +862,87 @@ impl Forth {
let val = perlin_noise_1d(freq * ctx.beat);
stack.push(Value::Float(val, None));
}
Op::InternalCycleEnd => {
let mut values = Vec::new();
while let Some(v) = stack.pop() {
if v.is_marker() {
break;
}
values.push(v);
}
if values.is_empty() {
return Err("empty internal cycle".into());
}
values.reverse();
stack.push(Value::Alternator(values));
}
Op::DivStart => {
let parent = scope_stack.last().ok_or("scope stack underflow")?;
let mut new_scope = ScopeContext::new(parent.start, parent.duration);
new_scope.weight = parent.weight;
scope_stack.push(new_scope);
}
Op::DivEnd => {
if scope_stack.len() <= 1 {
return Err("unmatched end".into());
}
let scope = scope_stack.pop().unwrap();
resolve_scope(&scope, outputs);
}
Op::StackStart => {
let parent = scope_stack.last().ok_or("scope stack underflow")?;
let mut new_scope = ScopeContext::new(parent.start, parent.duration);
new_scope.weight = parent.weight;
new_scope.stacked = true;
scope_stack.push(new_scope);
}
Op::EmitN => {
let n = stack.pop().ok_or("stack underflow")?.as_int()?;
if n < 0 {
return Err("emit count must be >= 0".into());
}
for _ in 0..n {
let (sound_val, params) = cmd.snapshot().ok_or("no sound set")?;
let (resolved_sound, sound_span) =
resolve_value_with_span(&sound_val, *emission_count);
if let Some(span) = sound_span {
if let Some(trace) = trace_cell.borrow_mut().as_mut() {
trace.selected_spans.push(span);
}
}
let sound = resolved_sound.as_str()?.to_string();
let resolved_params: Vec<(String, String)> = params
.iter()
.map(|(k, v)| {
let (resolved, param_span) =
resolve_value_with_span(v, *emission_count);
if let Some(span) = param_span {
if let Some(trace) = trace_cell.borrow_mut().as_mut() {
trace.selected_spans.push(span);
}
}
(k.clone(), resolved.to_param_string())
})
.collect();
let scope = scope_stack.last_mut().ok_or("scope stack underflow")?;
let slot_idx = scope.claim_slot();
scope.pending.push(PendingEmission {
sound,
params: resolved_params,
slot_index: slot_idx,
});
*emission_count += 1;
}
}
}
pc += 1;
}
@@ -953,12 +951,56 @@ impl Forth {
}
}
fn resolve_value_with_span(val: &Value, emission_count: usize) -> (Value, Option<SourceSpan>) {
match val {
Value::Alternator(items) if !items.is_empty() => {
let idx = emission_count % items.len();
let selected = &items[idx];
let (resolved, inner_span) = resolve_value_with_span(selected, emission_count);
// Prefer inner span (for nested alternators), fall back to selected's span
let span = inner_span.or_else(|| selected.span());
(resolved, span)
}
other => (other.clone(), other.span()),
}
}
fn resolve_scope(scope: &ScopeContext, outputs: &mut Vec<String>) {
if scope.slot_count == 0 || scope.pending.is_empty() {
return;
}
let slot_dur = scope.duration * scope.weight / scope.slot_count as f64;
for em in &scope.pending {
let delta = scope.start + slot_dur * em.slot_index as f64;
let mut pairs = vec![("sound".into(), em.sound.clone())];
pairs.extend(em.params.iter().cloned());
if delta > 0.0 {
pairs.push(("delta".into(), delta.to_string()));
}
if !pairs.iter().any(|(k, _)| k == "dur") {
pairs.push(("dur".into(), slot_dur.to_string()));
}
if let Some(idx) = pairs.iter().position(|(k, _)| k == "delaytime") {
let ratio: f64 = pairs[idx].1.parse().unwrap_or(1.0);
pairs[idx].1 = (ratio * slot_dur).to_string();
} else {
pairs.push(("delaytime".into(), slot_dur.to_string()));
}
outputs.push(format_cmd(&pairs));
}
}
fn perlin_grad(hash_input: i64) -> f64 {
let mut h = (hash_input as u64).wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
let mut h =
(hash_input as u64).wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407);
h ^= h >> 33;
h = h.wrapping_mul(0xff51afd7ed558ccd);
h ^= h >> 33;
if h & 1 == 0 { 1.0 } else { -1.0 }
if h & 1 == 0 {
1.0
} else {
-1.0
}
}
fn perlin_noise_1d(x: f64) -> f64 {
@@ -970,28 +1012,127 @@ fn perlin_noise_1d(x: f64) -> f64 {
(d0 + s * (d1 - d0)) * 0.5 + 0.5
}
fn float_to_value(result: f64) -> Value {
if result.fract() == 0.0 && result.abs() < i64::MAX as f64 {
Value::Int(result as i64, None)
} else {
Value::Float(result, None)
}
}
fn lift_unary<F>(val: Value, f: F) -> Result<Value, String>
where
F: Fn(f64) -> f64 + Copy,
{
match val {
Value::Alternator(items) => {
let mapped: Result<Vec<Value>, String> =
items.into_iter().map(|v| lift_unary(v, f)).collect();
Ok(Value::Alternator(mapped?))
}
other => Ok(float_to_value(f(other.as_float()?))),
}
}
fn lift_unary_int<F>(val: Value, f: F) -> Result<Value, String>
where
F: Fn(i64) -> i64 + Copy,
{
match val {
Value::Alternator(items) => {
let mapped: Result<Vec<Value>, String> =
items.into_iter().map(|v| lift_unary_int(v, f)).collect();
Ok(Value::Alternator(mapped?))
}
other => Ok(Value::Int(f(other.as_int()?), None)),
}
}
fn lift_binary<F>(a: Value, b: Value, f: F) -> Result<Value, String>
where
F: Fn(f64, f64) -> f64 + Copy,
{
match (a, b) {
(Value::Alternator(a_items), Value::Alternator(b_items)) => {
let len = a_items.len().max(b_items.len());
let mapped: Result<Vec<Value>, String> = (0..len)
.map(|i| {
let ai = a_items[i % a_items.len()].clone();
let bi = b_items[i % b_items.len()].clone();
lift_binary(ai, bi, f)
})
.collect();
Ok(Value::Alternator(mapped?))
}
(Value::Alternator(items), scalar) => {
let mapped: Result<Vec<Value>, String> = items
.into_iter()
.map(|v| lift_binary(v, scalar.clone(), f))
.collect();
Ok(Value::Alternator(mapped?))
}
(scalar, Value::Alternator(items)) => {
let mapped: Result<Vec<Value>, String> = items
.into_iter()
.map(|v| lift_binary(scalar.clone(), v, f))
.collect();
Ok(Value::Alternator(mapped?))
}
(a, b) => Ok(float_to_value(f(a.as_float()?, b.as_float()?))),
}
}
fn binary_op<F>(stack: &mut Vec<Value>, f: F) -> Result<(), String>
where
F: Fn(f64, f64) -> f64,
F: Fn(f64, f64) -> f64 + Copy,
{
let b = stack.pop().ok_or("stack underflow")?.as_float()?;
let a = stack.pop().ok_or("stack underflow")?.as_float()?;
let result = f(a, b);
if result.fract() == 0.0 && result.abs() < i64::MAX as f64 {
stack.push(Value::Int(result as i64, None));
} else {
stack.push(Value::Float(result, None));
}
let b = stack.pop().ok_or("stack underflow")?;
let a = stack.pop().ok_or("stack underflow")?;
stack.push(lift_binary(a, b, f)?);
Ok(())
}
fn cmp_op<F>(stack: &mut Vec<Value>, f: F) -> Result<(), String>
where
F: Fn(f64, f64) -> bool,
F: Fn(f64, f64) -> bool + Copy,
{
let b = stack.pop().ok_or("stack underflow")?.as_float()?;
let a = stack.pop().ok_or("stack underflow")?.as_float()?;
stack.push(Value::Int(if f(a, b) { 1 } else { 0 }, None));
fn lift_cmp<F>(a: Value, b: Value, f: F) -> Result<Value, String>
where
F: Fn(f64, f64) -> bool + Copy,
{
match (a, b) {
(Value::Alternator(a_items), Value::Alternator(b_items)) => {
let len = a_items.len().max(b_items.len());
let mapped: Result<Vec<Value>, String> = (0..len)
.map(|i| {
let ai = a_items[i % a_items.len()].clone();
let bi = b_items[i % b_items.len()].clone();
lift_cmp(ai, bi, f)
})
.collect();
Ok(Value::Alternator(mapped?))
}
(Value::Alternator(items), scalar) => {
let mapped: Result<Vec<Value>, String> = items
.into_iter()
.map(|v| lift_cmp(v, scalar.clone(), f))
.collect();
Ok(Value::Alternator(mapped?))
}
(scalar, Value::Alternator(items)) => {
let mapped: Result<Vec<Value>, String> = items
.into_iter()
.map(|v| lift_cmp(scalar.clone(), v, f))
.collect();
Ok(Value::Alternator(mapped?))
}
(a, b) => Ok(Value::Int(if f(a.as_float()?, b.as_float()?) { 1 } else { 0 }, None)),
}
}
let b = stack.pop().ok_or("stack underflow")?;
let a = stack.pop().ok_or("stack underflow")?;
stack.push(lift_cmp(a, b, f)?);
Ok(())
}

View File

@@ -260,10 +260,52 @@ pub const WORDS: &[Word] = &[
Word {
name: "@",
stack: "(--)",
desc: "Alias for emit",
example: "\"kick\" s 0.5 at @ pop",
desc: "Emit current sound, claim one time slot",
example: "\"kick\" s @ @ @ @",
compile: Alias("emit"),
},
Word {
name: ".",
stack: "(--)",
desc: "Emit current sound, claim one time slot",
example: "\"kick\" s . . . .",
compile: Alias("emit"),
},
Word {
name: "~",
stack: "(--)",
desc: "Silence, claim one time slot",
example: "\"kick\" s @ ~ @ ~",
compile: Simple,
},
Word {
name: ".!",
stack: "(n --)",
desc: "Emit current sound n times",
example: "\"kick\" s 4 .!",
compile: Simple,
},
Word {
name: "div",
stack: "(--)",
desc: "Start a time subdivision scope",
example: "div \"kick\" s . \"hat\" s . end",
compile: Simple,
},
Word {
name: "stack",
stack: "(--)",
desc: "Start a stacked subdivision scope (sounds stack/superpose)",
example: "stack \"kick\" s . \"hat\" s . end",
compile: Simple,
},
Word {
name: "end",
stack: "(--)",
desc: "End a time subdivision scope",
example: "div \"kick\" s . end",
compile: Simple,
},
// Variables (prefix syntax: @name to fetch, !name to store)
Word {
name: "@<var>",
@@ -538,88 +580,18 @@ pub const WORDS: &[Word] = &[
compile: Simple,
},
// Time
Word {
name: "at",
stack: "(pos --)",
desc: "Position in time (push context)",
example: "\"kick\" s 0.5 at emit pop",
compile: Simple,
},
Word {
name: "zoom",
stack: "(start end --)",
desc: "Zoom into time region",
example: "0.0 0.5 zoom",
compile: Simple,
},
Word {
name: "scale!",
stack: "(factor --)",
desc: "Scale time context duration",
desc: "Set weight of current time scope",
example: "2 scale!",
compile: Simple,
},
Word {
name: "pop",
stack: "(--)",
desc: "Pop time context",
example: "pop",
compile: Simple,
},
Word {
name: "div",
stack: "(n --)",
desc: "Subdivide time into n",
example: "4 div",
compile: Simple,
},
Word {
name: "each",
stack: "(--)",
desc: "Emit at each subdivision",
example: "4 div each",
compile: Simple,
},
Word {
name: "stack",
stack: "(n --)",
desc: "Create n subdivisions at same time",
example: "3 stack",
compile: Simple,
},
Word {
name: "echo",
stack: "(n --)",
desc: "Create n subdivisions with halving durations (stutter)",
example: "3 echo",
compile: Simple,
},
Word {
name: "necho",
stack: "(n --)",
desc: "Create n subdivisions with doubling durations (swell)",
example: "3 necho",
compile: Simple,
},
Word {
name: "for",
stack: "(quot --)",
desc: "Execute quotation for each subdivision",
example: "{ emit } 3 div for",
compile: Simple,
},
Word {
name: "loop",
stack: "(n --)",
desc: "Fit sample to n beats",
example: "\"break\" s 4 loop emit",
compile: Simple,
},
Word {
name: "|",
stack: "(-- marker)",
desc: "Start local cycle list",
example: "| 60 62 64 |",
example: "\"break\" s 4 loop @",
compile: Simple,
},
Word {
@@ -1543,12 +1515,8 @@ pub(super) fn simple_op(name: &str) -> Option<Op> {
"ftom" => Op::Ftom,
"?" => Op::When,
"!?" => Op::Unless,
"at" => Op::At,
"zoom" => Op::Window,
"~" => Op::Silence,
"scale!" => Op::Scale,
"pop" => Op::Pop,
"div" => Op::Subdivide,
"each" => Op::Each,
"tempo!" => Op::SetTempo,
"[" => Op::ListStart,
"]" => Op::ListEnd,
@@ -1556,10 +1524,6 @@ pub(super) fn simple_op(name: &str) -> Option<Op> {
">>" => Op::ListEndPCycle,
"adsr" => Op::Adsr,
"ad" => Op::Ad,
"stack" => Op::Stack,
"for" => Op::For,
"echo" => Op::Echo,
"necho" => Op::Necho,
"apply" => Op::Apply,
"ramp" => Op::Ramp,
"range" => Op::Range,
@@ -1567,6 +1531,10 @@ pub(super) fn simple_op(name: &str) -> Option<Op> {
"chain" => Op::Chain,
"loop" => Op::Loop,
"oct" => Op::Oct,
"div" => Op::DivStart,
"stack" => Op::StackStart,
"end" => Op::DivEnd,
".!" => Op::EmitN,
_ => return None,
})
}