Repository Public
1//! ORIX Sonata2//! File: crates/sonata-semantics/src/eval.rs3//! Description: The evaluator core: scopes, globals, expressions, user functions, type4//! annotations, quotas and the seeded random stream.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use crate::builtins;10use crate::modules::ModuleSet;11use crate::value::{arithmetic, compare, equal, Num, OpError, Value};12use sonata_ir::{Diagnostic, FileId, InstrumentSpec, Key, Rational, Registry, Span};13use sonata_lexer::{NumLit, UnitSuffix};14use sonata_parser::ast::*;15use sonata_parser::edit_distance;16use std::collections::HashMap;17use std::rc::Rc;1819/// Resource limits of one compilation. Exceeding one is a Q6xxx error and stops cleanly.20#[derive(Clone, Debug, PartialEq)]21pub struct Quotas {22 pub max_events: u64,23 pub max_steps: u64,24 pub max_recursion: u32,25 pub max_list_len: usize,26 pub max_import_depth: u32,27 pub max_tracks: u32,28 pub max_patch_nodes: usize,29 pub max_diagnostics: usize,30}3132impl Default for Quotas {33 fn default() -> Self {34 Quotas {35 max_events: 1_000_000,36 max_steps: 10_000_000,37 max_recursion: 64,38 max_list_len: 100_000,39 max_import_depth: 16,40 max_tracks: 256,41 max_patch_nodes: 4096,42 max_diagnostics: 200,43 }44 }45}4647/// SplitMix64: the only source of randomness in a composition.48#[derive(Clone, Debug)]49pub struct SplitMix64(pub u64);5051impl SplitMix64 {52 pub fn next_u64(&mut self) -> u64 {53 self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);54 let mut z = self.0;55 z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);56 z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);57 z ^ (z >> 31)58 }59 /// Uniform in [0, 1).60 pub fn next_f64(&mut self) -> f64 {61 (self.next_u64() >> 11) as f64 / (1u64 << 53) as f6462 }63 /// Uniform integer in [0, n), without modulo bias for the sizes used here.64 pub fn below(&mut self, n: u64) -> u64 {65 if n == 0 {66 return 0;67 }68 ((self.next_u64() as u128 * n as u128) >> 64) as u6469 }70 /// Stream of a track: derived from the composition seed and the track id.71 pub fn for_stream(seed: u64, stream: u64) -> SplitMix64 {72 let mut s = SplitMix64(seed ^ stream.wrapping_add(1).wrapping_mul(0xD6E8_FEB8_6659_FD93));73 s.next_u64();74 s75 }76}7778/// Deepest combined nesting of blocks, calls and expressions (see `Analyzer::enter_nest`).79pub const MAX_NEST: u32 = 4096;8081/// A diagnostic was reported; unwind to the nearest statement boundary.82#[derive(Debug)]83pub(crate) struct Stop;84pub(crate) type R<T> = Result<T, Stop>;8586#[derive(Clone, Copy)]87pub(crate) enum GlobalKind<'a> {88 Value(&'a LetDecl),89 Fn(&'a FnDecl),90 Pattern(&'a PatternDecl),91 Instrument(&'a InstrumentDef),92}9394#[derive(Clone, Copy)]95pub(crate) struct Global<'a> {96 pub kind: GlobalKind<'a>,97 pub file: FileId,98 pub is_std: bool,99 pub name_span: Span,100}101102pub(crate) enum GlobalState {103 Evaluating,104 Done(Value),105 Failed,106}107108#[derive(Clone)]109pub(crate) struct Var {110 pub value: Value,111 pub is_const: bool,112}113114pub(crate) enum Flow {115 Normal,116 Return(Value, Span),117}118119pub(crate) struct Analyzer<'a> {120 pub set: &'a ModuleSet,121 pub registry: &'a Registry,122 pub quotas: Quotas,123 pub diags: Vec<Diagnostic>,124 pub globals: HashMap<&'a str, Global<'a>>,125 pub global_values: HashMap<String, GlobalState>,126 pub scopes: Vec<HashMap<String, Var>>,127 pub steps: u64,128 pub depth: u32,129 pub aborted: bool,130 pub rng: SplitMix64,131 /// Signature points known so far (position, numerator, denominator), sorted.132 pub signatures: Vec<(Rational, u32, u32, Span)>,133 /// Cursor of the statement being evaluated (for `bars` and `beats` literals).134 pub now: Rational,135 pub key: Option<Key>,136 /// Tempo in effect at position 0 (resolves durations given to time parameters).137 pub tempo0: f64,138 pub events: u64,139 pub instruments: HashMap<String, Option<Rc<InstrumentSpec>>>,140 pub instrument_stack: Vec<String>,141 /// When true, a bare unknown identifier evaluates to its name (choice values, bus names).142 pub symbolic: bool,143 /// Combined nesting of blocks, calls and expressions currently being evaluated.144 pub nest: u32,145 pub comp: crate::exec::Comp,146 pub track: Option<crate::exec::TrackBuild>,147 pub strip: crate::exec::Strip,148}149150impl<'a> Analyzer<'a> {151 pub fn new(set: &'a ModuleSet, registry: &'a Registry, quotas: Quotas) -> Analyzer<'a> {152 Analyzer {153 set,154 registry,155 quotas,156 diags: Vec::new(),157 globals: HashMap::new(),158 global_values: HashMap::new(),159 scopes: vec![HashMap::new()],160 steps: 0,161 depth: 0,162 aborted: false,163 rng: SplitMix64::for_stream(0, u64::MAX),164 signatures: vec![(Rational::ZERO, 4, 4, Span::default())],165 now: Rational::ZERO,166 key: None,167 tempo0: 120.0,168 events: 0,169 instruments: HashMap::new(),170 instrument_stack: Vec::new(),171 symbolic: false,172 nest: 0,173 comp: Default::default(),174 track: None,175 strip: Default::default(),176 }177 }178179 // ----- diagnostics ----------------------------------------------------------------------180181 pub fn report(&mut self, d: Diagnostic) {182 if self.aborted {183 return;184 }185 if self.diags.len() >= self.quotas.max_diagnostics {186 self.diags.push(Diagnostic::error("Q6008", d.span, format!("more than {} diagnostics; analysis stopped", self.quotas.max_diagnostics)));187 self.aborted = true;188 return;189 }190 // The same problem inside a loop is reported once.191 if self.diags.iter().any(|x| x.code == d.code && x.span == d.span && x.message == d.message) {192 return;193 }194 self.diags.push(d);195 }196 pub fn err<T>(&mut self, code: &str, span: Span, msg: impl Into<String>) -> R<T> {197 self.report(Diagnostic::error(code, span, msg));198 Err(Stop)199 }200 pub fn err_hint<T>(&mut self, code: &str, span: Span, msg: impl Into<String>, hint: impl Into<String>) -> R<T> {201 self.report(Diagnostic::error(code, span, msg).with_suggestion(hint));202 Err(Stop)203 }204 pub fn warn(&mut self, code: &str, span: Span, msg: impl Into<String>) {205 self.report(Diagnostic::warning(code, span, msg));206 }207 /// Stops the whole analysis (quota exceeded).208 pub fn abort<T>(&mut self, code: &str, span: Span, msg: impl Into<String>) -> R<T> {209 if !self.aborted {210 self.diags.push(Diagnostic::error(code, span, msg));211 self.aborted = true;212 }213 Err(Stop)214 }215 pub fn step(&mut self, span: Span) -> R<()> {216 if self.aborted {217 return Err(Stop);218 }219 self.steps += 1;220 if self.steps > self.quotas.max_steps {221 let max = self.quotas.max_steps;222 return self.abort("Q6002", span, format!("the composition needs more than {max} evaluation steps"));223 }224 Ok(())225 }226 pub fn overflow<T>(&mut self, span: Span) -> R<T> {227 self.abort("Q6005", span, "musical time overflowed the exact 64-bit rational range")228 }229230 /// "did you mean" over a set of candidate names.231 pub fn closest<'c>(name: &str, candidates: impl Iterator<Item = &'c str>) -> Option<String> {232 let mut best: Option<(usize, &str)> = None;233 for c in candidates {234 let d = edit_distance(name, c);235 let limit = (name.chars().count() / 3).clamp(1, 3);236 if d <= limit && best.map(|(bd, bc)| d < bd || (d == bd && c < bc)).unwrap_or(true) {237 best = Some((d, c));238 }239 }240 best.map(|(_, c)| c.to_string())241 }242243 /// Diagnostic for an unknown name with a suggestion and, when close, a safe fix.244 pub fn unknown<'c, T>(&mut self, code: &str, span: Span, what: &str, name: &str, candidates: impl Iterator<Item = &'c str>) -> R<T> {245 let mut d = Diagnostic::error(code, span, format!("unknown {what} '{name}'"));246 if let Some(c) = Self::closest(name, candidates) {247 d = d.with_suggestion(format!("did you mean '{c}'?")).with_fix(format!("replace with '{c}'"), span, c);248 }249 self.report(d);250 Err(Stop)251 }252253 // ----- scopes ---------------------------------------------------------------------------254255 pub fn push_scope(&mut self) {256 self.scopes.push(HashMap::new());257 }258 pub fn pop_scope(&mut self) {259 self.scopes.pop();260 }261 pub fn declare(&mut self, name: &Ident, value: Value, is_const: bool) {262 if let Some(scope) = self.scopes.last_mut() {263 scope.insert(name.name.clone(), Var { value, is_const });264 }265 }266267 fn local(&self, name: &str) -> Option<&Var> {268 self.scopes.iter().rev().find_map(|s| s.get(name))269 }270271 pub fn signature_at(&self, pos: Rational) -> (u32, u32) {272 let mut cur = (4, 4);273 for (at, n, d, _) in &self.signatures {274 if *at <= pos {275 cur = (*n, *d);276 } else {277 break;278 }279 }280 cur281 }282283 pub fn lookup(&mut self, name: &str, span: Span) -> R<Value> {284 if let Some(v) = self.local(name) {285 return Ok(v.value.clone());286 }287 if let Some(g) = self.globals.get(name).copied() {288 return match g.kind {289 GlobalKind::Value(decl) => self.global_value(name, decl),290 GlobalKind::Fn(_) => self.err_hint("S2003", span, format!("'{name}' is a function"), format!("call it: {name}(…)")),291 GlobalKind::Pattern(_) => self.err_hint("S2003", span, format!("'{name}' is a pattern"), format!("call it as a statement: {name}(…)")),292 GlobalKind::Instrument(_) => {293 if self.symbolic {294 Ok(Value::str(name))295 } else {296 self.err("S2003", span, format!("'{name}' is an instrument, not a value"))297 }298 }299 };300 }301 if let Some(v) = builtins::constant(name) {302 return Ok(v);303 }304 if self.symbolic {305 return Ok(Value::str(name));306 }307 let mut names: Vec<String> = self.scopes.iter().flat_map(|s| s.keys().cloned()).collect();308 names.extend(self.globals.keys().map(|k| k.to_string()));309 names.extend(builtins::CONSTANTS.iter().map(|c| c.to_string()));310 names.extend(builtins::BUILTINS.iter().map(|b| b.name.to_string()));311 self.unknown("S2001", span, "name", name, names.iter().map(String::as_str))312 }313314 fn global_value(&mut self, name: &str, decl: &'a LetDecl) -> R<Value> {315 match self.global_values.get(name) {316 Some(GlobalState::Done(v)) => return Ok(v.clone()),317 Some(GlobalState::Failed) => return Err(Stop),318 Some(GlobalState::Evaluating) => {319 return self.err("S2006", decl.name.span, format!("'{name}' depends on itself"));320 }321 None => {}322 }323 self.global_values.insert(name.to_string(), GlobalState::Evaluating);324 let saved = std::mem::replace(&mut self.scopes, vec![HashMap::new()]);325 let was_symbolic = std::mem::replace(&mut self.symbolic, false);326 let result = self.eval(&decl.value).and_then(|v| match &decl.ty {327 Some(t) => self.check_type(t, v, decl.value.span),328 None => Ok(v),329 });330 self.symbolic = was_symbolic;331 self.scopes = saved;332 match result {333 Ok(v) => {334 self.global_values.insert(name.to_string(), GlobalState::Done(v.clone()));335 Ok(v)336 }337 Err(e) => {338 self.global_values.insert(name.to_string(), GlobalState::Failed);339 Err(e)340 }341 }342 }343344 // ----- types ----------------------------------------------------------------------------345346 /// Checks a value against a type annotation, applying the documented coercions347 /// (an exact number becomes a `Duration`).348 pub fn check_type(&mut self, ty: &TypeExpr, v: Value, span: Span) -> R<Value> {349 let name = ty.name.name.as_str();350 let ok = |v: Value| Ok(v);351 let unit_range = |v: &Value, lo: f64, hi: f64| matches!(v, Value::Num(n) if (lo..=hi).contains(&n.to_f64()));352 match name {353 "Any" => ok(v),354 "Number" if matches!(v, Value::Num(_)) => ok(v),355 "Bool" if matches!(v, Value::Bool(_)) => ok(v),356 "String" if matches!(v, Value::Str(_)) => ok(v),357 "Pitch" | "Note" if matches!(v, Value::Pitch(_)) => ok(v),358 "Interval" if matches!(v, Value::Interval(_)) => ok(v),359 "Duration" | "Beat" | "Bar" => match v.as_duration() {360 Some(d) => Ok(Value::Duration(d)),361 None => self.type_mismatch(ty, &v, span),362 },363 "Time" if matches!(v, Value::Time(_)) => ok(v),364 "Frequency" if matches!(v, Value::Freq(_)) => ok(v),365 "Gain" if matches!(v, Value::Gain(_)) => ok(v),366 "Tempo" if matches!(v, Value::Tempo(_)) => ok(v),367 "Velocity" if unit_range(&v, 0.0, 1.0) => ok(v),368 "Pan" if unit_range(&v, -1.0, 1.0) => ok(v),369 "List" | "Chord" | "Scale" => {370 let Value::List(items) = &v else { return self.type_mismatch(ty, &v, span) };371 let pitch = TypeExpr { name: Ident { name: "Pitch".into(), span: ty.span }, args: vec![], span: ty.span };372 let elem = if name == "List" { ty.args.first() } else { Some(&pitch) };373 match elem {374 None => ok(v),375 Some(elem) => {376 let mut out = Vec::with_capacity(items.len());377 for it in items.iter() {378 out.push(self.check_type(elem, it.clone(), span)?);379 }380 Ok(Value::list(out))381 }382 }383 }384 "TimeSignature" | "Pattern" | "Sequence" | "Instrument" | "Bus" | "AudioBuffer" | "Signal" | "ControlSignal" => self.err_hint(385 "T3010",386 ty.span,387 format!("'{name}' is not a value type in Sonata 0.1"),388 "values can be Number, Bool, String, Pitch, Interval, Duration, Time, Frequency, Gain, Tempo, Velocity, Pan, List<T>, Chord, Scale",389 ),390 "Number" | "Bool" | "String" | "Pitch" | "Note" | "Interval" | "Time" | "Frequency" | "Gain" | "Tempo" | "Velocity" | "Pan" => {391 self.type_mismatch(ty, &v, span)392 }393 other => self.unknown("S2004", ty.name.span, "type", other, TYPE_NAMES.iter().copied()),394 }395 }396397 fn type_mismatch<T>(&mut self, ty: &TypeExpr, v: &Value, span: Span) -> R<T> {398 let want = &ty.name.name;399 let extra = match want.as_str() {400 "Velocity" => " in [0, 1]",401 "Pan" => " in [-1, 1]",402 _ => "",403 };404 self.err("T3009", span, format!("expected {want}{extra}, found {} ({})", v.type_name(), v.display()))405 }406407 // ----- expressions ----------------------------------------------------------------------408409 /// Bounds the native stack used by the evaluator, whatever the program does.410 pub fn enter_nest(&mut self, span: Span) -> R<()> {411 if self.nest >= MAX_NEST {412 return self.abort("Q6003", span, format!("blocks, calls and expressions are nested deeper than {MAX_NEST} levels"));413 }414 self.nest += 1;415 Ok(())416 }417418 pub fn eval(&mut self, e: &Expr) -> R<Value> {419 self.enter_nest(e.span)?;420 let r = self.eval_inner(e);421 self.nest -= 1;422 r423 }424425 fn eval_inner(&mut self, e: &Expr) -> R<Value> {426 match &e.kind {427 ExprKind::Number { value, unit } => self.number(*value, *unit, e.span),428 ExprKind::Str { value } => Ok(Value::str(value)),429 ExprKind::Bool { value } => Ok(Value::Bool(*value)),430 ExprKind::Note { note } => Ok(Value::Pitch(note.midi() as f64)),431 ExprKind::PitchClass { pitch_class } => Ok(Value::PitchClass(*pitch_class)),432 ExprKind::Ident { name } => self.lookup(name, e.span),433 ExprKind::Paren { inner } => self.eval(inner),434 ExprKind::List { items } => {435 let mut out = Vec::with_capacity(items.len());436 for it in items {437 out.push(self.eval(it)?);438 }439 Ok(Value::list(out))440 }441 ExprKind::Range { start, end, inclusive } => {442 let (a, b) = (self.eval(start)?, self.eval(end)?);443 let (Some(a), Some(b)) = (int_of(&a), int_of(&b)) else {444 return self.err("T3001", e.span, format!("a range needs two integers, found {} and {}", a.type_name(), b.type_name()));445 };446 let b = if *inclusive { b.saturating_add(1) } else { b };447 let len = b.saturating_sub(a).max(0) as u64;448 if len > self.quotas.max_list_len as u64 {449 let max = self.quotas.max_list_len;450 return self.abort("Q6004", e.span, format!("this range has {len} elements; lists are limited to {max}"));451 }452 Ok(Value::list((a..b).map(Value::int).collect()))453 }454 ExprKind::Unary { op: UnOp::Neg, operand } => {455 let v = self.eval(operand)?;456 Ok(match v {457 Value::Num(Num::Exact(r)) => match Rational::ZERO.checked_sub(r) {458 Some(n) => Value::Num(Num::Exact(n)),459 None => Value::num(-r.to_f64()),460 },461 Value::Num(Num::Float(f)) => Value::num(-f),462 Value::Interval(x) => Value::Interval(-x),463 Value::Gain(x) => Value::Gain(-x),464 Value::Time(x) => Value::Time(-x),465 Value::Angle(x) => Value::Angle(-x),466 Value::Duration(d) => match Rational::ZERO.checked_sub(d) {467 Some(n) => Value::Duration(n),468 None => return self.overflow(e.span),469 },470 other => return self.err("T3001", e.span, format!("cannot negate a {}", other.type_name())),471 })472 }473 ExprKind::Unary { op: UnOp::Not, operand } => {474 let v = self.eval(operand)?;475 match v {476 Value::Bool(b) => Ok(Value::Bool(!b)),477 other => self.err("T3001", operand.span, format!("'not' needs a Bool, found {}", other.type_name())),478 }479 }480 ExprKind::Binary { op, left, right } => self.binary(*op, left, right, e.span),481 ExprKind::IfElse { cond, then, otherwise } => {482 if self.truth(cond)? {483 self.eval(then)484 } else {485 self.eval(otherwise)486 }487 }488 ExprKind::Index { base, index } => {489 let (b, i) = (self.eval(base)?, self.eval(index)?);490 let Value::List(items) = &b else {491 return self.err("T3001", base.span, format!("only lists can be indexed, found {}", b.type_name()));492 };493 let Some(i) = int_of(&i) else {494 return self.err("T3001", index.span, format!("a list index is an integer, found {}", i.type_name()));495 };496 let len = items.len() as i64;497 let at = if i < 0 { i + len } else { i };498 if at < 0 || at >= len {499 return self.err_hint(500 "T3008",501 index.span,502 format!("index {i} is outside the list of {len} elements"),503 "indices start at 0; negative indices count from the end",504 );505 }506 Ok(items[at as usize].clone())507 }508 ExprKind::Member { base, name } => {509 let b = self.eval(base)?;510 match (&b, name.name.as_str()) {511 (Value::List(items), "len") => Ok(Value::int(items.len() as i64)),512 (Value::List(items), "first") | (Value::List(items), "last") => {513 let it = if name.name == "first" { items.first() } else { items.last() };514 match it {515 Some(v) => Ok(v.clone()),516 None => self.err("T3008", e.span, "the list is empty"),517 }518 }519 (Value::Pitch(p), "midi") => Ok(Value::num(*p)),520 (Value::Pitch(p), "octave") => Ok(Value::int((p.round() as i64).div_euclid(12) - 1)),521 (Value::Pitch(p), "class") => Ok(Value::int((p.round() as i64).rem_euclid(12))),522 (Value::Pitch(p), "hz") => Ok(Value::Freq(440.0 * ((p - 69.0) / 12.0).exp2())),523 _ => {524 let members = match b {525 Value::List(_) => "len, first, last",526 Value::Pitch(_) => "midi, octave, class, hz",527 _ => "none",528 };529 self.err_hint("T3013", name.span, format!("{} has no member '{}'", b.type_name(), name.name), format!("available members: {members}"))530 }531 }532 }533 ExprKind::Call { callee, args } => self.call(callee, args, e.span),534 ExprKind::Error => Err(Stop),535 }536 }537538 pub fn number(&mut self, value: NumLit, unit: Option<UnitSuffix>, span: Span) -> R<Value> {539 let n = match value {540 NumLit::Int(i) => Num::int(i),541 NumLit::Float(f) => Num::Float(f),542 };543 let f = n.to_f64();544 Ok(match unit {545 None => Value::Num(n),546 Some(UnitSuffix::Percent) => match n {547 Num::Exact(r) => Value::Num(Num::Exact(r.checked_div(Rational::from_int(100)).unwrap_or(Rational::ZERO))),548 Num::Float(x) => Value::num(x / 100.0),549 },550 Some(UnitSuffix::Bpm) => Value::Tempo(f),551 Some(UnitSuffix::Hz) => Value::Freq(f),552 Some(UnitSuffix::KHz) => Value::Freq(f * 1000.0),553 Some(UnitSuffix::Db) => Value::Gain(f),554 Some(UnitSuffix::Ms) => Value::Time(f / 1000.0),555 Some(UnitSuffix::S) => Value::Time(f),556 Some(UnitSuffix::St) => Value::Interval(f),557 Some(UnitSuffix::Cents) => Value::Interval(f / 100.0),558 Some(UnitSuffix::Deg) => Value::Angle(f),559 Some(UnitSuffix::Bars) | Some(UnitSuffix::Beats) => {560 let (num, den) = self.signature_at(self.now);561 let unit_len =562 if unit == Some(UnitSuffix::Bars) { Rational::new(num as i64, den as i64) } else { Rational::new(1, den as i64) }.unwrap_or(Rational::ONE);563 let count = match n {564 Num::Exact(r) => r,565 Num::Float(x) => match Rational::approximate(x, crate::value::DURATION_MAX_DENOMINATOR) {566 Some(r) => r,567 None => return self.overflow(span),568 },569 };570 match count.checked_mul(unit_len) {571 Some(d) => Value::Duration(d),572 None => return self.overflow(span),573 }574 }575 })576 }577578 pub fn truth(&mut self, e: &Expr) -> R<bool> {579 match self.eval(e)? {580 Value::Bool(b) => Ok(b),581 other => {582 self.err_hint("T3011", e.span, format!("a condition must be a Bool, found {}", other.type_name()), "compare explicitly, for example: x > 0")583 }584 }585 }586587 fn binary(&mut self, op: BinOp, left: &Expr, right: &Expr, span: Span) -> R<Value> {588 if matches!(op, BinOp::And | BinOp::Or) {589 let l = self.truth(left)?;590 if (op == BinOp::And && !l) || (op == BinOp::Or && l) {591 return Ok(Value::Bool(l));592 }593 return Ok(Value::Bool(self.truth(right)?));594 }595 let (a, b) = (self.eval(left)?, self.eval(right)?);596 match op {597 BinOp::Eq => Ok(Value::Bool(equal(&a, &b))),598 BinOp::Ne => Ok(Value::Bool(!equal(&a, &b))),599 BinOp::Lt | BinOp::Le | BinOp::Gt | BinOp::Ge => match compare(&a, &b) {600 Some(o) => Ok(Value::Bool(match op {601 BinOp::Lt => o.is_lt(),602 BinOp::Le => o.is_le(),603 BinOp::Gt => o.is_gt(),604 _ => o.is_ge(),605 })),606 None => self.err("T3001", span, format!("cannot compare {} with {}", a.type_name(), b.type_name())),607 },608 _ => match arithmetic(op, &a, &b) {609 Ok(v) => {610 if let Value::List(items) = &v {611 if items.len() > self.quotas.max_list_len {612 let max = self.quotas.max_list_len;613 return self.abort("Q6004", span, format!("lists are limited to {max} elements"));614 }615 }616 Ok(v)617 }618 Err(OpError::DivisionByZero) => self.err("T3007", right.span, "division by zero"),619 Err(OpError::Overflow) => self.overflow(span),620 Err(OpError::Type(hint)) => {621 let msg = format!("cannot apply '{}' to {} and {}", op.symbol(), a.type_name(), b.type_name());622 match hint {623 Some(h) => self.err_hint("T3001", span, msg, h),624 None => self.err("T3001", span, msg),625 }626 }627 },628 }629 }630631 // ----- calls ----------------------------------------------------------------------------632633 fn call(&mut self, callee: &Ident, args: &[Arg], span: Span) -> R<Value> {634 self.step(span)?;635 if let Some(g) = self.globals.get(callee.name.as_str()).copied() {636 return match g.kind {637 GlobalKind::Fn(f) => self.call_fn(f, args, span),638 GlobalKind::Pattern(_) => self.err_hint(639 "S2003",640 callee.span,641 format!("pattern '{}' produces notes, not a value", callee.name),642 "call a pattern as a statement on its own line inside a track",643 ),644 _ => self.err("S2003", callee.span, format!("'{}' is not a function", callee.name)),645 };646 }647 if builtins::find(&callee.name).is_some() {648 let mut vals = Vec::with_capacity(args.len());649 for a in args {650 if let Some(n) = &a.name {651 return self.err_hint(652 "S2005",653 n.span,654 format!("built-in function '{}' takes positional arguments only", callee.name),655 "remove the argument name",656 );657 }658 vals.push((self.eval(&a.value)?, a.value.span));659 }660 return builtins::call(self, &callee.name, &vals, span);661 }662 let mut names: Vec<&str> = builtins::BUILTINS.iter().map(|b| b.name).collect();663 let user: Vec<&str> = self.globals.iter().filter(|(_, g)| matches!(g.kind, GlobalKind::Fn(_) | GlobalKind::Pattern(_))).map(|(k, _)| *k).collect();664 names.extend(user);665 self.unknown("S2001", callee.span, "function", &callee.name, names.into_iter())666 }667668 /// Binds call arguments to parameters: positional first, then named, then defaults.669 pub fn bind(&mut self, what: &str, name: &str, params: &'a [Param], args: &[Arg], span: Span) -> R<HashMap<String, Var>> {670 let mut bound: HashMap<String, Var> = HashMap::new();671 let mut positional = 0usize;672 let mut seen_named = false;673 for a in args {674 let value = self.eval(&a.value)?;675 let param = match &a.name {676 Some(n) => {677 seen_named = true;678 match params.iter().find(|p| p.name.name == n.name) {679 Some(p) => p,680 None => {681 return self.unknown(682 "S2005",683 n.span,684 &format!("parameter of {what} '{name}'"),685 &n.name,686 params.iter().map(|p| p.name.name.as_str()),687 );688 }689 }690 }691 None => {692 if seen_named {693 return self.err("S2005", a.span, "positional arguments must come before named ones");694 }695 match params.get(positional) {696 Some(p) => {697 positional += 1;698 p699 }700 None => {701 let n = params.len();702 return self.err(703 "S2005",704 a.span,705 format!("{what} '{name}' takes {n} argument{}, but {} were given", if n == 1 { "" } else { "s" }, args.len()),706 );707 }708 }709 }710 };711 if bound.contains_key(¶m.name.name) {712 return self.err("S2005", a.span, format!("parameter '{}' is given twice", param.name.name));713 }714 let value = match ¶m.ty {715 Some(t) => self.check_type(t, value, a.value.span)?,716 None => value,717 };718 bound.insert(param.name.name.clone(), Var { value, is_const: false });719 }720 for p in params {721 if bound.contains_key(&p.name.name) {722 continue;723 }724 let Some(default) = &p.default else {725 return self.err("S2005", span, format!("{what} '{name}' is missing its argument '{}'", p.name.name));726 };727 // Defaults see only globals.728 let saved = std::mem::replace(&mut self.scopes, vec![HashMap::new()]);729 let v = self.eval(default);730 self.scopes = saved;731 let v = v?;732 let v = match &p.ty {733 Some(t) => self.check_type(t, v, default.span)?,734 None => v,735 };736 bound.insert(p.name.name.clone(), Var { value: v, is_const: false });737 }738 Ok(bound)739 }740741 pub fn enter_call(&mut self, span: Span) -> R<()> {742 if self.depth >= self.quotas.max_recursion {743 let max = self.quotas.max_recursion;744 return self.abort("Q6003", span, format!("calls are nested deeper than {max} levels (unbounded recursion?)"));745 }746 self.depth += 1;747 Ok(())748 }749750 fn call_fn(&mut self, f: &'a FnDecl, args: &[Arg], span: Span) -> R<Value> {751 let bound = self.bind("function", &f.name.name, &f.params, args, span)?;752 self.enter_call(span)?;753 let saved = std::mem::replace(&mut self.scopes, vec![bound]);754 let was_symbolic = std::mem::replace(&mut self.symbolic, false);755 let flow = self.exec_fn_block(&f.body);756 self.symbolic = was_symbolic;757 self.scopes = saved;758 self.depth -= 1;759 let (value, vspan) = match flow? {760 Flow::Return(v, s) => (v, s),761 Flow::Normal => (Value::Unit, f.name.span),762 };763 match &f.ret {764 Some(t) => {765 if matches!(value, Value::Unit) {766 return self.err("T3009", f.name.span, format!("function '{}' must return a {} on every path", f.name.name, t.name.name));767 }768 self.check_type(t, value, vspan)769 }770 None => Ok(value),771 }772 }773774 /// Statements allowed in a function body: let, assignment, if, for, repeat, return, calls.775 pub fn exec_fn_block(&mut self, block: &'a Block) -> R<Flow> {776 self.enter_nest(block.span)?;777 self.push_scope();778 let r = self.exec_fn_stmts(&block.stmts);779 self.pop_scope();780 self.nest -= 1;781 r782 }783784 fn exec_fn_stmts(&mut self, stmts: &'a [Stmt]) -> R<Flow> {785 for s in stmts {786 self.step(s.span)?;787 match &s.kind {788 StmtKind::Let(l) => self.exec_let(l)?,789 StmtKind::Assign { target, value } => self.exec_assign(target, value)?,790 StmtKind::Return { value } => {791 let v = match value {792 Some(e) => self.eval(e)?,793 None => Value::Unit,794 };795 return Ok(Flow::Return(v, value.as_ref().map(|e| e.span).unwrap_or(s.span)));796 }797 StmtKind::If { cond, then, otherwise } => {798 let branch = if self.truth(cond)? { Some(then) } else { otherwise.as_ref() };799 if let Some(b) = branch {800 if let Flow::Return(v, sp) = self.exec_fn_block(b)? {801 return Ok(Flow::Return(v, sp));802 }803 }804 }805 StmtKind::For { var, iter, body } => {806 let items = self.iterable(iter)?;807 for it in items.iter() {808 self.step(s.span)?;809 self.push_scope();810 self.declare(var, it.clone(), true);811 let r = self.exec_fn_stmts(&body.stmts);812 self.pop_scope();813 if let Flow::Return(v, sp) = r? {814 return Ok(Flow::Return(v, sp));815 }816 }817 }818 StmtKind::Repeat { count, body } => {819 let n = self.count(count)?;820 for _ in 0..n {821 self.step(s.span)?;822 if let Flow::Return(v, sp) = self.exec_fn_block(body)? {823 return Ok(Flow::Return(v, sp));824 }825 }826 }827 StmtKind::Expr { expr } => {828 self.eval(expr)?;829 }830 _ => {831 return self.err_hint(832 "S2008",833 s.span,834 "this statement is not allowed in a function",835 "functions are pure: they compute and return a value; use a pattern to produce notes",836 );837 }838 }839 }840 Ok(Flow::Normal)841 }842843 pub fn exec_let(&mut self, l: &LetDecl) -> R<()> {844 let v = self.eval(&l.value)?;845 let v = match &l.ty {846 Some(t) => self.check_type(t, v, l.value.span)?,847 None => v,848 };849 if matches!(v, Value::Unit) {850 return self.err("T3001", l.value.span, "this expression produces no value");851 }852 self.declare(&l.name, v, l.is_const);853 Ok(())854 }855856 pub fn exec_assign(&mut self, target: &Ident, value: &Expr) -> R<()> {857 let v = self.eval(value)?;858 for scope in self.scopes.iter_mut().rev() {859 if let Some(var) = scope.get_mut(&target.name) {860 if var.is_const {861 let d = Diagnostic::error("S2007", target.span, format!("'{}' is constant and cannot be assigned", target.name))862 .with_suggestion("declare it with 'let' to make it assignable");863 self.report(d);864 return Err(Stop);865 }866 var.value = v;867 return Ok(());868 }869 }870 if self.globals.contains_key(target.name.as_str()) {871 return self.err("S2007", target.span, format!("'{}' is a top-level definition and cannot be assigned", target.name));872 }873 self.err_hint("S2001", target.span, format!("'{}' is not defined", target.name), format!("declare it first: let {} = …", target.name))874 }875876 pub fn iterable(&mut self, e: &Expr) -> R<Rc<Vec<Value>>> {877 match self.eval(e)? {878 Value::List(items) => Ok(items),879 other => self.err_hint(880 "T3012",881 e.span,882 format!("'for' iterates over a list or a range, found {}", other.type_name()),883 "for example: for i in 0..4 { … }",884 ),885 }886 }887888 pub fn count(&mut self, e: &Expr) -> R<u64> {889 let v = self.eval(e)?;890 match int_of(&v) {891 Some(n) if n >= 0 => Ok(n as u64),892 _ => self.err("T3001", e.span, format!("a repeat count is a non-negative integer, found {}", v.display())),893 }894 }895}896897pub(crate) fn int_of(v: &Value) -> Option<i64> {898 match v {899 Value::Num(n) => n.as_int(),900 _ => None,901 }902}903904/// Type names accepted in annotations.905pub const TYPE_NAMES: &[&str] = &[906 "Any",907 "Number",908 "Bool",909 "String",910 "Pitch",911 "Note",912 "Interval",913 "Duration",914 "Beat",915 "Bar",916 "Time",917 "Frequency",918 "Gain",919 "Tempo",920 "TimeSignature",921 "Velocity",922 "Pan",923 "List",924 "Chord",925 "Scale",926 "Pattern",927 "Sequence",928 "Instrument",929 "Bus",930 "AudioBuffer",931 "Signal",932 "ControlSignal",933];934