SPB Git

Repository Public

builtins.rs 23.8 KB 587 lines rust

1//! ORIX Sonata2//! File: crates/sonata-semantics/src/builtins.rs3//! Description: Built-in constants and functions of the language (math, lists, seeded4//! randomness, durations, pitches, scales, chords, rhythms), with their documentation.5//!6//! Author: Simon-Pierre Boucher7//! Contact: contact@spboucher.ai89use crate::eval::{int_of, Analyzer, R};10use crate::value::{compare, equal, Num, Value};11use sonata_ir::{Mode, Rational, Span};12use std::cmp::Ordering;1314/// Documentation of one built-in function (hover, signature help, generated reference).15pub struct Builtin {16    pub name: &'static str,17    pub signature: &'static str,18    pub doc: &'static str,19}2021macro_rules! b {22    ($n:literal, $s:literal, $d:literal) => {23        Builtin { name: $n, signature: $s, doc: $d }24    };25}2627pub const BUILTINS: &[Builtin] = &[28    b!("len", "len(xs: List) -> Number", "Number of elements of a list."),29    b!("str", "str(x: Any) -> String", "Text of any value."),30    b!("min", "min(a, b, …) -> same type", "Smallest of its arguments (or of one list)."),31    b!("max", "max(a, b, …) -> same type", "Largest of its arguments (or of one list)."),32    b!("abs", "abs(x: Number) -> Number", "Absolute value (also of an Interval or a Time)."),33    b!("floor", "floor(x: Number) -> Number", "Largest integer not above x."),34    b!("ceil", "ceil(x: Number) -> Number", "Smallest integer not below x."),35    b!("round", "round(x: Number) -> Number", "Nearest integer, halves away from zero."),36    b!("sqrt", "sqrt(x: Number) -> Number", "Square root; x must not be negative."),37    b!("pow", "pow(base: Number, exponent: Number) -> Number", "base raised to exponent."),38    b!("sin", "sin(x: Number) -> Number", "Sine of x radians."),39    b!("cos", "cos(x: Number) -> Number", "Cosine of x radians."),40    b!("exp", "exp(x: Number) -> Number", "e raised to x."),41    b!("ln", "ln(x: Number) -> Number", "Natural logarithm; x must be positive."),42    b!("clamp", "clamp(x, lo, hi) -> same type", "x limited to [lo, hi]."),43    b!("lerp", "lerp(a: Number, b: Number, t: Number) -> Number", "Linear interpolation a + (b - a)·t."),44    b!("random", "random() -> Number", "Next seeded uniform number in [0, 1). Reproducible: the stream depends on `seed` and the track."),45    b!("random_int", "random_int(lo: Number, hi: Number) -> Number", "Next seeded integer in [lo, hi], both included."),46    b!("choose", "choose(xs: List) -> element", "A seeded random element of a non-empty list."),47    b!("shuffle", "shuffle(xs: List) -> List", "A seeded random permutation (Fisher–Yates)."),48    b!("note_value", "note_value(fraction: Number) -> Duration", "A musical duration from a fraction of a whole note: note_value(1/8) is an eighth note. Needed where a bare number is not already read as a duration, for example a tempo-synced effect time."),49    b!("dotted", "dotted(d: Duration) -> Duration", "d × 3/2."),50    b!("triplet", "triplet(d: Duration) -> Duration", "d × 2/3."),51    b!("seconds", "seconds(d: Duration) -> Time", "Length of a duration in seconds at the tempo in effect at position 0."),52    b!("beats", "beats(d: Duration) -> Number", "Length of a duration in beats of the current signature."),53    b!("hz", "hz(p: Pitch) -> Frequency", "Frequency of a pitch in twelve-tone equal temperament, A4 = 440 Hz (the composition `tuning` scales the result at render time)."),54    b!("midi", "midi(n: Number) -> Pitch", "Pitch of a MIDI note number (60 = C4), fractional for microtones."),55    b!("pitch_number", "pitch_number(p: Pitch) -> Number", "MIDI note number of a pitch."),56    b!("db", "db(x: Number) -> Gain", "Level of a linear amplitude ratio: 20·log10(x)."),57    b!("linear", "linear(g: Gain) -> Number", "Linear amplitude ratio of a level: 10^(g/20)."),58    b!("scale", "scale(root: Pitch, mode: String) -> List<Pitch>", "Pitches of one octave of a scale, from the root, without the octave."),59    b!("chord", "chord(root: Pitch, quality: String) -> List<Pitch>", "Pitches of a chord: maj, min, dim, aug, maj7, min7, dom7, dim7, min7b5, sus2, sus4, add9, maj9, min9, power."),60    b!("transpose", "transpose(x: Pitch | List<Pitch>, by: Interval) -> same type", "Moves a pitch or every pitch of a list."),61    b!("invert", "invert(chord: List<Pitch>, n: Number) -> List<Pitch>", "n-th inversion: the n lowest notes move up an octave (negative n moves the highest down)."),62    b!("degree", "degree(n: Number, octave: Number = 4) -> Pitch", "n-th degree (1 = tonic) of the composition key; degrees above 7 continue upwards."),63    b!("octave", "octave(p: Pitch) -> Number", "Octave number of a pitch (C4 is in octave 4)."),64    b!("pitch_class", "pitch_class(p: Pitch) -> Number", "Pitch class 0–11 of a pitch (0 = C)."),65    b!("interval", "interval(from: Pitch, to: Pitch) -> Interval", "Interval between two pitches."),66    b!("euclid", "euclid(hits: Number, steps: Number) -> List<Bool>", "Euclidean rhythm: `hits` onsets spread as evenly as possible over `steps`."),67    b!("reverse", "reverse(xs: List) -> List", "The list backwards (retrograde)."),68    b!("rotate", "rotate(xs: List, n: Number) -> List", "The list rotated left by n positions."),69    b!("take", "take(xs: List, n: Number) -> List", "The first n elements."),70    b!("drop", "drop(xs: List, n: Number) -> List", "The list without its first n elements."),71    b!("cycle", "cycle(xs: List, n: Number) -> List", "A list of n elements repeating xs."),72    b!("concat", "concat(a: List, b: List) -> List", "Both lists, one after the other."),73    b!("contains", "contains(xs: List, x: Any) -> Bool", "Whether x is an element of xs."),74    b!("sum", "sum(xs: List) -> element type", "Sum of the elements (numbers or durations)."),75];7677pub fn find(name: &str) -> Option<&'static Builtin> {78    BUILTINS.iter().find(|b| b.name == name)79}8081const MODES: &[(&str, Mode, &[u8])] = &[82    ("major", Mode::Major, &[0, 2, 4, 5, 7, 9, 11]),83    ("minor", Mode::Minor, &[0, 2, 3, 5, 7, 8, 10]),84    ("dorian", Mode::Dorian, &[0, 2, 3, 5, 7, 9, 10]),85    ("phrygian", Mode::Phrygian, &[0, 1, 3, 5, 7, 8, 10]),86    ("lydian", Mode::Lydian, &[0, 2, 4, 6, 7, 9, 11]),87    ("mixolydian", Mode::Mixolydian, &[0, 2, 4, 5, 7, 9, 10]),88    ("locrian", Mode::Locrian, &[0, 1, 3, 5, 6, 8, 10]),89    ("harmonic_minor", Mode::HarmonicMinor, &[0, 2, 3, 5, 7, 8, 11]),90    ("melodic_minor", Mode::MelodicMinor, &[0, 2, 3, 5, 7, 9, 11]),91    ("pentatonic_major", Mode::PentatonicMajor, &[0, 2, 4, 7, 9]),92    ("pentatonic_minor", Mode::PentatonicMinor, &[0, 3, 5, 7, 10]),93    ("blues", Mode::Blues, &[0, 3, 5, 6, 7, 10]),94    ("whole_tone", Mode::WholeTone, &[0, 2, 4, 6, 8, 10]),95    ("chromatic", Mode::Chromatic, &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]),96];9798const QUALITIES: &[(&str, &[u8])] = &[99    ("major", &[0, 4, 7]),100    ("minor", &[0, 3, 7]),101    ("maj", &[0, 4, 7]),102    ("min", &[0, 3, 7]),103    ("dim", &[0, 3, 6]),104    ("aug", &[0, 4, 8]),105    ("maj7", &[0, 4, 7, 11]),106    ("min7", &[0, 3, 7, 10]),107    ("dom7", &[0, 4, 7, 10]),108    ("dim7", &[0, 3, 6, 9]),109    ("min7b5", &[0, 3, 6, 10]),110    ("sus2", &[0, 2, 7]),111    ("sus4", &[0, 5, 7]),112    ("add9", &[0, 4, 7, 14]),113    ("maj9", &[0, 4, 7, 11, 14]),114    ("min9", &[0, 3, 7, 10, 14]),115    ("power", &[0, 7]),116];117118/// Names of every built-in constant (mode and chord-quality symbols, `pi`, `tau`, `on`, `off`).119pub const CONSTANTS: &[&str] = &[120    "major",121    "minor",122    "dorian",123    "phrygian",124    "lydian",125    "mixolydian",126    "locrian",127    "harmonic_minor",128    "melodic_minor",129    "pentatonic_major",130    "pentatonic_minor",131    "blues",132    "whole_tone",133    "chromatic",134    "maj",135    "min",136    "dim",137    "aug",138    "maj7",139    "min7",140    "dom7",141    "dim7",142    "min7b5",143    "sus2",144    "sus4",145    "add9",146    "maj9",147    "min9",148    "power",149    "pi",150    "tau",151    "on",152    "off",153];154155pub fn constant(name: &str) -> Option<Value> {156    match name {157        "pi" => Some(Value::num(std::f64::consts::PI)),158        "tau" => Some(Value::num(std::f64::consts::TAU)),159        "on" => Some(Value::Bool(true)),160        "off" => Some(Value::Bool(false)),161        n if CONSTANTS.contains(&n) => Some(Value::str(n)),162        _ => None,163    }164}165166pub fn mode_by_name(name: &str) -> Option<(Mode, &'static [u8])> {167    MODES.iter().find(|(n, _, _)| *n == name).map(|(_, m, s)| (*m, *s))168}169170pub fn mode_steps(mode: Mode) -> &'static [u8] {171    MODES.iter().find(|(_, m, _)| *m == mode).map(|(_, _, s)| *s).unwrap_or(&[0])172}173174pub fn mode_names() -> impl Iterator<Item = &'static str> {175    MODES.iter().map(|(n, _, _)| *n)176}177178type Args<'v> = &'v [(Value, Span)];179180fn arity<T>(an: &mut Analyzer, name: &str, span: Span) -> R<T> {181    let sig = find(name).map(|b| b.signature).unwrap_or(name);182    an.err_hint("S2005", span, format!("wrong number of arguments for '{name}'"), format!("signature: {sig}"))183}184185fn bad<T>(an: &mut Analyzer, name: &str, arg: &(Value, Span), want: &str) -> R<T> {186    let sig = find(name).map(|b| b.signature).unwrap_or(name);187    an.err_hint("T3002", arg.1, format!("'{name}' expects {want}, found {} ({})", arg.0.type_name(), arg.0.display()), format!("signature: {sig}"))188}189190fn num(an: &mut Analyzer, name: &str, arg: &(Value, Span)) -> R<f64> {191    match &arg.0 {192        Value::Num(n) => Ok(n.to_f64()),193        _ => bad(an, name, arg, "a Number"),194    }195}196fn int(an: &mut Analyzer, name: &str, arg: &(Value, Span)) -> R<i64> {197    match int_of(&arg.0) {198        Some(i) => Ok(i),199        None => bad(an, name, arg, "an integer"),200    }201}202fn pitch(an: &mut Analyzer, name: &str, arg: &(Value, Span)) -> R<f64> {203    match &arg.0 {204        Value::Pitch(p) => Ok(*p),205        _ => bad(an, name, arg, "a Pitch"),206    }207}208fn list<'v>(an: &mut Analyzer, name: &str, arg: &'v (Value, Span)) -> R<&'v [Value]> {209    match &arg.0 {210        Value::List(l) => Ok(l.as_slice()),211        _ => bad(an, name, arg, "a List"),212    }213}214fn dur(an: &mut Analyzer, name: &str, arg: &(Value, Span)) -> R<Rational> {215    match arg.0.as_duration() {216        Some(d) => Ok(d),217        None => bad(an, name, arg, "a Duration"),218    }219}220fn text<'v>(an: &mut Analyzer, name: &str, arg: &'v (Value, Span)) -> R<&'v str> {221    match &arg.0 {222        Value::Str(s) => Ok(s),223        _ => bad(an, name, arg, "a name such as minor or maj7"),224    }225}226fn finite(an: &mut Analyzer, name: &str, x: f64, span: Span) -> R<Value> {227    if x.is_finite() {228        // Keep integers exact so they can still be used as counts and durations.229        if x.fract() == 0.0 && x.abs() < 9.0e15 {230            Ok(Value::int(x as i64))231        } else {232            Ok(Value::num(x))233        }234    } else {235        an.err("T3005", span, format!("'{name}' is not defined for this argument"))236    }237}238fn checked_len(an: &mut Analyzer, len: usize, span: Span) -> R<()> {239    if len > an.quotas.max_list_len {240        let max = an.quotas.max_list_len;241        return an.abort("Q6004", span, format!("lists are limited to {max} elements"));242    }243    Ok(())244}245246pub(crate) fn call(an: &mut Analyzer, name: &str, a: Args, span: Span) -> R<Value> {247    macro_rules! need {248        ($n:expr) => {249            if a.len() != $n {250                return arity(an, name, span);251            }252        };253    }254    match name {255        "len" => {256            need!(1);257            Ok(Value::int(list(an, name, &a[0])?.len() as i64))258        }259        "str" => {260            need!(1);261            Ok(Value::str(&a[0].0.display()))262        }263        "min" | "max" => {264            let owned: Vec<(Value, Span)>;265            let items: &[(Value, Span)] = if a.len() == 1 {266                owned = list(an, name, &a[0])?.iter().map(|v| (v.clone(), a[0].1)).collect();267                &owned268            } else {269                a270            };271            if items.is_empty() {272                return arity(an, name, span);273            }274            let mut best = items[0].0.clone();275            for it in &items[1..] {276                match compare(&it.0, &best) {277                    Some(o) => {278                        if (name == "min" && o == Ordering::Less) || (name == "max" && o == Ordering::Greater) {279                            best = it.0.clone();280                        }281                    }282                    None => return an.err("T3002", it.1, format!("'{name}' cannot compare {} with {}", it.0.type_name(), best.type_name())),283                }284            }285            Ok(best)286        }287        "abs" => {288            need!(1);289            Ok(match &a[0].0 {290                Value::Num(Num::Exact(r)) if r.is_negative() => Value::Num(Num::Exact(Rational::ZERO.checked_sub(*r).unwrap_or(*r))),291                Value::Num(Num::Float(f)) => Value::num(f.abs()),292                Value::Num(n) => Value::Num(*n),293                Value::Interval(x) => Value::Interval(x.abs()),294                Value::Time(x) => Value::Time(x.abs()),295                _ => return bad(an, name, &a[0], "a Number"),296            })297        }298        "floor" | "ceil" | "round" | "sqrt" | "sin" | "cos" | "exp" | "ln" => {299            need!(1);300            let x = num(an, name, &a[0])?;301            let y = match name {302                "floor" => x.floor(),303                "ceil" => x.ceil(),304                "round" => x.round(),305                "sqrt" => x.sqrt(),306                "sin" => x.sin(),307                "cos" => x.cos(),308                "exp" => x.exp(),309                _ => x.ln(),310            };311            if matches!(name, "floor" | "ceil" | "round" | "sqrt") {312                finite(an, name, y, a[0].1)313            } else if y.is_finite() {314                Ok(Value::num(y))315            } else {316                an.err("T3005", a[0].1, format!("'{name}' is not defined for this argument"))317            }318        }319        "pow" => {320            need!(2);321            let (x, y) = (num(an, name, &a[0])?, num(an, name, &a[1])?);322            finite(an, name, x.powf(y), span)323        }324        "clamp" => {325            need!(3);326            match (compare(&a[0].0, &a[1].0), compare(&a[0].0, &a[2].0)) {327                (Some(lo), Some(hi)) => Ok(if lo == Ordering::Less {328                    a[1].0.clone()329                } else if hi == Ordering::Greater {330                    a[2].0.clone()331                } else {332                    a[0].0.clone()333                }),334                _ => an.err("T3002", span, "'clamp' needs three values of the same type"),335            }336        }337        "lerp" => {338            need!(3);339            let (x, y, t) = (num(an, name, &a[0])?, num(an, name, &a[1])?, num(an, name, &a[2])?);340            Ok(Value::num(x + (y - x) * t))341        }342        "random" => {343            need!(0);344            Ok(Value::num(an.rng.next_f64()))345        }346        "random_int" => {347            need!(2);348            let (lo, hi) = (int(an, name, &a[0])?, int(an, name, &a[1])?);349            if hi < lo {350                return an.err("T3005", span, format!("random_int needs lo <= hi, found {lo} and {hi}"));351            }352            let width = (hi as i128 - lo as i128 + 1) as u64;353            Ok(Value::int((lo as i128 + an.rng.below(width) as i128) as i64))354        }355        "choose" => {356            need!(1);357            let xs = list(an, name, &a[0])?;358            if xs.is_empty() {359                return an.err("T3008", a[0].1, "cannot choose from an empty list");360            }361            let i = an.rng.below(xs.len() as u64) as usize;362            Ok(xs[i].clone())363        }364        "shuffle" => {365            need!(1);366            let mut xs = list(an, name, &a[0])?.to_vec();367            for i in (1..xs.len()).rev() {368                let j = an.rng.below(i as u64 + 1) as usize;369                xs.swap(i, j);370            }371            Ok(Value::list(xs))372        }373        "note_value" => {374            need!(1);375            Ok(Value::Duration(dur(an, name, &a[0])?))376        }377        "dotted" | "triplet" => {378            need!(1);379            let d = dur(an, name, &a[0])?;380            let f = if name == "dotted" { Rational::new(3, 2) } else { Rational::new(2, 3) }.unwrap_or(Rational::ONE);381            match d.checked_mul(f) {382                Some(r) => Ok(Value::Duration(r)),383                None => an.overflow(span),384            }385        }386        "seconds" => {387            need!(1);388            let d = dur(an, name, &a[0])?;389            Ok(Value::Time(d.to_f64() * 240.0 / an.tempo0))390        }391        "beats" => {392            need!(1);393            let d = dur(an, name, &a[0])?;394            let (_, den) = an.signature_at(an.now);395            match d.checked_mul(Rational::from_int(den as i64)) {396                Some(r) => Ok(Value::Num(Num::Exact(r))),397                None => an.overflow(span),398            }399        }400        "hz" => {401            need!(1);402            let p = pitch(an, name, &a[0])?;403            Ok(Value::Freq(440.0 * ((p - 69.0) / 12.0).exp2()))404        }405        "midi" => {406            need!(1);407            let n = num(an, name, &a[0])?;408            if !(-12.0..=140.0).contains(&n) {409                return an.err("T3005", a[0].1, format!("MIDI note {n} is outside [-12, 140]"));410            }411            Ok(Value::Pitch(n))412        }413        "pitch_number" => {414            need!(1);415            let p = pitch(an, name, &a[0])?;416            finite(an, name, p, span)417        }418        "db" => {419            need!(1);420            let x = num(an, name, &a[0])?;421            if x <= 0.0 {422                return an.err("T3005", a[0].1, "db(x) needs a positive ratio");423            }424            Ok(Value::Gain(20.0 * x.log10()))425        }426        "linear" => {427            need!(1);428            match &a[0].0 {429                Value::Gain(g) => Ok(Value::num(10f64.powf(g / 20.0))),430                _ => bad(an, name, &a[0], "a Gain"),431            }432        }433        "scale" => {434            need!(2);435            let root = pitch(an, name, &a[0])?;436            let m = text(an, name, &a[1])?;437            match mode_by_name(m) {438                Some((_, steps)) => Ok(Value::list(steps.iter().map(|s| Value::Pitch(root + *s as f64)).collect())),439                None => an.unknown("S2001", a[1].1, "scale mode", m, mode_names()),440            }441        }442        "chord" => {443            need!(2);444            let root = pitch(an, name, &a[0])?;445            let q = text(an, name, &a[1])?;446            match QUALITIES.iter().find(|(n, _)| *n == q) {447                Some((_, steps)) => Ok(Value::list(steps.iter().map(|s| Value::Pitch(root + *s as f64)).collect())),448                None => an.unknown("S2001", a[1].1, "chord quality", q, QUALITIES.iter().map(|(n, _)| *n)),449            }450        }451        "transpose" => {452            need!(2);453            let Value::Interval(by) = a[1].0 else { return bad(an, name, &a[1], "an Interval such as 7st") };454            match &a[0].0 {455                Value::Pitch(p) => Ok(Value::Pitch(p + by)),456                Value::List(xs) if xs.iter().all(|v| matches!(v, Value::Pitch(_))) => {457                    Ok(Value::list(xs.iter().map(|v| if let Value::Pitch(p) = v { Value::Pitch(p + by) } else { v.clone() }).collect()))458                }459                _ => bad(an, name, &a[0], "a Pitch or a list of pitches"),460            }461        }462        "invert" => {463            need!(2);464            let xs = list(an, name, &a[0])?;465            let n = int(an, name, &a[1])?;466            let mut ps = Vec::with_capacity(xs.len());467            for v in xs {468                match v {469                    Value::Pitch(p) => ps.push(*p),470                    _ => return bad(an, name, &a[0], "a list of pitches"),471                }472            }473            if ps.is_empty() || n.unsigned_abs() > 64 {474                return an.err("T3005", span, "invert needs a non-empty chord and at most 64 inversions");475            }476            ps.sort_by(|x, y| x.partial_cmp(y).unwrap_or(Ordering::Equal));477            for _ in 0..n.unsigned_abs() {478                if n > 0 {479                    let low = ps.remove(0);480                    ps.push(low + 12.0);481                } else {482                    let high = ps.pop().unwrap_or(0.0);483                    ps.insert(0, high - 12.0);484                }485            }486            Ok(Value::list(ps.into_iter().map(Value::Pitch).collect()))487        }488        "degree" => {489            if a.is_empty() || a.len() > 2 {490                return arity(an, name, span);491            }492            let n = int(an, name, &a[0])?;493            let oct = if a.len() == 2 { int(an, name, &a[1])? } else { 4 };494            let Some(key) = an.key else {495                return an.err_hint("M4018", span, "degree() needs the key of the composition", "declare it before the tracks: key D minor");496            };497            if !(1..=128).contains(&n) || !(-1..=9).contains(&oct) {498                return an.err("T3005", span, "degree() takes a degree from 1 and an octave from -1 to 9");499            }500            let steps = mode_steps(key.mode);501            let idx = (n - 1) as usize;502            let semis = steps[idx % steps.len()] as i64 + 12 * (idx / steps.len()) as i64;503            Ok(Value::Pitch(((oct + 1) * 12 + key.tonic as i64 + semis) as f64))504        }505        "octave" | "pitch_class" => {506            need!(1);507            let p = pitch(an, name, &a[0])?.round() as i64;508            Ok(Value::int(if name == "octave" { p.div_euclid(12) - 1 } else { p.rem_euclid(12) }))509        }510        "interval" => {511            need!(2);512            let (x, y) = (pitch(an, name, &a[0])?, pitch(an, name, &a[1])?);513            Ok(Value::Interval(y - x))514        }515        "euclid" => {516            need!(2);517            let (k, n) = (int(an, name, &a[0])?, int(an, name, &a[1])?);518            if n <= 0 || k < 0 || k > n {519                return an.err("T3005", span, format!("euclid needs 0 <= hits <= steps and steps > 0, found {k} and {n}"));520            }521            checked_len(an, n as usize, span)?;522            // Bresenham form of the Euclidean rhythm; the first step is an onset when k > 0.523            Ok(Value::list((0..n).map(|i| Value::Bool((i * k) % n < k)).collect()))524        }525        "reverse" => {526            need!(1);527            let mut xs = list(an, name, &a[0])?.to_vec();528            xs.reverse();529            Ok(Value::list(xs))530        }531        "rotate" => {532            need!(2);533            let mut xs = list(an, name, &a[0])?.to_vec();534            let n = int(an, name, &a[1])?;535            if !xs.is_empty() {536                let k = n.rem_euclid(xs.len() as i64) as usize;537                xs.rotate_left(k);538            }539            Ok(Value::list(xs))540        }541        "take" | "drop" => {542            need!(2);543            let xs = list(an, name, &a[0])?;544            let n = int(an, name, &a[1])?.clamp(0, xs.len() as i64) as usize;545            Ok(Value::list(if name == "take" { xs[..n].to_vec() } else { xs[n..].to_vec() }))546        }547        "cycle" => {548            need!(2);549            let xs = list(an, name, &a[0])?;550            let n = int(an, name, &a[1])?;551            if xs.is_empty() || n < 0 {552                return an.err("T3005", span, "cycle needs a non-empty list and a non-negative length");553            }554            checked_len(an, n as usize, span)?;555            Ok(Value::list((0..n as usize).map(|i| xs[i % xs.len()].clone()).collect()))556        }557        "concat" => {558            need!(2);559            let mut xs = list(an, name, &a[0])?.to_vec();560            xs.extend_from_slice(list(an, name, &a[1])?);561            checked_len(an, xs.len(), span)?;562            Ok(Value::list(xs))563        }564        "contains" => {565            need!(2);566            let xs = list(an, name, &a[0])?;567            Ok(Value::Bool(xs.iter().any(|v| equal(v, &a[1].0))))568        }569        "sum" => {570            need!(1);571            let xs = list(an, name, &a[0])?;572            let mut acc = match xs.first() {573                Some(v) => v.clone(),574                None => return Ok(Value::int(0)),575            };576            for v in &xs[1..] {577                acc = match crate::value::arithmetic(sonata_parser::ast::BinOp::Add, &acc, v) {578                    Ok(v) => v,579                    Err(_) => return an.err("T3002", a[0].1, format!("cannot sum {} and {}", acc.type_name(), v.type_name())),580                };581            }582            Ok(acc)583        }584        _ => an.err("S2001", span, format!("unknown function '{name}'")),585    }586}587
Files main
Menu

Theme