SPB Git

Repository Public

sonata-language.md 27.5 KB

# The Sonata language — version 0.1 (normative)

Sonata describes music as a program. A source file is compiled to a Musical IR (timestamped notes, tempo map, automation, routing) and an Audio DSP IR (the mixing graph), which the runtime turns into sound. This document defines what a program means. The grammar is in grammar.ebnf, the diagnostics in diagnostics.md, the versioning rules in compatibility.md.

Every block marked sonata in this document is a complete program that the test suite compiles (crates/sonata-compiler/tests/spec.rs). Blocks marked text are fragments.

Words used: must is a rule the compiler enforces with an error; is defines behaviour.

# 1. A first program

sonata
composition "Aurora" {
    tempo 120bpm
    key D minor
    signature 4/4
    seed 42
    instrument piano: GrandPiano {
        gain -8dB
        sequence {
            chord [D3, A3, D4] duration 1/2
            chord [F3, A3, C4] duration 1/2
            rest 1/4
            play A4 duration 1/4 velocity 0.75
        }
        effects { reverb hall(mix: 0.2) }
    }
    instrument strings: ConcertStrings {
        articulation legato
        play D4 duration 1/1
    }
    master { sample_rate 48000Hz; peak_limit -1dB }
}

A file holds top-level items (imports, constants, functions, patterns, instrument definitions) and compositions. A file without a composition is a module. The compiler compiles the first composition of the root file, or the one whose title is requested.

