Repository Public
1<!--2ORIX Sonata3File: Documentation/adr/0002-language-design.md4Author: Simon-Pierre Boucher5Contact: contact@spboucher.ai6-->7# ADR 0002 — Sonata language 0.1: binding design decisions89Status: accepted (2026-11-24). The normative text is `Documentation/spec/sonata-language.md`10and `Documentation/spec/grammar.ebnf`; they must agree with this record and with the parser.1112## Lexical1314- UTF-8 source, at most 4 MiB. Comments `// …` and nestable `/* … */`.15- Strings `"…"` with escapes `\n \t \" \\ \u{HEX}`.16- Numbers: integers and decimals. A unit suffix is glued to the number:17 `bpm`, `Hz`, `kHz`, `dB`, `ms`, `s`, `st`, `cents`, `%`, `bars`/`bar`, `beats`/`beat`, `deg`.18 Integers are exact; `1/4` is an exact rational (integer division yields a rational, never truncates).19- Note literals: `[A-G]`, optional accidental `#`, `##`, `b`, `bb`, octave `-1..9` (`C4` = MIDI 60,20 `A4` = MIDI 69). Pitch-class literals (no octave): `C D E F G A B` with optional `#`/`b`.21 Tokens of these shapes are always literals and can never be identifiers.22 Microtones are arithmetic: `A4 + 25cents`.23- Statements are separated by newlines or `;`. A newline ends an expression unless the line ends24 with a binary operator, `,` or an open bracket; `-`, `(` and `[` at the start of a line never25 continue the previous expression.26- Keywords are reserved (list in the spec).2728## Types and units2930`Number` (exact rational or float), `Bool`, `String`, `Pitch`, `Interval` (semitones),31`Duration` (musical, exact rational of a whole note), `Time` (seconds), `Frequency` (Hz),32`Gain` (dB), `Tempo`, `TimeSignature`, `Velocity`, `Pan`, `List<T>`, `Chord` (= `List<Pitch>`),33`Scale`, `Pattern`, `Sequence`, `Instrument`, `Bus`, `AudioBuffer`, `Signal`, `ControlSignal`,34`Note`, `Beat`, `Bar`.3536- In a duration position a bare number is a **fraction of a whole note**: `1/4` = quarter note37 = 1 beat in 4/4. `2bars` and `3beats` are durations resolved with the signature in effect38 (a beat is `1/denominator`). `dotted(d)` = d·3/2, `triplet(d)` = d·2/3.39- Seconds (`Time`), musical durations (`Duration`) and sample counts are distinct types;40 mixing them is error T3xxx. Conversions are explicit: `seconds(d)`, `beats(d)`, `hz(p)`,41 `db(x)`, `linear(g)`.42- Unit algebra: `Duration ± Duration`, `Duration × Number`, `Pitch ± Interval → Pitch`,43 `Pitch − Pitch → Interval`, `Gain ± Gain`, `Frequency × Number`, `Time × Number`.44 Anything else is a type error with a suggestion.45- Musical time is exact (`Rational`, checked `i64`); overflow is error Q6xxx, never a wrap.46- Seconds come from the tempo map; samples from `floor(seconds × rate + 0.5)` (`sonata_ir::time`).4748## Program structure4950Top level: `import a.b`, `const`, `let`, `fn`, `pattern`, `instrument` definitions, `composition`.51A file without a composition is a module. Imports: `std.*` is embedded in the compiler52(`StandardLibrary/std/*.sonata`); other paths resolve relative to the project root through a53`SourceLoader`. No file, network or shell access exists in the language. Import cycles are54error I7xxx. Everything top-level in an imported module is visible unqualified; a clash is an error.5556`composition "Title" { … }` contains settings (`tempo`, `key`, `signature`, `seed`, `swing`,57`tuning`), tracks (`instrument name: Type { … }`, `audio name { clip "x.wav" at 0bars }`),58`bus name { … }`, `master { … }`, `marker "A" at 4bars`, `let`/`const`.5960A track body has a **cursor** starting at 0. Statements:6162| Statement | Effect |63|---|---|64| `play P [duration d] [velocity v] [articulation] [tie] [bend …]` | note (or chord if `P` is a list) at the cursor; cursor advances by `d` |65| `chord [..] …` | same as `play` with a list |66| `rest d` | advances the cursor |67| `sequence { }` | sequential group |68| `voice { }` / `parallel { }` | each block starts at the cursor on its own voice; the cursor advances by the longest |69| `at POS { }` | block placed at an absolute position; the cursor is restored after |70| `repeat N { }`, `for x in LIST { }`, `if c { } else { }` | bounded control flow |71| `tuplet N in M { }` | durations × M/N |72| `transpose I { }`, `swing R { }` | scoped transforms |73| `tempo T` / `tempo T ramp D` | tempo point at the cursor (ramp: linear over `D`) |74| `signature N/D` | only on a bar line |75| `name(args)` | calls a `pattern` at the cursor |76| `gain`, `pan`, `mute`, `solo`, `articulation`, `output`, `send`, `effects { }`, `automate … { }` | strip settings |7778Defaults: duration `1/4`, velocity `0.8`. Articulation rules (documented, the only places the79compiler changes what was written): staccato 50 % of the notated duration, staccatissimo 25 %,80marcato velocity × 1.2, accent velocity × 1.25 (clamped to 1), others 100 %.81Swing ratio `r` in [50 %, 75 %] on a unit `u` (default `1/8`): a note starting on an odd multiple82of `u` is delayed by `(2r − 1)·u`. Ties merge into one sounding note and keep the notated notes83for the score.8485`fn name(a: T, …) -> T { … }` are pure functions (`let`, assignment to locals, `if`, bounded86`for`, `return`). Recursion depth is limited to 64. `pattern name(a: T) { track statements }`.87Randomness only through the seeded generator (`random()`, `random_int(a, b)`, `choose(xs)`,88`shuffle(xs)`); the stream is SplitMix64 seeded by `seed` and the track id, so a compilation is89reproducible.9091Instrument definitions: `instrument Name [: Base] { model m; preset p; <param> <value>;92<slot> <kind>(args); graph { node x = kind(port: expr, …) … out expr } }`. Slots and parameters93are validated against the registry (`sonata_ir::Registry`) with their units and ranges.94`graph` compiles to a `PatchSpec`; a loop without a `delay` node is error G5xxx.9596Effects: `effects { [bypass] kind [preset] [(name: value, …)] }`, validated against the registry.97A `Duration` given to a `Seconds` parameter is resolved at the tempo in effect at position 098(tempo-synced values do not follow later tempo changes in 0.1; documented limitation).99100## Quotas (defaults, configurable through `CompileOptions`)1011021 000 000 note events, 10 000 000 evaluation steps, recursion depth 64, list length 100 000,103import depth 16, 256 tracks, 4 096 nodes per patch, source 4 MiB. Exceeding one is error Q6xxx104at the statement that crossed the limit; compilation stops cleanly.105106## Versioning107108`LANGUAGE_VERSION = "0.1"`. A file may start with `sonata 0.1`. A newer minor than the109toolchain is error I7xxx; migrations are described in `Documentation/spec/compatibility.md`.110The formatter is canonical and idempotent (`fmt(fmt(x)) == fmt(x)`), 4 spaces, one statement per line.111112## Amendments made while implementing (2026-11-24)113114The frontend was built against this record. Where the implementation had to choose or to115differ, the choice is recorded here and specified in `Documentation/spec/sonata-language.md`.1161171. **Prelude.** `std.music`, `std.instruments` and `std.effects` are always in scope. The118 mandate's Aurora listing uses `GrandPiano` and `ConcertStrings` while importing only119 `std.music` and `std.effects`; it must compile unchanged, so explicit imports of the three120 modules are allowed and redundant. A project definition shadows a standard one silently, so121 the standard library can grow without breaking projects.1222. **Ties.** A tied chain is a single `NoteEvent` whose notated and sounding durations are the123 sums. `NoteEvent::tied_from_previous` is never set by the compiler: emitting the notated124 segments as separate events would have required every audio consumer to skip them. Score125 export splits long notes at bar lines itself.1263. **`note_value(f)`.** A bare fraction is a duration only in a duration position. A *time*127 parameter (`delay(time: …)`, `envelope.release …`) accepts a `Time` or a `Duration`, not a128 bare number: `time: 1/8` could mean an eighth note or an eighth of a second. `note_value(1/8)`129 and the standard constants (`eighth`, …) make durations explicitly.1304. **Calls named like keywords.** `chord(root, quality)` (built-in function) and `clip(in: …)`131 (patch node) are accepted in expression position although `chord` and `clip` are reserved.132 Reserved words are also accepted as argument labels (`lowpass(in: x)`).1335. **Type checking is evaluation-time.** Names, kinds and arity are resolved statically in134 every file; types and units are checked when an expression is evaluated. Because a135 composition is evaluated completely at compile time, everything that contributes to the136 music is checked; untaken branches and uncalled functions get names and arity only. A full137 static type inference is deferred (roadmap), the diagnostics codes are already separated138 (S2xxx static, T3xxx evaluation).1396. **Order of evaluation.** Settings, buses, master, markers and variables of a composition are140 evaluated before its tracks, whatever their position in the source; tracks follow in141 declaration order. `tempo` and `signature` may also appear in tracks, at the cursor.1427. **Voices.** Adjacent `voice { }` blocks form one simultaneous group; `parallel { }` starts143 each of its direct statements at the cursor.1448. **Swing** delays the off-beat note and shortens it by the same amount, so it never overlaps145 the next note.1469. **Automation** positions are relative to the cursor of the `automate` statement; an effect147 must be declared above the statement that automates it. `mix` of any effect is automatable148 as `EFFECT.mix` (target `Effect { index, param: "mix" }`).14910. **Top-level `let`** is a constant (evaluated lazily, once). Mutable variables exist in150 blocks only.15111. **Float × Duration** is approximated by a fraction with denominator ≤ 40 320 (documented);152 floats are refused where a duration is written directly.15312. **Mute and solo in the graph.** `mute` silences a strip including its sends; pruning of154 silent strips is an option of the graph builder (offline bounce), off by default so the155 live mixer can un-mute without a new graph.15613. **Formatter.** One statement per line is enforced, so `master { a; b }` is expanded.15714. **Stack.** Parsing and analysis run on a dedicated thread with a large reserved stack, and158 the evaluator bounds its combined nesting (4 096), so a compilation is safe from any159 caller thread. `SourceLoader` is therefore `Sync`.16015. **Quota added:** 200 diagnostics (Q6008). **Not in 0.1:** `sonata fmt --migrate` (nothing to161 migrate yet).162