Repository Public
1<!--2ORIX Sonata3File: Documentation/spec/sonata-language.md4Author: Simon-Pierre Boucher5Contact: contact@spboucher.ai6-->7# The Sonata language — version 0.1 (normative)89Sonata describes music as a program. A source file is compiled to a **Musical IR** (timestamped10notes, tempo map, automation, routing) and an **Audio DSP IR** (the mixing graph), which the11runtime turns into sound. This document defines what a program means. The grammar is in12[`grammar.ebnf`](grammar.ebnf), the diagnostics in [`diagnostics.md`](diagnostics.md), the13versioning rules in [`compatibility.md`](compatibility.md).1415Every block marked `sonata` in this document is a complete program that the test suite16compiles (`crates/sonata-compiler/tests/spec.rs`). Blocks marked `text` are fragments.1718Words used: **must** is a rule the compiler enforces with an error; **is** defines behaviour.1920## 1. A first program2122```sonata23composition "Aurora" {24 tempo 120bpm25 key D minor26 signature 4/427 seed 4228 instrument piano: GrandPiano {29 gain -8dB30 sequence {31 chord [D3, A3, D4] duration 1/232 chord [F3, A3, C4] duration 1/233 rest 1/434 play A4 duration 1/4 velocity 0.7535 }36 effects { reverb hall(mix: 0.2) }37 }38 instrument strings: ConcertStrings {39 articulation legato40 play D4 duration 1/141 }42 master { sample_rate 48000Hz; peak_limit -1dB }43}44```4546A file holds top-level *items* (imports, constants, functions, patterns, instrument47definitions) and *compositions*. A file without a composition is a *module*. The compiler48compiles the first composition of the root file, or the one whose title is requested.4950## 2. Lexical structure5152* Source is UTF-8, at most 4 MiB. Line comments `// …`; block comments `/* … */` nest.53* Strings are written on one line between double quotes, with the escapes `\n`, `\t`, `\"`,54 `\\` and `\u{HEX}` (1 to 6 hexadecimal digits).55* **Numbers** are integers (`42`, `48_000`) or decimals (`0.75`). Integers are exact. A unit is56 glued to the number: `120bpm`, `440Hz`, `2kHz`, `-8dB` (the minus is an operator), `5ms`,57 `2s`, `7st`, `25cents`, `60%`, `3bars`, `1beat`, `90deg`.58* **Note literals** are a letter `A`–`G`, an optional accidental (`#`, `##`, `b`, `bb`) and an59 octave from `-1` to `9`: `C4` is MIDI 60, `A4` is MIDI 69, `C-1` is MIDI 0.60 **Pitch-class literals** have no octave: `D`, `F#`, `Bb`.61 A token of either shape is always a literal and can never be a name: `A4`, `Bb` and `C` are62 not identifiers; `a4`, `Amp`, `Cmaj` are.63* **Identifiers** are ASCII letters, digits and `_`, not starting with a digit. The reserved64 words are listed in the grammar. A reserved word may still be used as an argument label65 (`lowpass(in: x)`), and `chord(…)` and `clip(…)` written as calls are the built-in function66 and the patch node.67* **Lines.** Statements are separated by a line break or `;`. An expression continues on the68 next line only if the current line ends with an operator, a comma or an open bracket. A69 line that starts with `-`, `(`, `[` or any operator starts a new statement.7071## 3. Values, types and units7273| Type | Literal or source | Canonical unit |74|---|---|---|75| `Number` | `3`, `1/4`, `0.75`, `60%` | exact rational when written with integers, float otherwise |76| `Bool` | `true`, `false`, `on`, `off` | |77| `String` | `"text"`, mode and chord names (`minor`, `maj7`) | |78| `Pitch` (`Note`) | `D4`, `midi(62)` | MIDI number, fractional for microtones |79| `PitchClass` | `D`, `Bb` | used by `key` |80| `Interval` | `7st`, `25cents` | semitones |81| `Duration` (`Beat`, `Bar`) | `2bars`, `1beat`, `note_value(1/8)` | exact rational of a whole note |82| `Time` | `5ms`, `2s` | seconds |83| `Frequency` | `440Hz`, `2kHz` | hertz |84| `Gain` | `-6dB` | decibels |85| `Tempo` | `120bpm` | quarter notes per minute |86| `Angle` | `90deg` | degrees |87| `Velocity` | a `Number` in [0, 1] | linear |88| `Pan` | a `Number` in [-1, 1] | -1 left, 1 right |89| `List<T>`, `Chord`, `Scale` | `[D3, A3, D4]`, `0..4` | `Chord` and `Scale` are `List<Pitch>` |9091`TimeSignature`, `Pattern`, `Sequence`, `Instrument`, `Bus`, `AudioBuffer`, `Signal` and92`ControlSignal` name things of the language but are not value types in 0.1: using one in an93annotation is error T3010. Signals exist inside `graph` blocks (section 9).9495### 3.1 Three kinds of time9697Musical durations (`Duration`), seconds (`Time`) and sample counts are distinct and never mix98implicitly; `1s + 1/4` is error T3001.99100* In a **duration position** (after `duration`, `rest`, `at`, in automation positions, …) a101 bare exact number is a fraction of a **whole note**: `1/4` is a quarter note, which is one102 beat in 4/4. Floats are refused there (T3003): musical time is exact.103* `2bars` and `3beats` are durations resolved with the signature in effect at the cursor: a104 beat is `1/denominator` of a whole note, a bar is `numerator/denominator`.105* `note_value(1/8)` makes a `Duration` from a fraction where no duration is expected, for106 example for a tempo-synced effect time. The standard constants `whole`, `half`, `quarter`,107 `eighth`, `sixteenth` are durations.108* Conversions are explicit: `seconds(d)` (at the tempo in effect at position 0),109 `beats(d)`, `hz(p)`, `db(x)`, `linear(g)`.110111Musical positions and durations are exact rationals with 64-bit numerator and denominator.112Overflow is error Q6005; nothing wraps. Seconds are derived from the tempo map (section 6.3) as11364-bit floats, and a sample index is `floor(seconds × rate + 0.5)`. This single rule is114`sonata_ir::time::seconds_to_samples`; the offline renderer, the real-time engine and the115studio rulers all use it.116117### 3.2 Operators118119| Expression | Result |120|---|---|121| `Number ± × ÷ % Number` | `Number`; exact while both are exact (`1/4` is one quarter, never 0) |122| `Duration ± Duration`, `Duration ± exact Number` | `Duration` |123| `Duration × Number`, `Duration ÷ Number` | `Duration` (a float factor is approximated by a fraction with denominator ≤ 40 320) |124| `Duration ÷ Duration` | `Number` |125| `Pitch ± Interval` | `Pitch` — microtones are arithmetic: `A4 + 25cents` |126| `Pitch − Pitch` | `Interval` |127| `List<Pitch> ± Interval` | every pitch moves |128| `Interval ± Interval`, `Interval × Number`, `Interval ÷ Interval` | `Interval`, `Interval`, `Number` |129| `Gain ± Gain` | `Gain` |130| `Frequency`, `Time`, `Tempo`: `± same`, `× ÷ Number`, `÷ same` | same type, same type, `Number` |131| `String + String`, `List + List` | concatenation |132| `== != < <= > >=` | `Bool`; both sides of the same kind |133| `and`, `or`, `not` | `Bool`; `and` and `or` evaluate their right side only if needed |134| `a..b`, `a..=b` | list of integers, end excluded or included |135| `xs[i]` | element; negative indices count from the end; out of range is T3008 |136| `xs.len`, `xs.first`, `xs.last`, `p.midi`, `p.octave`, `p.class`, `p.hz` | members |137| `if c then a else b` | conditional expression |138139Anything else is a type error that names both types and, where one exists, the conversion to140use. Division by zero is T3007. An exact `Number` that would overflow becomes a float; a141`Duration` that would overflow is Q6005.142143Precedence, lowest first: `or`, `and`, `not`, comparisons, ranges, `+ -`, `* / %`, unary `-` and `+` (a leading plus has no effect: `gain +4dB`),144then indexing, member access and calls. Binary operators associate to the left.145146### 3.3 Type checking147148Names, kinds (function, pattern, instrument, value) and argument counts are checked statically149in every file, executed or not. Types and units are checked when an expression is evaluated,150with the exact source span; an annotation (`let x: Pitch = …`, parameters, return types) is151checked at that point too and applies one coercion: an exact number becomes a `Duration`.152A composition is evaluated completely at compile time, so every statement that contributes to153the music is checked; a branch that is never taken, or a function that is never called, is154checked for names and arity only.155156## 4. Names, modules and scope157158```sonata159import std.music160161const root = D3162let motif = [root, root + 7st, root + 12st]163164fn double(d: Duration) -> Duration {165 return d * 2166}167168pattern there_and_back(notes: List<Pitch>, step: Duration = 1/8) {169 for n in notes + reverse(notes) {170 play n duration step171 }172}173174composition "Scopes" {175 let step = 1/16176 instrument a: Harp {177 let local = double(step)178 there_and_back(motif, step: local)179 }180}181```182183* Top-level `const` and `let` are both constants, evaluated on first use; one that depends on184 itself is S2006. Inside blocks, `let` declares a variable that can be reassigned185 (`x = x + 1`), `const` one that cannot. A block opens a scope.186* A composition's own `let`s are visible in its tracks. Functions and patterns see only their187 parameters and top-level definitions.188* **Imports.** `import a.b` loads a module. `std.*` modules are embedded in the compiler. Any189 other path is given by the host through a `SourceLoader`; the command line and the app map190 `a.b` to `<project root>/a/b.sonata`, refuse anything that resolves outside the root (after191 following symbolic links) and files over 4 MiB. The language has no other access to files,192 and none to the network or to processes.193* Everything top-level of an imported module is visible unqualified. Two project definitions194 of the same name are S2002; a project definition silently shadows a standard one. Import195 cycles are I7002, a missing module I7001, more than 16 nested imports I7003.196* **Prelude.** `std.music`, `std.instruments` and `std.effects` are always in scope; importing197 them explicitly is allowed and has no effect.198199### 4.1 Functions200201`fn name(a: T, b: T = default) -> T { … }` is a pure function: its body may contain `let`,202assignment, `if`, `for`, `repeat`, `return` and calls, and nothing that produces music.203Arguments are positional, then named (`f(1, b: 2)`). Call depth is limited to 64 (Q6003).204205### 4.2 Patterns206207`pattern name(params) { track statements }` is a reusable piece of a track. Calling it as a208statement runs its body at the caller's cursor and advances it. Scoped transforms set inside a209pattern (`transpose`, `swing`) do not leak out.210211### 4.3 Randomness212213`random()`, `random_int(a, b)`, `choose(xs)` and `shuffle(xs)` draw from a SplitMix64 stream214selected by `seed` (default 0). Each track has its own stream, derived from the seed and the215track's declaration order; code outside tracks uses a separate stream. The same source and216seed always give the same Program.217218## 5. Compositions219220`composition "Title" { … }` contains, in any order:221222| Statement | Meaning |223|---|---|224| `tempo 120bpm` | tempo at position 0 (default 120) |225| `key D minor` | key; modes: `major minor dorian phrygian lydian mixolydian locrian harmonic_minor melodic_minor pentatonic_major pentatonic_minor blues whole_tone chromatic` |226| `signature 4/4` | signature at position 0 (default 4/4) |227| `seed 42` | random seed (default 0) |228| `swing 60%` / `swing 60% of 1/16` | default swing of every track (section 6.5) |229| `tuning 442Hz` | frequency of A4, 220–880 Hz (default 440) |230| `instrument name: Type { … }` | an instrument track (section 6) |231| `audio name { clip "file.wav" at 0bars }` | an audio track (section 8.3) |232| `bus name { … }`, `master { … }` | mixer strips (section 8) |233| `marker "A" at 4bars` | a named position |234| `at POSITION { tempo …; signature …; marker … }` | the same statements at another position |235| `let`, `const` | variables visible in the tracks |236237Whatever their order in the source, the settings, buses, master and variables of a composition238are evaluated before its tracks, so every track sees the same tempo, signatures, key and swing.239Tracks are then evaluated in declaration order.240241## 6. Tracks: the cursor model242243A track body is executed once, at compile time. It has a **cursor**, a musical position that244starts at 0. Statements place events at the cursor and move it.245246```sonata247composition "Cursor" {248 tempo 96bpm249 signature 3/4250 instrument flute: Flute {251 default duration 1/8252 play D5 duration 1/4 // cursor: 0 → 1/4253 play [F5, A5] duration 1/4 // a chord: both notes at 1/4254 rest 1beat // cursor: 1/2 → 3/4, one full bar255 repeat 2 {256 play A5257 play F5 staccato258 }259 at 4bars {260 play D6 duration 1bar // placed at bar 5; the cursor does not move261 }262 tuplet 3 in 2 {263 for n in [D5, E5, F5] {264 play n duration 1/4 // three quarters in the time of two265 }266 }267 }268}269```270271### 6.1 Notes272273`play PITCH {modifier}` places a note; `play LIST` and `chord LIST` place the notes of a list274together. `chord` requires a list. The cursor advances by the duration.275276| Modifier | Meaning | Default |277|---|---|---|278| `duration D` | notated duration, must be positive | `default duration`, initially `1/4` |279| `velocity V` | linear velocity in [0, 1] | `default velocity`, initially `0.8` |280| an articulation | `normal legato staccato staccatissimo tenuto marcato accent pizzicato tremolo` | the track's `articulation`, initially `normal` |281| `tie` | ties this note to the next note of the same pitch in the same voice | |282| `bend { 0ms: 0st, 200ms: 2st }` | pitch curve relative to the note start, in time order, within ±48 st | none |283284`rest D` moves the cursor by `D` (zero is allowed, negative is M4009).285286Articulations are the only place where the compiler changes what was written, and exactly so:287288| Articulation | Sounding duration | Velocity |289|---|---|---|290| `staccato` | 50 % of the notated duration | unchanged |291| `staccatissimo` | 25 % | unchanged |292| `marcato` | 100 % | × 1.2, at most 1 |293| `accent` | 100 % | × 1.25, at most 1 |294| others | 100 % | unchanged |295296The cursor always advances by the notated duration. Every note keeps both its notated and its297sounding start and duration in the IR; engines receive the articulation and may respond to it298(a bowed string slurs `legato`, plucks `pizzicato`).299300**Ties.** A note with `tie` and the next note of the same pitch in the same voice, starting301exactly where it ends, are one sounding note whose duration is the sum; a chain may continue.302The IR holds that single note (score export splits it at bar lines). A tie without303continuation is warning M4005.304305**Range.** A note outside the playable range of the instrument's engine is warning M4001 and306is rendered anyway.307308### 6.2 Structure309310| Statement | Effect on the cursor |311|---|---|312| `sequence { … }` | a group; statements run one after the other |313| `voice { … }` | adjacent `voice` blocks start together, each on its own voice number; the cursor advances by the longest |314| `parallel { … }` | every direct statement of the block starts at the cursor; the cursor advances by the longest |315| `at POS { … }` | the block runs at absolute position `POS`; the cursor is unchanged afterwards |316| `repeat N { … }` | `N` times; `N` is a non-negative integer |317| `for x in LIST { … }` | once per element |318| `if C { … } else if D { … } else { … }` | `C` must be a `Bool` |319| `tuplet N in M { … }` | durations inside are multiplied by `M/N` (nested tuplets multiply) |320| `transpose I { … }` / `transpose I` | pitches move by interval `I` in the block, or from here to the end of the enclosing block |321| `swing R [of U] { … }` / `swing R [of U]` | swing in the block, or from here on |322| `name(args)` | runs a pattern at the cursor |323324All loops are bounded by the evaluation-step quota (Q6002).325326### 6.3 Tempo327328`tempo T` sets the tempo at the cursor. `tempo T ramp D` moves the tempo linearly, in musical329position, from the tempo in effect at the cursor to `T` over duration `D`. Tempo is always in330quarter notes per minute, whatever the signature.331332Seconds are the integral of the tempo map. A constant segment contributes333`length × 240 / bpm` seconds per whole note of length; a ramp contributes the trapezoid of the334linearly interpolated seconds-per-whole-note. Two different tempos set at the same position335are M4004. Tempos outside [1, 1000] bpm are M4003.336337Effect and instrument parameters that are *times* accept a musical duration and convert it at338the tempo in effect at position 0; they do not follow later tempo changes in 0.1.339340### 6.4 Signatures341342`signature N/D` sets the signature at the cursor, which must be on a bar line of the signature343it replaces (M4002). `N` is 1–64, `D` a power of two up to 64 (M4007). Signatures decide what344`bars` and `beats` mean and how the score is barred; they do not change durations already345written as fractions. Declare meter changes at composition level (`at 4bars { signature 7/8 }`)346so every track counts bars the same way.347348### 6.5 Swing349350With ratio `r` in [50 %, 75 %] and unit `u` (default `1/8`), a note whose notated start is an351odd multiple of `u` starts `(2r − 1) × u` later, and ends where it would have ended (it is352shortened by the same amount). 50 % is straight; 66.7 % is a triplet feel. Other notes are353untouched.354355## 7. Instruments356357A track's type is an instrument definition, or directly the name of a registry engine.358359```sonata360instrument CrystalHarp {361 model plucked_string362 damping 0.015363 excitation pluck(position: 0.35)364 resonance modal(frequencies: [440Hz, 880Hz, 1320Hz])365 envelope adsr(attack: 5ms, decay: 300ms, sustain: 0.6, release: 2s)366}367368instrument SoftHarp: CrystalHarp {369 damping 0.05370 brightness 0.3371}372373composition "Instruments" {374 instrument a: CrystalHarp { play A4 }375 instrument b: SoftHarp { play A3 }376 instrument c: Marimba { play A2 }377}378```379380* `model m` selects a registry **engine** (`piano`, `plucked_string`, `bowed_string`, `flute`,381 `clarinet`, `brass`, `organ`, `bass`, `synth`, `fm`, `kick`, `snare`, `hihat`,382 `modal_percussion`, `voice`, `patch`). An instrument must have a model, its own or inherited.383* `preset p` applies a preset of the engine; `name value` sets a parameter; members apply in384 order, so later lines override earlier ones.385* `slot kind(arg: value)` sets the choice parameter `slot` to `kind` and the parameters386 `slot.arg`. `envelope.attack 5ms` is the same parameter written directly.387* `instrument B: A { … }` inherits everything from `A` and then applies its own members; it388 cannot change the model (S2027).389* Every name, unit and range is validated against the **registry**, the metadata the DSP390 crates publish (`sonata_compiler::registry()`). Units are checked dimensionally: a time391 parameter accepts `5ms` or a musical duration, never a bare number (T3006); out of range is392 T3005. The parameter reference of the documentation is generated from the same metadata.393* The standard library (`std.instruments`) defines the named instruments (`GrandPiano`,394 `ConcertStrings`, `NylonGuitar`, `Marimba`, …), each one an engine with one of its presets.395396The models are approximations chosen for musical usefulness, not exact physical simulations;397each engine documents its method and its domain of validity.398399## 8. Mixing400401### 8.1 Strips402403Tracks, buses and the master are *strips* with the same statements:404405| Statement | Tracks | Buses | Master |406|---|---|---|---|407| `gain G` — fader, [-120, 24] dB, default 0 dB | yes | yes | yes |408| `pan P` — [-1, 1], constant-power law, −3 dB at the centre | yes | yes | |409| `mute`, `mute off` | yes | yes | |410| `solo` | yes | | |411| `effects { … }` — insert chain, in order | yes | yes | yes |412| `send BUS [GAIN] [pre]` — post-fader unless `pre` | yes | yes | |413| `output BUS` — default `master` | yes | yes | |414| `automate TARGET { … }` | yes | yes | yes |415| `sample_rate`, `peak_limit` | | | yes |416417```sonata418composition "Mix" {419 tempo 110bpm420 bus hall {421 effects {422 reverb hall(mix: 100%)423 }424 gain -8dB425 }426 instrument keys: ElectricPiano {427 gain -9dB428 pan -0.2429 send hall -6dB430 effects {431 eq(low_cut: 80Hz)432 bypass chorus lush433 delay(time: note_value(3/16), feedback: 0.3, mix: 0.2)434 }435 chord [D3, F3, A3, C4] duration 2bars436 automate gain {437 0bars: -30dB438 1bar: -9dB exp439 }440 automate delay.feedback {441 0bars: 0.2442 2bars: 0.6443 }444 }445 master {446 sample_rate 48000Hz447 peak_limit -1dB448 }449}450```451452### 8.2 Effects453454An effect is `[bypass] kind [preset] [(name: value, …)]`. Arguments are named. `mix` is the455dry/wet ratio in [0, 1] of every effect (its default comes from the registry); the runtime456mixes the dry signal aligned with the effect's latency, and a bypassed effect keeps its457latency, so bypassing never shifts a track.458459### 8.3 Audio tracks460461`audio name { clip "path" at POS [offset T] [length T] [gain G] [fade_in T] [fade_out T] }`462places an audio file. The path is relative to the project's `assets` directory; absolute463paths, `..`, backslashes and control characters are refused (I7005). The compiler does not464open the file: the host supplies its samples to the runtime.465466### 8.4 Automation467468`automate TARGET { POSITION: VALUE [curve], … }` records a lane. Targets are `gain`, `pan`,469`instrument.PARAM` and `EFFECT.PARAM` (`EFFECT[1].PARAM` for the second effect of that kind;470the effect must be declared above). Positions are durations **relative to the cursor** of the471statement, in non-decreasing order (M4011); the statement does not move the cursor. Values use472the unit and range of the target. The curve describes the segment that ends at the point:473`linear` (default), `step` (hold the previous value) or `exp`. A parameter must be declared474automatable by the registry (T3014).475476### 8.5 Master477478`sample_rate` is one of 44 100, 48 000, 88 200, 96 000, 176 400, 192 000 Hz (default 48 000).479`peak_limit` is the ceiling of the safety limiter in dBFS, within [-60, 0] (default −1 dB);480`peak_limit off` removes the limiter, for measurements and scientific exports. No loudness481normalisation is ever applied implicitly.482483### 8.6 The mixing graph484485For one sample rate the compiler derives the DSP IR:486487* track: source → inserts → fader → output; sends tap before the fader (`pre`) or after it;488* bus: sum of what it receives → inserts → fader → output; a bus that receives nothing is not489 built;490* master: sum → inserts → fader → limiter (unless `peak_limit off`) → output.491492Bus routing must be acyclic (G5001). Where parallel paths meet at a sum, the compiler inserts493pure delays so that all inputs carry the same latency, and reports the total latency of the494graph. Node identifiers follow declaration order: the same Program gives the same graph.495496`mute` silences a strip entirely, its sends included; with at least one `solo`, tracks that are497not soloed are silent. For offline bounces the compiler can prune silent strips from the graph498(`GraphOptions::prune_silent`); for live playback they stay, so the mixer can un-mute without a499new graph.500501## 9. DSP graphs502503An instrument with `model patch` is a per-voice signal graph.504505```sonata506instrument GlassLead {507 model patch508 graph {509 node osc = saw(freq: note.freq)510 node env = adsr(attack: 8ms, decay: 250ms, sustain: 0.6, release: 400ms)511 node tone = lowpass(in: osc, cutoff: 400Hz + env * 2400, q: 2)512 node echo = delay(in: mixed, time: 11ms)513 node mixed = tone + echo * 0.35514 out mixed * env * note.velocity515 }516}517518composition "Patch" {519 instrument lead: GlassLead { play A3 duration 1/2 }520}521```522523* `node name = expression` names a signal; `out expression` is the output of the voice. A524 graph has exactly one `out`.525* A call to a registry **patch node** (`sine`, `saw`, `adsr`, `lowpass`, `delay`, `modal`, …)526 creates a node. Ports are given by name or in the registry order; a port that is not given527 takes its default.528* `note.freq`, `note.pitch`, `note.velocity`, `note.gate` and `note.time` are the per-note529 inputs.530* `+`, `-`, `*` between signals create arithmetic nodes; `/` is allowed by a constant only.531 Sub-expressions that involve no signal are evaluated at compile time with the full unit532 algebra and folded into constants; next to a signal a value is its canonical number533 (Hz, seconds, semitones, dB).534* Signals are **typed by rate**: audio (`Signal`, one value per sample) or control535 (`ControlSignal`, one value per control block), as declared by the registry; arithmetic is536 audio rate as soon as one operand is. The output must be audio rate (G5007).537* **Causality.** A node may only read nodes defined before it. The single exception is the538 `in` port of `delay`, which may read a later node: a feedback loop is only causal through a539 delay. Anything else is G5002.540* An envelope multiplied into the output is the amplitude envelope: the voice ends when it541 reaches zero after note-off.542* A node that does not reach the output is not part of the instrument (warning G5011 when it543 has a name): it costs nothing at run time and cannot change the sound.544545## 10. Built-in functions546547Generated from the compiler's own table (`sonata_semantics::builtins::BUILTINS`):548549| Function | Result |550|---|---|551| `len(xs)`, `sum(xs)`, `contains(xs, x)` | size, sum, membership |552| `reverse(xs)`, `rotate(xs, n)`, `take(xs, n)`, `drop(xs, n)`, `cycle(xs, n)`, `concat(a, b)` | lists |553| `min(a, b, …)`, `max(a, b, …)`, `clamp(x, lo, hi)`, `abs(x)` | same type as the arguments |554| `floor(x)`, `ceil(x)`, `round(x)`, `sqrt(x)`, `pow(a, b)`, `sin(x)`, `cos(x)`, `exp(x)`, `ln(x)`, `lerp(a, b, t)` | numbers (angles in radians) |555| `random()`, `random_int(lo, hi)`, `choose(xs)`, `shuffle(xs)` | seeded randomness |556| `note_value(f)`, `dotted(d)`, `triplet(d)` | durations: `f` of a whole note, `d × 3/2`, `d × 2/3` |557| `seconds(d)`, `beats(d)` | conversions of a duration |558| `hz(p)`, `midi(n)`, `pitch_number(p)`, `octave(p)`, `pitch_class(p)`, `interval(a, b)` | pitches |559| `db(x)`, `linear(g)` | level conversions |560| `scale(root, mode)` | the pitches of one octave of a scale, without the octave |561| `chord(root, quality)` | `major minor maj min dim aug maj7 min7 dom7 dim7 min7b5 sus2 sus4 add9 maj9 min9 power` |562| `transpose(x, interval)`, `invert(chord, n)` | pitch transforms |563| `degree(n, octave = 4)` | n-th degree of the composition key (needs `key`) |564| `euclid(hits, steps)` | Euclidean rhythm as a list of `Bool` |565| `str(x)` | text of a value |566567Constants: `pi`, `tau`, `on`, `off`, and the mode and chord-quality names. `hz(p)` and `p.hz`568assume A4 = 440 Hz; the composition `tuning` is applied by the runtime to sounding notes.569570## 11. Limits571572| Limit | Default | Code |573|---|---|---|574| Source size | 4 MiB | L0007 |575| Nesting of blocks and expressions in source | 96 | P1004 |576| Notes | 1 000 000 | Q6001 |577| Evaluation steps | 10 000 000 | Q6002 |578| Call depth; combined run-time nesting | 64; 4 096 | Q6003 |579| List length | 100 000 | Q6004 |580| Tracks | 256 | Q6006 |581| Nodes per patch | 4 096 | Q6007 |582| Import depth | 16 | I7003 |583| Diagnostics before analysis stops | 200 | Q6008 |584585The quotas are options of the compiler (`CompileOptions::quotas`). Exceeding one stops the586compilation with a located error; it never hangs or exhausts memory silently.587588## 12. Formatting589590`sonata fmt` prints the canonical form: four spaces per level, one statement per line, one591blank line kept where there were several, comments preserved, `1/4` without spaces between592integers. It is idempotent, changes no meaning (the tests compare the programs), and refuses593to rewrite a file that does not parse.594595## 13. What 0.1 does not have596597Stated so that nothing is assumed: no user-defined types or records; no first-class functions;598no string formatting beyond `str` and `+`; no `while`; no static type inference beyond599section 3.3; no tempo-following effect times; no per-note parameter automation other than600`bend`; no polyphonic pitch bend per note beyond `bend`; no multichannel beyond stereo; no601user-defined effects (effects come from the registry; instruments can be built with `graph`).602