SPB Git

Repository Public

value.rs 16.6 KB 419 lines rust

1//! ORIX Sonata2//! File: crates/sonata-semantics/src/value.rs3//! Description: Runtime values of the Sonata evaluator, their types and the unit algebra.4//!5//! Author: Simon-Pierre Boucher6//! Contact: contact@spboucher.ai78use sonata_ir::Rational;9use sonata_lexer::PitchClassLit;10use sonata_parser::ast::BinOp;11use std::cmp::Ordering;12use std::rc::Rc;1314/// A dimensionless number: exact while it can be, float otherwise.15#[derive(Clone, Copy, Debug, PartialEq)]16pub enum Num {17    Exact(Rational),18    Float(f64),19}2021impl Num {22    pub fn int(v: i64) -> Num {23        Num::Exact(Rational::from_int(v))24    }25    pub fn to_f64(self) -> f64 {26        match self {27            Num::Exact(r) => r.to_f64(),28            Num::Float(f) => f,29        }30    }31    /// The value as an integer, when it is one exactly.32    pub fn as_int(self) -> Option<i64> {33        match self {34            Num::Exact(r) if r.is_integer() => Some(r.num()),35            Num::Float(f) if f.fract() == 0.0 && f.abs() < 9.0e15 => Some(f as i64),36            _ => None,37        }38    }39    pub fn exact(self) -> Option<Rational> {40        match self {41            Num::Exact(r) => Some(r),42            Num::Float(_) => None,43        }44    }45}4647#[derive(Clone, Debug, PartialEq)]48pub enum Value {49    Num(Num),50    Bool(bool),51    Str(Rc<str>),52    /// MIDI pitch, fractional for microtones.53    Pitch(f64),54    PitchClass(PitchClassLit),55    /// Semitones.56    Interval(f64),57    /// Musical duration or position, whole notes, exact.58    Duration(Rational),59    /// Seconds.60    Time(f64),61    /// Hertz.62    Freq(f64),63    /// Decibels.64    Gain(f64),65    /// Quarter notes per minute.66    Tempo(f64),67    /// Degrees.68    Angle(f64),69    List(Rc<Vec<Value>>),70    /// Result of a call that produces no value (a pattern).71    Unit,72}7374impl Value {75    pub fn num(f: f64) -> Value {76        Value::Num(Num::Float(f))77    }78    pub fn int(v: i64) -> Value {79        Value::Num(Num::int(v))80    }81    pub fn str(s: &str) -> Value {82        Value::Str(Rc::from(s))83    }84    pub fn list(v: Vec<Value>) -> Value {85        Value::List(Rc::new(v))86    }8788    pub fn type_name(&self) -> String {89        match self {90            Value::Num(_) => "Number".into(),91            Value::Bool(_) => "Bool".into(),92            Value::Str(_) => "String".into(),93            Value::Pitch(_) => "Pitch".into(),94            Value::PitchClass(_) => "PitchClass".into(),95            Value::Interval(_) => "Interval".into(),96            Value::Duration(_) => "Duration".into(),97            Value::Time(_) => "Time".into(),98            Value::Freq(_) => "Frequency".into(),99            Value::Gain(_) => "Gain".into(),100            Value::Tempo(_) => "Tempo".into(),101            Value::Angle(_) => "Angle".into(),102            Value::List(items) => match items.first() {103                Some(first) if items.iter().all(|i| std::mem::discriminant(i) == std::mem::discriminant(first)) => format!("List<{}>", first.type_name()),104                Some(_) => "List<Any>".into(),105                None => "List".into(),106            },107            Value::Unit => "Nothing".into(),108        }109    }110111    /// Text shown in hovers and by `str()`.112    pub fn display(&self) -> String {113        fn f(x: f64) -> String {114            let r = (x * 1e6).round() / 1e6;115            format!("{r}")116        }117        match self {118            Value::Num(Num::Exact(r)) => r.to_string(),119            Value::Num(Num::Float(x)) => f(*x),120            Value::Bool(b) => b.to_string(),121            Value::Str(s) => s.to_string(),122            Value::Pitch(p) => pitch_name(*p),123            Value::PitchClass(p) => sonata_parser::format::pitch_class_text(*p),124            Value::Interval(s) => format!("{}st", f(*s)),125            Value::Duration(d) => format!("{d} of a whole note"),126            Value::Time(s) => format!("{}s", f(*s)),127            Value::Freq(h) => format!("{}Hz", f(*h)),128            Value::Gain(d) => format!("{}dB", f(*d)),129            Value::Tempo(b) => format!("{}bpm", f(*b)),130            Value::Angle(a) => format!("{}deg", f(*a)),131            Value::List(items) => format!("[{}]", items.iter().map(|i| i.display()).collect::<Vec<_>>().join(", ")),132            Value::Unit => "nothing".into(),133        }134    }135136    /// A duration, accepting an exact bare number as a fraction of a whole note.137    pub fn as_duration(&self) -> Option<Rational> {138        match self {139            Value::Duration(d) => Some(*d),140            Value::Num(Num::Exact(r)) => Some(*r),141            _ => None,142        }143    }144}145146/// Name of a MIDI pitch with sharps (`C#4`), with a cent offset for microtones.147pub fn pitch_name(p: f64) -> String {148    const NAMES: [&str; 12] = ["C", "C#", "D", "D#", "E", "F", "F#", "G", "G#", "A", "A#", "B"];149    let nearest = p.round();150    let cents = ((p - nearest) * 100.0).round() as i64;151    let n = nearest as i64;152    let name = format!("{}{}", NAMES[n.rem_euclid(12) as usize], n.div_euclid(12) - 1);153    match cents {154        0 => name,155        c if c > 0 => format!("{name}+{c}cents"),156        c => format!("{name}{c}cents"),157    }158}159160/// Why an operation failed. The evaluator turns it into a diagnostic with the right span.161#[derive(Clone, Debug, PartialEq)]162pub enum OpError {163    /// The operand types do not combine. Optional suggestion.164    Type(Option<String>),165    DivisionByZero,166    Overflow,167}168169fn type_err<T>(s: &str) -> Result<T, OpError> {170    Err(OpError::Type(if s.is_empty() { None } else { Some(s.to_string()) }))171}172173/// Largest denominator used when a float has to become an exact musical duration.174pub const DURATION_MAX_DENOMINATOR: i64 = 40_320;175176fn num_arith(op: BinOp, a: Num, b: Num) -> Result<Num, OpError> {177    if let (Num::Exact(x), Num::Exact(y)) = (a, b) {178        let r = match op {179            BinOp::Add => x.checked_add(y),180            BinOp::Sub => x.checked_sub(y),181            BinOp::Mul => x.checked_mul(y),182            BinOp::Div => {183                if y.is_zero() {184                    return Err(OpError::DivisionByZero);185                }186                x.checked_div(y)187            }188            BinOp::Rem => {189                if y.is_zero() {190                    return Err(OpError::DivisionByZero);191                }192                // x - y * floor(x / y)193                x.checked_div(y).and_then(|q| {194                    let fl = (q.num() as i128).div_euclid(q.den() as i128) as i64;195                    y.checked_mul(Rational::from_int(fl)).and_then(|m| x.checked_sub(m))196                })197            }198            _ => return type_err(""),199        };200        // An exact overflow falls back to floating point for plain numbers.201        if let Some(r) = r {202            return Ok(Num::Exact(r));203        }204    }205    let (x, y) = (a.to_f64(), b.to_f64());206    let r = match op {207        BinOp::Add => x + y,208        BinOp::Sub => x - y,209        BinOp::Mul => x * y,210        BinOp::Div => {211            if y == 0.0 {212                return Err(OpError::DivisionByZero);213            }214            x / y215        }216        BinOp::Rem => {217            if y == 0.0 {218                return Err(OpError::DivisionByZero);219            }220            x.rem_euclid(y)221        }222        _ => return type_err(""),223    };224    if r.is_finite() {225        Ok(Num::Float(r))226    } else {227        Err(OpError::Overflow)228    }229}230231fn dur_scale(d: Rational, n: Num, divide: bool) -> Result<Value, OpError> {232    let factor = match n {233        Num::Exact(r) => r,234        Num::Float(f) => Rational::approximate(f, DURATION_MAX_DENOMINATOR).ok_or(OpError::Overflow)?,235    };236    if divide && factor.is_zero() {237        return Err(OpError::DivisionByZero);238    }239    let r = if divide { d.checked_div(factor) } else { d.checked_mul(factor) };240    r.map(Value::Duration).ok_or(OpError::Overflow)241}242243fn scalar(op: BinOp, a: f64, b: Num, wrap: fn(f64) -> Value) -> Result<Value, OpError> {244    match op {245        BinOp::Mul => Ok(wrap(a * b.to_f64())),246        BinOp::Div => {247            if b.to_f64() == 0.0 {248                Err(OpError::DivisionByZero)249            } else {250                Ok(wrap(a / b.to_f64()))251            }252        }253        _ => type_err(""),254    }255}256257fn same(op: BinOp, a: f64, b: f64, wrap: fn(f64) -> Value) -> Result<Value, OpError> {258    match op {259        BinOp::Add => Ok(wrap(a + b)),260        BinOp::Sub => Ok(wrap(a - b)),261        BinOp::Div => {262            if b == 0.0 {263                Err(OpError::DivisionByZero)264            } else {265                Ok(Value::num(a / b))266            }267        }268        _ => type_err(""),269    }270}271272/// Arithmetic of the unit algebra (`+ - * / %`). Comparisons and logic are in [`compare`].273pub fn arithmetic(op: BinOp, a: &Value, b: &Value) -> Result<Value, OpError> {274    use Value::*;275    let add_sub = matches!(op, BinOp::Add | BinOp::Sub);276    match (a, b) {277        (Num(x), Num(y)) => num_arith(op, *x, *y).map(Num),278        (Duration(x), Duration(y)) => match op {279            BinOp::Add => x.checked_add(*y).map(Duration).ok_or(OpError::Overflow),280            BinOp::Sub => x.checked_sub(*y).map(Duration).ok_or(OpError::Overflow),281            BinOp::Div => {282                if y.is_zero() {283                    Err(OpError::DivisionByZero)284                } else {285                    x.checked_div(*y).map(|r| Num(self::Num::Exact(r))).ok_or(OpError::Overflow)286                }287            }288            _ => type_err("durations can be added, subtracted, scaled by a number or divided by a duration"),289        },290        // An exact bare number is a fraction of a whole note next to a duration.291        (Duration(x), Num(self::Num::Exact(y))) if add_sub => arithmetic(op, &Duration(*x), &Duration(*y)),292        (Num(self::Num::Exact(x)), Duration(y)) if add_sub => arithmetic(op, &Duration(*x), &Duration(*y)),293        (Duration(x), Num(n)) if matches!(op, BinOp::Mul | BinOp::Div) => dur_scale(*x, *n, op == BinOp::Div),294        (Num(n), Duration(x)) if op == BinOp::Mul => dur_scale(*x, *n, false),295        (Pitch(p), Interval(i)) if add_sub => Ok(Pitch(if op == BinOp::Add { p + i } else { p - i })),296        (Interval(i), Pitch(p)) if op == BinOp::Add => Ok(Pitch(p + i)),297        (Pitch(x), Pitch(y)) if op == BinOp::Sub => Ok(Interval(x - y)),298        (Pitch(_), Num(_)) if add_sub => type_err("to transpose a pitch add an interval: D4 + 2st, A4 + 25cents"),299        (Interval(x), Interval(y)) if op != BinOp::Mul && op != BinOp::Rem => same(op, *x, *y, Interval),300        (Interval(x), Num(n)) => scalar(op, *x, *n, Interval),301        (Num(n), Interval(x)) if op == BinOp::Mul => Ok(Interval(n.to_f64() * x)),302        (Gain(x), Gain(y)) if add_sub => same(op, *x, *y, Gain),303        (Gain(_), Num(_)) | (Num(_), Gain(_)) => type_err("gains combine with gains: -6dB + 3dB; use linear(g) or db(x) to convert"),304        (Freq(x), Freq(y)) if op != BinOp::Mul && op != BinOp::Rem => same(op, *x, *y, Freq),305        (Freq(x), Num(n)) => scalar(op, *x, *n, Freq),306        (Num(n), Freq(x)) if op == BinOp::Mul => Ok(Freq(n.to_f64() * x)),307        (Time(x), Time(y)) if op != BinOp::Mul && op != BinOp::Rem => same(op, *x, *y, Time),308        (Time(x), Num(n)) => scalar(op, *x, *n, Time),309        (Num(n), Time(x)) if op == BinOp::Mul => Ok(Time(n.to_f64() * x)),310        (Tempo(x), Tempo(y)) if op != BinOp::Mul && op != BinOp::Rem => same(op, *x, *y, Tempo),311        (Tempo(x), Num(n)) => scalar(op, *x, *n, Tempo),312        (Num(n), Tempo(x)) if op == BinOp::Mul => Ok(Tempo(n.to_f64() * x)),313        (Angle(x), Angle(y)) if add_sub => same(op, *x, *y, Angle),314        (Angle(x), Num(n)) => scalar(op, *x, *n, Angle),315        (Time(_), Duration(_)) | (Duration(_), Time(_)) => type_err("seconds and musical durations are different types; convert with seconds(d) or beats(d)"),316        (Str(x), Str(y)) if op == BinOp::Add => Ok(Value::str(&format!("{x}{y}"))),317        (Str(_), _) | (_, Str(_)) if op == BinOp::Add => type_err("convert the other operand with str(x)"),318        (List(x), List(y)) if op == BinOp::Add => {319            let mut v = x.as_ref().clone();320            v.extend(y.iter().cloned());321            Ok(Value::list(v))322        }323        // Transposing a chord: every pitch of the list moves.324        (List(x), Interval(_)) if add_sub && x.iter().all(|v| matches!(v, Pitch(_))) => {325            let mut out = Vec::with_capacity(x.len());326            for v in x.iter() {327                out.push(arithmetic(op, v, b)?);328            }329            Ok(Value::list(out))330        }331        _ => type_err(""),332    }333}334335/// Ordering of two values of the same kind. `None` when they cannot be compared.336pub fn compare(a: &Value, b: &Value) -> Option<Ordering> {337    use Value::*;338    match (a, b) {339        (Num(x), Num(y)) => match (x, y) {340            (self::Num::Exact(p), self::Num::Exact(q)) => Some(p.cmp(q)),341            _ => x.to_f64().partial_cmp(&y.to_f64()),342        },343        (Duration(x), Duration(y)) => Some(x.cmp(y)),344        (Duration(x), Num(self::Num::Exact(y))) | (Num(self::Num::Exact(x)), Duration(y)) => Some(x.cmp(y)),345        (Pitch(x), Pitch(y))346        | (Interval(x), Interval(y))347        | (Time(x), Time(y))348        | (Freq(x), Freq(y))349        | (Gain(x), Gain(y))350        | (Tempo(x), Tempo(y))351        | (Angle(x), Angle(y)) => x.partial_cmp(y),352        (Str(x), Str(y)) => Some(x.cmp(y)),353        (Bool(x), Bool(y)) => Some(x.cmp(y)),354        _ => None,355    }356}357358/// Structural equality (`==`); values of different kinds are never equal, except an exact359/// number and a duration of the same magnitude.360pub fn equal(a: &Value, b: &Value) -> bool {361    match (a, b) {362        (Value::List(x), Value::List(y)) => x.len() == y.len() && x.iter().zip(y.iter()).all(|(p, q)| equal(p, q)),363        (Value::PitchClass(x), Value::PitchClass(y)) => x.pitch_class() == y.pitch_class(),364        _ => compare(a, b) == Some(Ordering::Equal),365    }366}367368#[cfg(test)]369mod tests {370    use super::*;371372    fn r(n: i64, d: i64) -> Rational {373        Rational::new(n, d).unwrap()374    }375376    #[test]377    fn exact_numbers_stay_exact() {378        let q = arithmetic(BinOp::Div, &Value::int(1), &Value::int(4)).unwrap();379        assert_eq!(q, Value::Num(Num::Exact(r(1, 4))));380        assert_eq!(arithmetic(BinOp::Rem, &Value::int(-1), &Value::int(4)).unwrap(), Value::int(3));381        assert_eq!(arithmetic(BinOp::Div, &Value::int(1), &Value::int(0)), Err(OpError::DivisionByZero));382        // Overflow of plain numbers degrades to float instead of wrapping.383        let big = Value::int(i64::MAX);384        assert!(matches!(arithmetic(BinOp::Mul, &big, &big).unwrap(), Value::Num(Num::Float(_))));385    }386387    #[test]388    fn unit_algebra() {389        let d = Value::Duration(r(1, 4));390        assert_eq!(arithmetic(BinOp::Add, &d, &d).unwrap(), Value::Duration(r(1, 2)));391        assert_eq!(arithmetic(BinOp::Mul, &d, &Value::int(3)).unwrap(), Value::Duration(r(3, 4)));392        assert_eq!(arithmetic(BinOp::Mul, &d, &Value::num(1.5)).unwrap(), Value::Duration(r(3, 8)));393        assert_eq!(arithmetic(BinOp::Add, &d, &Value::Num(Num::Exact(r(1, 8)))).unwrap(), Value::Duration(r(3, 8)));394        assert_eq!(arithmetic(BinOp::Div, &d, &Value::Duration(r(1, 8))).unwrap(), Value::int(2));395        assert_eq!(arithmetic(BinOp::Add, &Value::Pitch(69.0), &Value::Interval(0.25)).unwrap(), Value::Pitch(69.25));396        assert_eq!(arithmetic(BinOp::Sub, &Value::Pitch(72.0), &Value::Pitch(60.0)).unwrap(), Value::Interval(12.0));397        assert_eq!(arithmetic(BinOp::Add, &Value::Gain(-6.0), &Value::Gain(3.0)).unwrap(), Value::Gain(-3.0));398        assert_eq!(arithmetic(BinOp::Mul, &Value::Freq(440.0), &Value::int(2)).unwrap(), Value::Freq(880.0));399        assert_eq!(arithmetic(BinOp::Div, &Value::Freq(880.0), &Value::Freq(440.0)).unwrap(), Value::num(2.0));400        assert!(matches!(arithmetic(BinOp::Add, &Value::Time(1.0), &d), Err(OpError::Type(Some(_)))));401        assert!(matches!(arithmetic(BinOp::Add, &Value::Pitch(60.0), &Value::int(2)), Err(OpError::Type(Some(_)))));402        assert!(matches!(arithmetic(BinOp::Mul, &Value::Gain(1.0), &Value::Gain(1.0)), Err(OpError::Type(_))));403        let chord = Value::list(vec![Value::Pitch(60.0), Value::Pitch(64.0)]);404        assert_eq!(arithmetic(BinOp::Add, &chord, &Value::Interval(2.0)).unwrap(), Value::list(vec![Value::Pitch(62.0), Value::Pitch(66.0)]));405        assert_eq!(arithmetic(BinOp::Mul, &Value::Duration(Rational::from_int(i64::MAX)), &Value::int(2)), Err(OpError::Overflow));406    }407408    #[test]409    fn names_and_comparisons() {410        assert_eq!(pitch_name(60.0), "C4");411        assert_eq!(pitch_name(69.25), "A4+25cents");412        assert_eq!(pitch_name(0.0), "C-1");413        assert_eq!(Value::list(vec![Value::Pitch(1.0)]).type_name(), "List<Pitch>");414        assert_eq!(compare(&Value::Duration(r(1, 4)), &Value::Num(Num::Exact(r(1, 2)))), Some(Ordering::Less));415        assert_eq!(compare(&Value::Pitch(1.0), &Value::int(1)), None);416        assert!(equal(&Value::int(2), &Value::num(2.0)));417    }418}419
Files main
Menu

Theme