SPB Git

Repository Public

0002-language-design.md 10.2 KB

# ADR 0002 — Sonata language 0.1: binding design decisions

Status: accepted (2026-11-24). The normative text is Documentation/spec/sonata-language.md and Documentation/spec/grammar.ebnf; they must agree with this record and with the parser.

# Lexical

  • UTF-8 source, at most 4 MiB. Comments // … and nestable /* … */.
  • Strings "…" with escapes \n \t \" \\ \u{HEX}.
  • Numbers: integers and decimals. A unit suffix is glued to the number: bpm, Hz, kHz, dB, ms, s, st, cents, %, bars/bar, beats/beat, deg. Integers are exact; 1/4 is an exact rational (integer division yields a rational, never truncates).
  • Note literals: [A-G], optional accidental #, ##, b, bb, octave -1..9 (C4 = MIDI 60, A4 = MIDI 69). Pitch-class literals (no octave): C D E F G A B with optional #/b. Tokens of these shapes are always literals and can never be identifiers. Microtones are arithmetic: A4 + 25cents.
  • Statements are separated by newlines or ;. A newline ends an expression unless the line ends with a binary operator, , or an open bracket; -, ( and [ at the start of a line never continue the previous expression.
  • Keywords are reserved (list in the spec).

# Types and units

Number (exact rational or float), Bool, String, Pitch, Interval (semitones), Duration (musical, exact rational of a whole note), Time (seconds), Frequency (Hz), Gain (dB), Tempo, TimeSignature, Velocity, Pan, List<T>, Chord (= List<Pitch>), Scale, Pattern, Sequence, Instrument, Bus, AudioBuffer, Signal, ControlSignal, Note, Beat, Bar.

  • In a duration position a bare number is a fraction of a whole note: 1/4 = quarter note = 1 beat in 4/4. 2bars and 3beats are durations resolved with the signature in effect (a beat is 1/denominator). dotted(d) = d·3/2, triplet(d) = d·2/3.
  • Seconds (Time), musical durations (Duration) and sample counts are distinct types; mixing them is error T3xxx. Conversions are explicit: seconds(d), beats(d), hz(p), db(x), linear(g).
  • Unit algebra: Duration ± Duration, Duration × Number, Pitch ± Interval → Pitch, Pitch − Pitch → Interval, Gain ± Gain, Frequency × Number, Time × Number. Anything else is a type error with a suggestion.
  • Musical time is exact (Rational, checked i64); overflow is error Q6xxx, never a wrap.
  • Seconds come from the tempo map; samples from floor(seconds × rate + 0.5) (sonata_ir::time).

# Program structure

Top level: import a.b, const, let, fn, pattern, instrument definitions, composition. A file without a composition is a module. Imports: std.* is embedded in the compiler (StandardLibrary/std/*.sonata); other paths resolve relative to the project root through a SourceLoader. No file, network or shell access exists in the language. Import cycles are error I7xxx. Everything top-level in an imported module is visible unqualified; a clash is an error.

composition "Title" { … } contains settings (tempo, key, signature, seed, swing, tuning), tracks (instrument name: Type { … }, audio name { clip "x.wav" at 0bars }), bus name { … }, master { … }, marker "A" at 4bars, let/const.

A track body has a cursor starting at 0. Statements:

Statement Effect
play P [duration d] [velocity v] [articulation] [tie] [bend …] note (or chord if P is a list) at the cursor; cursor advances by d
chord [..] … same as play with a list
rest d advances the cursor
sequence { } sequential group
voice { } / parallel { } each block starts at the cursor on its own voice; the cursor advances by the longest
at POS { } block placed at an absolute position; the cursor is restored after
repeat N { }, for x in LIST { }, if c { } else { } bounded control flow
tuplet N in M { } durations × M/N
transpose I { }, swing R { } scoped transforms
tempo T / tempo T ramp D tempo point at the cursor (ramp: linear over D)
signature N/D only on a bar line
name(args) calls a pattern at the cursor
gain, pan, mute, solo, articulation, output, send, effects { }, automate … { } strip settings

Defaults: duration 1/4, velocity 0.8. Articulation rules (documented, the only places the compiler changes what was written): staccato 50 % of the notated duration, staccatissimo 25 %, marcato velocity × 1.2, accent velocity × 1.25 (clamped to 1), others 100 %. Swing ratio r in [50 %, 75 %] on a unit u (default 1/8): a note starting on an odd multiple of u is delayed by (2r − 1)·u. Ties merge into one sounding note and keep the notated notes for the score.

fn name(a: T, …) -> T { … } are pure functions (let, assignment to locals, if, bounded for, return). Recursion depth is limited to 64. pattern name(a: T) { track statements }. Randomness only through the seeded generator (random(), random_int(a, b), choose(xs), shuffle(xs)); the stream is SplitMix64 seeded by seed and the track id, so a compilation is reproducible.

Instrument definitions: instrument Name [: Base] { model m; preset p; <param> <value>; <slot> <kind>(args); graph { node x = kind(port: expr, …) … out expr } }. Slots and parameters are validated against the registry (sonata_ir::Registry) with their units and ranges. graph compiles to a PatchSpec; a loop without a delay node is error G5xxx.

Effects: effects { [bypass] kind [preset] [(name: value, …)] }, validated against the registry. A Duration given to a Seconds parameter is resolved at the tempo in effect at position 0 (tempo-synced values do not follow later tempo changes in 0.1; documented limitation).

# Quotas (defaults, configurable through CompileOptions)

1 000 000 note events, 10 000 000 evaluation steps, recursion depth 64, list length 100 000, import depth 16, 256 tracks, 4 096 nodes per patch, source 4 MiB. Exceeding one is error Q6xxx at the statement that crossed the limit; compilation stops cleanly.

# Versioning

LANGUAGE_VERSION = "0.1". A file may start with sonata 0.1. A newer minor than the toolchain is error I7xxx; migrations are described in Documentation/spec/compatibility.md. The formatter is canonical and idempotent (fmt(fmt(x)) == fmt(x)), 4 spaces, one statement per line.

# Amendments made while implementing (2026-11-24)

The frontend was built against this record. Where the implementation had to choose or to differ, the choice is recorded here and specified in Documentation/spec/sonata-language.md.

  1. Prelude. std.music, std.instruments and std.effects are always in scope. The mandate's Aurora listing uses GrandPiano and ConcertStrings while importing only std.music and std.effects; it must compile unchanged, so explicit imports of the three modules are allowed and redundant. A project definition shadows a standard one silently, so the standard library can grow without breaking projects.
  2. Ties. A tied chain is a single NoteEvent whose notated and sounding durations are the sums. NoteEvent::tied_from_previous is never set by the compiler: emitting the notated segments as separate events would have required every audio consumer to skip them. Score export splits long notes at bar lines itself.
  3. note_value(f). A bare fraction is a duration only in a duration position. A time parameter (delay(time: …), envelope.release …) accepts a Time or a Duration, not a bare number: time: 1/8 could mean an eighth note or an eighth of a second. note_value(1/8) and the standard constants (eighth, …) make durations explicitly.
  4. Calls named like keywords. chord(root, quality) (built-in function) and clip(in: …) (patch node) are accepted in expression position although chord and clip are reserved. Reserved words are also accepted as argument labels (lowpass(in: x)).
  5. Type checking is evaluation-time. Names, kinds and arity are resolved statically in every file; types and units are checked when an expression is evaluated. Because a composition is evaluated completely at compile time, everything that contributes to the music is checked; untaken branches and uncalled functions get names and arity only. A full static type inference is deferred (roadmap), the diagnostics codes are already separated (S2xxx static, T3xxx evaluation).
  6. Order of evaluation. Settings, buses, master, markers and variables of a composition are evaluated before its tracks, whatever their position in the source; tracks follow in declaration order. tempo and signature may also appear in tracks, at the cursor.
  7. Voices. Adjacent voice { } blocks form one simultaneous group; parallel { } starts each of its direct statements at the cursor.
  8. Swing delays the off-beat note and shortens it by the same amount, so it never overlaps the next note.
  9. Automation positions are relative to the cursor of the automate statement; an effect must be declared above the statement that automates it. mix of any effect is automatable as EFFECT.mix (target Effect { index, param: "mix" }).
  10. Top-level let is a constant (evaluated lazily, once). Mutable variables exist in blocks only.
  11. Float × Duration is approximated by a fraction with denominator ≤ 40 320 (documented); floats are refused where a duration is written directly.
  12. Mute and solo in the graph. mute silences a strip including its sends; pruning of silent strips is an option of the graph builder (offline bounce), off by default so the live mixer can un-mute without a new graph.
  13. Formatter. One statement per line is enforced, so master { a; b } is expanded.
  14. Stack. Parsing and analysis run on a dedicated thread with a large reserved stack, and the evaluator bounds its combined nesting (4 096), so a compilation is safe from any caller thread. SourceLoader is therefore Sync.
  15. Quota added: 200 diagnostics (Q6008). Not in 0.1: sonata fmt --migrate (nothing to migrate yet).
Files main
Menu

Theme