# 2. Lexical structure

  • Source is UTF-8, at most 4 MiB. Line comments // …; block comments /* … */ nest.
  • Strings are written on one line between double quotes, with the escapes \n, \t, \", \\ and \u{HEX} (1 to 6 hexadecimal digits).
  • Numbers are integers (42, 48_000) or decimals (0.75). Integers are exact. A unit is glued to the number: 120bpm, 440Hz, 2kHz, -8dB (the minus is an operator), 5ms, 2s, 7st, 25cents, 60%, 3bars, 1beat, 90deg.
  • Note literals are a letter A–G, an optional accidental (#, ##, b, bb) and an octave from -1 to 9: C4 is MIDI 60, A4 is MIDI 69, C-1 is MIDI 0. Pitch-class literals have no octave: D, F#, Bb. A token of either shape is always a literal and can never be a name: A4, Bb and C are not identifiers; a4, Amp, Cmaj are.
  • Identifiers are ASCII letters, digits and _, not starting with a digit. The reserved words are listed in the grammar. A reserved word may still be used as an argument label (lowpass(in: x)), and chord(…) and clip(…) written as calls are the built-in function and the patch node.
  • Lines. Statements are separated by a line break or ;. An expression continues on the next line only if the current line ends with an operator, a comma or an open bracket. A line that starts with -, (, [ or any operator starts a new statement.

# 3. Values, types and units

Type Literal or source Canonical unit
Number 3, 1/4, 0.75, 60% exact rational when written with integers, float otherwise
Bool true, false, on, off
String "text", mode and chord names (minor, maj7)
Pitch (Note) D4, midi(62) MIDI number, fractional for microtones
PitchClass D, Bb used by key
Interval 7st, 25cents semitones
Duration (Beat, Bar) 2bars, 1beat, note_value(1/8) exact rational of a whole note
Time 5ms, 2s seconds
Frequency 440Hz, 2kHz hertz
Gain -6dB decibels
Tempo 120bpm quarter notes per minute
Angle 90deg degrees
Velocity a Number in [0, 1] linear
Pan a Number in [-1, 1] -1 left, 1 right
List<T>, Chord, Scale [D3, A3, D4], 0..4 Chord and Scale are List<Pitch>

TimeSignature, Pattern, Sequence, Instrument, Bus, AudioBuffer, Signal and ControlSignal name things of the language but are not value types in 0.1: using one in an annotation is error T3010. Signals exist inside graph blocks (section 9).

# 3.1 Three kinds of time

Musical durations (Duration), seconds (Time) and sample counts are distinct and never mix implicitly; 1s + 1/4 is error T3001.

  • In a duration position (after duration, rest, at, in automation positions, …) a bare exact number is a fraction of a whole note: 1/4 is a quarter note, which is one beat in 4/4. Floats are refused there (T3003): musical time is exact.
  • 2bars and 3beats are durations resolved with the signature in effect at the cursor: a beat is 1/denominator of a whole note, a bar is numerator/denominator.
  • note_value(1/8) makes a Duration from a fraction where no duration is expected, for example for a tempo-synced effect time. The standard constants whole, half, quarter, eighth, sixteenth are durations.
  • Conversions are explicit: seconds(d) (at the tempo in effect at position 0), beats(d), hz(p), db(x), linear(g).

Musical positions and durations are exact rationals with 64-bit numerator and denominator. Overflow is error Q6005; nothing wraps. Seconds are derived from the tempo map (section 6.3) as 64-bit floats, and a sample index is floor(seconds × rate + 0.5). This single rule is sonata_ir::time::seconds_to_samples; the offline renderer, the real-time engine and the studio rulers all use it.

# 3.2 Operators

Expression Result
Number ± × ÷ % Number Number; exact while both are exact (1/4 is one quarter, never 0)
Duration ± Duration, Duration ± exact Number Duration
Duration × Number, Duration ÷ Number Duration (a float factor is approximated by a fraction with denominator ≤ 40 320)
Duration ÷ Duration Number
Pitch ± Interval Pitch — microtones are arithmetic: A4 + 25cents
Pitch − Pitch Interval
List<Pitch> ± Interval every pitch moves
Interval ± Interval, Interval × Number, Interval ÷ Interval Interval, Interval, Number
Gain ± Gain Gain
Frequency, Time, Tempo: ± same, × ÷ Number, ÷ same same type, same type, Number
String + String, List + List concatenation
== != < <= > >= Bool; both sides of the same kind
and, or, not Bool; and and or evaluate their right side only if needed
a..b, a..=b list of integers, end excluded or included
xs[i] element; negative indices count from the end; out of range is T3008
xs.len, xs.first, xs.last, p.midi, p.octave, p.class, p.hz members
if c then a else b conditional expression

Anything else is a type error that names both types and, where one exists, the conversion to use. Division by zero is T3007. An exact Number that would overflow becomes a float; a Duration that would overflow is Q6005.

Precedence, lowest first: or, and, not, comparisons, ranges, + -, * / %, unary - and + (a leading plus has no effect: gain +4dB), then indexing, member access and calls. Binary operators associate to the left.

# 3.3 Type checking

Names, kinds (function, pattern, instrument, value) and argument counts are checked statically in every file, executed or not. Types and units are checked when an expression is evaluated, with the exact source span; an annotation (let x: Pitch = …, parameters, return types) is checked at that point too and applies one coercion: an exact number becomes a Duration. A composition is evaluated completely at compile time, so every statement that contributes to the music is checked; a branch that is never taken, or a function that is never called, is checked for names and arity only.

# 4. Names, modules and scope

sonata
import std.music

const root = D3
let motif = [root, root + 7st, root + 12st]

fn double(d: Duration) -> Duration {
    return d * 2
}

pattern there_and_back(notes: List<Pitch>, step: Duration = 1/8) {
    for n in notes + reverse(notes) {
        play n duration step
    }
}

composition "Scopes" {
    let step = 1/16
    instrument a: Harp {
        let local = double(step)
        there_and_back(motif, step: local)
    }
}
  • Top-level const and let are both constants, evaluated on first use; one that depends on itself is S2006. Inside blocks, let declares a variable that can be reassigned (x = x + 1), const one that cannot. A block opens a scope.
  • A composition's own lets are visible in its tracks. Functions and patterns see only their parameters and top-level definitions.
  • Imports. import a.b loads a module. std.* modules are embedded in the compiler. Any other path is given by the host through a SourceLoader; the command line and the app map a.b to <project root>/a/b.sonata, refuse anything that resolves outside the root (after following symbolic links) and files over 4 MiB. The language has no other access to files, and none to the network or to processes.
  • Everything top-level of an imported module is visible unqualified. Two project definitions of the same name are S2002; a project definition silently shadows a standard one. Import cycles are I7002, a missing module I7001, more than 16 nested imports I7003.
  • Prelude. std.music, std.instruments and std.effects are always in scope; importing them explicitly is allowed and has no effect.

# 4.1 Functions

fn name(a: T, b: T = default) -> T { … } is a pure function: its body may contain let, assignment, if, for, repeat, return and calls, and nothing that produces music. Arguments are positional, then named (f(1, b: 2)). Call depth is limited to 64 (Q6003).

# 4.2 Patterns

pattern name(params) { track statements } is a reusable piece of a track. Calling it as a statement runs its body at the caller's cursor and advances it. Scoped transforms set inside a pattern (transpose, swing) do not leak out.

# 4.3 Randomness

random(), random_int(a, b), choose(xs) and shuffle(xs) draw from a SplitMix64 stream selected by seed (default 0). Each track has its own stream, derived from the seed and the track's declaration order; code outside tracks uses a separate stream. The same source and seed always give the same Program.

# 5. Compositions

composition "Title" { … } contains, in any order:

Statement Meaning
tempo 120bpm tempo at position 0 (default 120)
key D minor key; modes: major minor dorian phrygian lydian mixolydian locrian harmonic_minor melodic_minor pentatonic_major pentatonic_minor blues whole_tone chromatic
signature 4/4 signature at position 0 (default 4/4)
seed 42 random seed (default 0)
swing 60% / swing 60% of 1/16 default swing of every track (section 6.5)
tuning 442Hz frequency of A4, 220–880 Hz (default 440)
instrument name: Type { … } an instrument track (section 6)
audio name { clip "file.wav" at 0bars } an audio track (section 8.3)
bus name { … }, master { … } mixer strips (section 8)
marker "A" at 4bars a named position
at POSITION { tempo …; signature …; marker … } the same statements at another position
let, const variables visible in the tracks

Whatever their order in the source, the settings, buses, master and variables of a composition are evaluated before its tracks, so every track sees the same tempo, signatures, key and swing. Tracks are then evaluated in declaration order.

# 6. Tracks: the cursor model

A track body is executed once, at compile time. It has a cursor, a musical position that starts at 0. Statements place events at the cursor and move it.

sonata
composition "Cursor" {
    tempo 96bpm
    signature 3/4
    instrument flute: Flute {
        default duration 1/8
        play D5 duration 1/4            // cursor: 0 → 1/4
        play [F5, A5] duration 1/4      // a chord: both notes at 1/4
        rest 1beat                      // cursor: 1/2 → 3/4, one full bar
        repeat 2 {
            play A5
            play F5 staccato
        }
        at 4bars {
            play D6 duration 1bar       // placed at bar 5; the cursor does not move
        }
        tuplet 3 in 2 {
            for n in [D5, E5, F5] {
                play n duration 1/4     // three quarters in the time of two
            }
        }
    }
}

# 6.1 Notes

play PITCH {modifier} places a note; play LIST and chord LIST place the notes of a list together. chord requires a list. The cursor advances by the duration.

Modifier Meaning Default
duration D notated duration, must be positive default duration, initially 1/4
velocity V linear velocity in [0, 1] default velocity, initially 0.8
an articulation normal legato staccato staccatissimo tenuto marcato accent pizzicato tremolo the track's articulation, initially normal
tie ties this note to the next note of the same pitch in the same voice
bend { 0ms: 0st, 200ms: 2st } pitch curve relative to the note start, in time order, within ±48 st none

rest D moves the cursor by D (zero is allowed, negative is M4009).

Articulations are the only place where the compiler changes what was written, and exactly so:

Articulation Sounding duration Velocity
staccato 50 % of the notated duration unchanged
staccatissimo 25 % unchanged
marcato 100 % × 1.2, at most 1
accent 100 % × 1.25, at most 1
others 100 % unchanged

The cursor always advances by the notated duration. Every note keeps both its notated and its sounding start and duration in the IR; engines receive the articulation and may respond to it (a bowed string slurs legato, plucks pizzicato).

Ties. A note with tie and the next note of the same pitch in the same voice, starting exactly where it ends, are one sounding note whose duration is the sum; a chain may continue. The IR holds that single note (score export splits it at bar lines). A tie without continuation is warning M4005.

Range. A note outside the playable range of the instrument's engine is warning M4001 and is rendered anyway.

# 6.2 Structure

Statement Effect on the cursor
sequence { … } a group; statements run one after the other
voice { … } adjacent voice blocks start together, each on its own voice number; the cursor advances by the longest
parallel { … } every direct statement of the block starts at the cursor; the cursor advances by the longest
at POS { … } the block runs at absolute position POS; the cursor is unchanged afterwards
repeat N { … } N times; N is a non-negative integer
for x in LIST { … } once per element
if C { … } else if D { … } else { … } C must be a Bool
tuplet N in M { … } durations inside are multiplied by M/N (nested tuplets multiply)
transpose I { … } / transpose I pitches move by interval I in the block, or from here to the end of the enclosing block
swing R [of U] { … } / swing R [of U] swing in the block, or from here on
name(args) runs a pattern at the cursor

All loops are bounded by the evaluation-step quota (Q6002).

# 6.3 Tempo

tempo T sets the tempo at the cursor. tempo T ramp D moves the tempo linearly, in musical position, from the tempo in effect at the cursor to T over duration D. Tempo is always in quarter notes per minute, whatever the signature.

Seconds are the integral of the tempo map. A constant segment contributes length × 240 / bpm seconds per whole note of length; a ramp contributes the trapezoid of the linearly interpolated seconds-per-whole-note. Two different tempos set at the same position are M4004. Tempos outside [1, 1000] bpm are M4003.

Effect and instrument parameters that are times accept a musical duration and convert it at the tempo in effect at position 0; they do not follow later tempo changes in 0.1.

# 6.4 Signatures

signature N/D sets the signature at the cursor, which must be on a bar line of the signature it replaces (M4002). N is 1–64, D a power of two up to 64 (M4007). Signatures decide what bars and beats mean and how the score is barred; they do not change durations already written as fractions. Declare meter changes at composition level (at 4bars { signature 7/8 }) so every track counts bars the same way.

# 6.5 Swing

With ratio r in [50 %, 75 %] and unit u (default 1/8), a note whose notated start is an odd multiple of u starts (2r − 1) × u later, and ends where it would have ended (it is shortened by the same amount). 50 % is straight; 66.7 % is a triplet feel. Other notes are untouched.

# 7. Instruments

A track's type is an instrument definition, or directly the name of a registry engine.

sonata
instrument CrystalHarp {
    model plucked_string
    damping 0.015
    excitation pluck(position: 0.35)
    resonance modal(frequencies: [440Hz, 880Hz, 1320Hz])
    envelope adsr(attack: 5ms, decay: 300ms, sustain: 0.6, release: 2s)
}

instrument SoftHarp: CrystalHarp {
    damping 0.05
    brightness 0.3
}

composition "Instruments" {
    instrument a: CrystalHarp { play A4 }
    instrument b: SoftHarp { play A3 }
    instrument c: Marimba { play A2 }
}
  • model m selects a registry engine (piano, plucked_string, bowed_string, flute, clarinet, brass, organ, bass, synth, fm, kick, snare, hihat, modal_percussion, voice, patch). An instrument must have a model, its own or inherited.
  • preset p applies a preset of the engine; name value sets a parameter; members apply in order, so later lines override earlier ones.
  • slot kind(arg: value) sets the choice parameter slot to kind and the parameters slot.arg. envelope.attack 5ms is the same parameter written directly.
  • instrument B: A { … } inherits everything from A and then applies its own members; it cannot change the model (S2027).
  • Every name, unit and range is validated against the registry, the metadata the DSP crates publish (sonata_compiler::registry()). Units are checked dimensionally: a time parameter accepts 5ms or a musical duration, never a bare number (T3006); out of range is T3005. The parameter reference of the documentation is generated from the same metadata.
  • The standard library (std.instruments) defines the named instruments (GrandPiano, ConcertStrings, NylonGuitar, Marimba, …), each one an engine with one of its presets.

The models are approximations chosen for musical usefulness, not exact physical simulations; each engine documents its method and its domain of validity.

# 8. Mixing

# 8.1 Strips

Tracks, buses and the master are strips with the same statements:

Statement Tracks Buses Master
gain G — fader, [-120, 24] dB, default 0 dB yes yes yes
pan P — [-1, 1], constant-power law, −3 dB at the centre yes yes
mute, mute off yes yes
solo yes
effects { … } — insert chain, in order yes yes yes
send BUS [GAIN] [pre] — post-fader unless pre yes yes
output BUS — default master yes yes
automate TARGET { … } yes yes yes
sample_rate, peak_limit yes
sonata
composition "Mix" {
    tempo 110bpm
    bus hall {
        effects {
            reverb hall(mix: 100%)
        }
        gain -8dB
    }
    instrument keys: ElectricPiano {
        gain -9dB
        pan -0.2
        send hall -6dB
        effects {
            eq(low_cut: 80Hz)
            bypass chorus lush
            delay(time: note_value(3/16), feedback: 0.3, mix: 0.2)
        }
        chord [D3, F3, A3, C4] duration 2bars
        automate gain {
            0bars: -30dB
            1bar: -9dB exp
        }
        automate delay.feedback {
            0bars: 0.2
            2bars: 0.6
        }
    }
    master {
        sample_rate 48000Hz
        peak_limit -1dB
    }
}

# 8.2 Effects

An effect is [bypass] kind [preset] [(name: value, …)]. Arguments are named. mix is the dry/wet ratio in [0, 1] of every effect (its default comes from the registry); the runtime mixes the dry signal aligned with the effect's latency, and a bypassed effect keeps its latency, so bypassing never shifts a track.

# 8.3 Audio tracks

audio name { clip "path" at POS [offset T] [length T] [gain G] [fade_in T] [fade_out T] } places an audio file. The path is relative to the project's assets directory; absolute paths, .., backslashes and control characters are refused (I7005). The compiler does not open the file: the host supplies its samples to the runtime.

# 8.4 Automation

automate TARGET { POSITION: VALUE [curve], … } records a lane. Targets are gain, pan, instrument.PARAM and EFFECT.PARAM (EFFECT[1].PARAM for the second effect of that kind; the effect must be declared above). Positions are durations relative to the cursor of the statement, in non-decreasing order (M4011); the statement does not move the cursor. Values use the unit and range of the target. The curve describes the segment that ends at the point: linear (default), step (hold the previous value) or exp. A parameter must be declared automatable by the registry (T3014).

# 8.5 Master

sample_rate is one of 44 100, 48 000, 88 200, 96 000, 176 400, 192 000 Hz (default 48 000). peak_limit is the ceiling of the safety limiter in dBFS, within [-60, 0] (default −1 dB); peak_limit off removes the limiter, for measurements and scientific exports. No loudness normalisation is ever applied implicitly.

# 8.6 The mixing graph

For one sample rate the compiler derives the DSP IR:

  • track: source → inserts → fader → output; sends tap before the fader (pre) or after it;
  • bus: sum of what it receives → inserts → fader → output; a bus that receives nothing is not built;
  • master: sum → inserts → fader → limiter (unless peak_limit off) → output.

Bus routing must be acyclic (G5001). Where parallel paths meet at a sum, the compiler inserts pure delays so that all inputs carry the same latency, and reports the total latency of the graph. Node identifiers follow declaration order: the same Program gives the same graph.

mute silences a strip entirely, its sends included; with at least one solo, tracks that are not soloed are silent. For offline bounces the compiler can prune silent strips from the graph (GraphOptions::prune_silent); for live playback they stay, so the mixer can un-mute without a new graph.

# 9. DSP graphs

An instrument with model patch is a per-voice signal graph.

sonata
instrument GlassLead {
    model patch
    graph {
        node osc = saw(freq: note.freq)
        node env = adsr(attack: 8ms, decay: 250ms, sustain: 0.6, release: 400ms)
        node tone = lowpass(in: osc, cutoff: 400Hz + env * 2400, q: 2)
        node echo = delay(in: mixed, time: 11ms)
        node mixed = tone + echo * 0.35
        out mixed * env * note.velocity
    }
}

composition "Patch" {
    instrument lead: GlassLead { play A3 duration 1/2 }
}
  • node name = expression names a signal; out expression is the output of the voice. A graph has exactly one out.
  • A call to a registry patch node (sine, saw, adsr, lowpass, delay, modal, …) creates a node. Ports are given by name or in the registry order; a port that is not given takes its default.
  • note.freq, note.pitch, note.velocity, note.gate and note.time are the per-note inputs.
  • +, -, * between signals create arithmetic nodes; / is allowed by a constant only. Sub-expressions that involve no signal are evaluated at compile time with the full unit algebra and folded into constants; next to a signal a value is its canonical number (Hz, seconds, semitones, dB).
  • Signals are typed by rate: audio (Signal, one value per sample) or control (ControlSignal, one value per control block), as declared by the registry; arithmetic is audio rate as soon as one operand is. The output must be audio rate (G5007).
  • Causality. A node may only read nodes defined before it. The single exception is the in port of delay, which may read a later node: a feedback loop is only causal through a delay. Anything else is G5002.
  • An envelope multiplied into the output is the amplitude envelope: the voice ends when it reaches zero after note-off.
  • A node that does not reach the output is not part of the instrument (warning G5011 when it has a name): it costs nothing at run time and cannot change the sound.

# 10. Built-in functions

Generated from the compiler's own table (sonata_semantics::builtins::BUILTINS):

Function Result
len(xs), sum(xs), contains(xs, x) size, sum, membership
reverse(xs), rotate(xs, n), take(xs, n), drop(xs, n), cycle(xs, n), concat(a, b) lists
min(a, b, …), max(a, b, …), clamp(x, lo, hi), abs(x) same type as the arguments
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)
random(), random_int(lo, hi), choose(xs), shuffle(xs) seeded randomness
note_value(f), dotted(d), triplet(d) durations: f of a whole note, d × 3/2, d × 2/3
seconds(d), beats(d) conversions of a duration
hz(p), midi(n), pitch_number(p), octave(p), pitch_class(p), interval(a, b) pitches
db(x), linear(g) level conversions
scale(root, mode) the pitches of one octave of a scale, without the octave
chord(root, quality) major minor maj min dim aug maj7 min7 dom7 dim7 min7b5 sus2 sus4 add9 maj9 min9 power
transpose(x, interval), invert(chord, n) pitch transforms
degree(n, octave = 4) n-th degree of the composition key (needs key)
euclid(hits, steps) Euclidean rhythm as a list of Bool
str(x) text of a value

Constants: pi, tau, on, off, and the mode and chord-quality names. hz(p) and p.hz assume A4 = 440 Hz; the composition tuning is applied by the runtime to sounding notes.

# 11. Limits

Limit Default Code
Source size 4 MiB L0007
Nesting of blocks and expressions in source 96 P1004
Notes 1 000 000 Q6001
Evaluation steps 10 000 000 Q6002
Call depth; combined run-time nesting 64; 4 096 Q6003
List length 100 000 Q6004
Tracks 256 Q6006
Nodes per patch 4 096 Q6007
Import depth 16 I7003
Diagnostics before analysis stops 200 Q6008

The quotas are options of the compiler (CompileOptions::quotas). Exceeding one stops the compilation with a located error; it never hangs or exhausts memory silently.

# 12. Formatting

sonata fmt prints the canonical form: four spaces per level, one statement per line, one blank line kept where there were several, comments preserved, 1/4 without spaces between integers. It is idempotent, changes no meaning (the tests compare the programs), and refuses to rewrite a file that does not parse.

# 13. What 0.1 does not have

Stated so that nothing is assumed: no user-defined types or records; no first-class functions; no string formatting beyond str and +; no while; no static type inference beyond section 3.3; no tempo-following effect times; no per-note parameter automation other than bend; no polyphonic pitch bend per note beyond bend; no multichannel beyond stereo; no user-defined effects (effects come from the registry; instruments can be built with graph).

Files main
Menu

Theme