summaryrefslogtreecommitdiff
path: root/examples/live/src/Lang.zig
blob: 4ce504e5797469023838555b9ad997aff830d6b1 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
//! The language: lines of `name = expression` over `t`, `x` and `y`,
//! compiled into two tapes, `out` (heard, -1..1) and `color` (seen), that
//! one interpreter (shaders/vm.glsl) runs per sample and per pixel. Names
//! are shared by both lines; a name is defined once, before it is used, so
//! a program is a graph without cycles and every program ends.
//!
//!     beat = t * 2
//!     kick = exp(-7 * fract(beat))
//!     out = sin(tau * 48 * t) * kick   # heard
//!     color = hsv(x, 0.5, y * kick)    # seen
//!
//! `+ - * /`, unary `-` and parentheses; numbers like 0.5, 120, 1e-3;
//! `#` to the end of the line is a comment; the builtins are `builtins`.
//!
//! A tape is at most `max_tape` instructions, holding only what its line
//! reaches; instruction i writes register i from earlier ones. Its GPU
//! form is the uniform blocks at the end of this file, and build.zig
//! writes `Op` out as ops.glsl for the shaders: this file is the one
//! definition of both. `compile` allocates nothing: its work is a few
//! fixed arrays on the stack (`max_terms`, `max_names`, `max_depth`), and a
//! program past any of them is a problem like any other, in words.
const std = @import("std");

pub const max_tape = 128;
/// Numbers, names used and operations in the whole text.
pub const max_terms = 512;
/// Lines that define a name.
pub const max_names = 128;
/// Parentheses and unary minuses inside each other.
pub const max_depth = 32;
/// seq's index and values.
pub const max_args = 17;

/// By how many registers an instruction reads: none, one, two, three.
pub const Op = enum(u32) {
    /// `a` is the value's bits.
    constant,
    t,
    x,
    y,
    neg,
    sin,
    cos,
    exp,
    log,
    sqrt,
    abs,
    floor,
    fract,
    saw,
    sqr,
    tri,
    /// Register `a`, so that seq's values sit side by side.
    copy,
    /// Register `b + floor(a) mod c`: `b` and `c` are numbers, not
    /// registers it reads, and registers b.. hold the values.
    seq,
    add,
    sub,
    mul,
    div,
    pow,
    min,
    max,
    step,
    atan2,
    clamp,
    mix,
    smoothstep,
    noise,
    /// A colour, only as the color tape's last instruction.
    hsv,
    rgb,
};

pub const Builtin = struct {
    /// As it is called, for the manual.
    call: []const u8,
    op: Op,
    /// Arguments; 0 for an input or a constant, used without parentheses.
    min: u8 = 0,
    max: u8 = 0,
    value: f32 = 0,
    doc: []const u8,

    pub fn name(b: Builtin) []const u8 {
        return b.call[0 .. std.mem.indexOfScalar(u8, b.call, '(') orelse b.call.len];
    }
};

/// The builtins, the one table: a name is added here and in vm.glsl's
/// switch, and only for a program that needs it.
pub const builtins = [_]Builtin{
    .{ .call = "t", .op = .t, .doc = "seconds" },
    .{ .call = "x", .op = .x, .doc = "across, in half the window's height: 0 at the centre, -1.78 to 1.78 on 16:9; 0 in sound" },
    .{ .call = "y", .op = .y, .doc = "up, in half the window's height: -1 at the bottom, 0 at the centre, 1 at the top; 0 in sound" },
    .{ .call = "tau", .op = .constant, .value = std.math.tau, .doc = "a turn in radians, 6.283..." },
    .{ .call = "pi", .op = .constant, .value = std.math.pi, .doc = "half a turn, 3.141..." },
    .{ .call = "sin(a)", .op = .sin, .min = 1, .max = 1, .doc = "sine, of radians" },
    .{ .call = "cos(a)", .op = .cos, .min = 1, .max = 1, .doc = "cosine, of radians" },
    .{ .call = "exp(a)", .op = .exp, .min = 1, .max = 1, .doc = "e to the a" },
    .{ .call = "log(a)", .op = .log, .min = 1, .max = 1, .doc = "natural logarithm" },
    .{ .call = "pow(a, b)", .op = .pow, .min = 2, .max = 2, .doc = "a to the b (a not negative)" },
    .{ .call = "sqrt(a)", .op = .sqrt, .min = 1, .max = 1, .doc = "square root" },
    .{ .call = "abs(a)", .op = .abs, .min = 1, .max = 1, .doc = "a without its sign" },
    .{ .call = "floor(a)", .op = .floor, .min = 1, .max = 1, .doc = "the whole number at or below a" },
    .{ .call = "fract(a)", .op = .fract, .min = 1, .max = 1, .doc = "a - floor(a): 0..1, again every 1" },
    .{ .call = "min(a, b)", .op = .min, .min = 2, .max = 2, .doc = "the smaller" },
    .{ .call = "max(a, b)", .op = .max, .min = 2, .max = 2, .doc = "the larger" },
    .{ .call = "clamp(v, lo, hi)", .op = .clamp, .min = 3, .max = 3, .doc = "v kept between lo and hi" },
    .{ .call = "mix(a, b, w)", .op = .mix, .min = 3, .max = 3, .doc = "a + (b - a) * w" },
    .{ .call = "step(edge, v)", .op = .step, .min = 2, .max = 2, .doc = "0 below edge, 1 from it on" },
    .{ .call = "smoothstep(lo, hi, v)", .op = .smoothstep, .min = 3, .max = 3, .doc = "0 to 1, smoothly, as v goes from lo to hi (either way round)" },
    .{ .call = "atan2(y, x)", .op = .atan2, .min = 2, .max = 2, .doc = "the angle of the point (x, y), radians" },
    .{ .call = "noise(x, y, z)", .op = .noise, .min = 1, .max = 3, .doc = "smooth noise, -1..1, a new value about every 1; y and z are 0 when left out" },
    .{ .call = "saw(p)", .op = .saw, .min = 1, .max = 1, .doc = "a sawtooth, -1..1, of period 1 (cycles, not radians), rising through 0 at 0" },
    .{ .call = "sqr(p)", .op = .sqr, .min = 1, .max = 1, .doc = "a square wave, 1 then -1, of period 1" },
    .{ .call = "tri(p)", .op = .tri, .min = 1, .max = 1, .doc = "a triangle wave, -1..1, of period 1, rising through 0 at 0" },
    .{ .call = "seq(i, v0, v1, ...)", .op = .seq, .min = 2, .max = max_args, .doc = "the value at floor(i), round the list: a step pattern (16 values at most)" },
    .{ .call = "hsv(h, s, v)", .op = .hsv, .min = 3, .max = 3, .doc = "a colour: hue round the wheel 0..1, saturation, value; only as the whole color line" },
    .{ .call = "rgb(r, g, b)", .op = .rgb, .min = 3, .max = 3, .doc = "a colour, red, green and blue 0..1; only as the whole color line" },
};

fn builtin(name: []const u8) ?Builtin {
    for (builtins) |b| if (std.mem.eql(u8, b.name(), name)) return b;
    return null;
}

pub const Instruction = extern struct {
    op: Op = .constant,
    a: u32 = 0,
    b: u32 = 0,
    c: u32 = 0,
};

pub const Tape = struct {
    len: u32 = 0,
    code: Code = @splat(.{}),

    pub const Code = [max_tape]Instruction;

    pub fn slice(tape: *const Tape) []const Instruction {
        return tape.code[0..@min(tape.len, max_tape)];
    }
};

/// What is wrong with a program, and where: a byte of its text.
pub const Problem = struct {
    at: u32 = 0,
    len: u32 = 0,
    words: [96]u8 = @splat(0),

    pub fn text(p: *const Problem) []const u8 {
        return p.words[0..@min(p.len, p.words.len)];
    }
};

/// `probe` is what is heard and seen instead of the program while a
/// selection is on an expression (main.zig): empty when none is asked for,
/// none holds it, or it is longer than a tape.
pub const Program = struct { out: Tape = .{}, color: Tape = .{}, probe: Tape = .{} };

pub const Result = union(enum) { program: Program, problem: Problem };

/// `probe`: bytes from..to of the text, a selection; the smallest
/// expression holding them is compiled as `Program.probe`.
pub fn compile(text: []const u8, probe: ?[2]u32) Result {
    var c: Compiler = .{ .text = text, .probe = probe };
    var program: Program = .{};
    c.lines() catch return .{ .problem = c.problem };
    for ([_]struct { *Tape, []const u8 }{ .{ &program.out, "out" }, .{ &program.color, "color" } }) |line| {
        const name = c.lookup(line[1]) orelse continue;
        var registers: [max_terms]u16 = @splat(none);
        _ = c.emit(line[0], name.term, &registers) catch
            return .{ .problem = (c.fail(name.at, "the {s} line needs more than {d} instructions", .{ line[1], max_tape }) catch c.problem) };
    }
    if (c.heard != none) {
        var registers: [max_terms]u16 = @splat(none);
        _ = c.emit(&program.probe, c.heard, &registers) catch {
            program.probe = .{};
        };
    }
    return .{ .program = program };
}

const none = std.math.maxInt(u16);

const Term = struct {
    op: Op,
    value: f32 = 0,
    /// Where it was written.
    at: u32,
    len: u8 = 0,
    args: [max_args]u16 = undefined,
};

const Name = struct { text: []const u8, term: u16, at: u32 };

const Token = struct {
    kind: enum { name, number, symbol, newline, end },
    at: u32,
    end: u32,
    symbol: u8 = 0,

    fn is(tok: Token, symbol: u8) bool {
        return tok.kind == .symbol and tok.symbol == symbol;
    }
};

const Compiler = struct {
    text: []const u8,
    pos: u32 = 0,
    terms: [max_terms]Term = undefined,
    term_count: u16 = 0,
    names: [max_names]Name = undefined,
    name_count: u16 = 0,
    /// The term of t, x and y, made once.
    inputs: [3]u16 = .{ none, none, none },
    depth: u8 = 0,
    /// The line's hsv or rgb, if it called one.
    colour: u16 = none,
    problem: Problem = .{},
    /// The bytes probed, and the smallest expression found holding them.
    probe: ?[2]u32 = null,
    heard: u16 = none,
    heard_len: u32 = std.math.maxInt(u32),

    /// The expression from byte `from` to where the parse is, its term `t`:
    /// the probe's, if it is the smallest yet that holds the probed bytes.
    fn spanned(c: *Compiler, from: u32, t: u16) u16 {
        const p = c.probe orelse return t;
        if (from <= p[0] and p[1] <= c.pos and c.pos - from < c.heard_len) {
            c.heard = t;
            c.heard_len = c.pos - from;
        }
        return t;
    }

    fn fail(c: *Compiler, at: u32, comptime fmt: []const u8, args: anytype) error{Problem} {
        c.problem = .{ .at = at };
        var w: std.Io.Writer = .fixed(&c.problem.words);
        w.print(fmt, args) catch {};
        c.problem.len = @intCast(w.end);
        return error.Problem;
    }

    fn span(c: *const Compiler, tok: Token) []const u8 {
        return c.text[tok.at..tok.end];
    }

    fn next(c: *Compiler) Token {
        const s = c.text;
        var i = c.pos;
        while (i < s.len and (s[i] == ' ' or s[i] == '\t' or s[i] == '\r')) i += 1;
        if (i < s.len and s[i] == '#') while (i < s.len and s[i] != '\n') : (i += 1) {};
        const at = i;
        defer c.pos = i;
        if (i == s.len) return .{ .kind = .end, .at = at, .end = at };
        switch (s[i]) {
            '\n' => {
                i += 1;
                return .{ .kind = .newline, .at = at, .end = i };
            },
            'a'...'z', 'A'...'Z', '_' => {
                while (i < s.len and (std.ascii.isAlphanumeric(s[i]) or s[i] == '_')) i += 1;
                return .{ .kind = .name, .at = at, .end = i };
            },
            '0'...'9', '.' => {
                while (i < s.len and (std.ascii.isDigit(s[i]) or s[i] == '.' or s[i] == 'e' or
                    ((s[i] == '-' or s[i] == '+') and s[i - 1] == 'e'))) i += 1;
                return .{ .kind = .number, .at = at, .end = i };
            },
            else => {
                i += 1;
                return .{ .kind = .symbol, .at = at, .end = i, .symbol = s[at] };
            },
        }
    }

    fn peek(c: *Compiler) Token {
        const pos = c.pos;
        defer c.pos = pos;
        return c.next();
    }

    fn describe(c: *const Compiler, tok: Token) []const u8 {
        return switch (tok.kind) {
            .newline, .end => "the end of the line",
            else => c.span(tok),
        };
    }

    fn term(c: *Compiler, t: Term) !u16 {
        if (c.term_count == max_terms) return c.fail(t.at, "the program is longer than {d} terms", .{max_terms});
        c.terms[c.term_count] = t;
        c.term_count += 1;
        return c.term_count - 1;
    }

    fn call(c: *Compiler, op: Op, at: u32, args: []const u16) !u16 {
        var t: Term = .{ .op = op, .at = at, .len = @intCast(args.len) };
        @memcpy(t.args[0..args.len], args);
        return c.term(t);
    }

    fn lookup(c: *const Compiler, name: []const u8) ?Name {
        for (c.names[0..c.name_count]) |n| if (std.mem.eql(u8, n.text, name)) return n;
        return null;
    }

    fn lines(c: *Compiler) !void {
        while (true) {
            const first = c.next();
            switch (first.kind) {
                .end => return,
                .newline => continue,
                .name => {},
                else => return c.fail(first.at, "a line is a name, =, and an expression", .{}),
            }
            const name = c.span(first);
            const eq = c.next();
            if (!eq.is('=')) return c.fail(eq.at, "expected = after {s}, found {s}", .{ name, c.describe(eq) });
            if (builtin(name) != null) return c.fail(first.at, "{s} is a builtin: call yours something else", .{name});
            if (c.lookup(name) != null) return c.fail(first.at, "{s} is defined twice: a name is given once", .{name});
            c.colour = none;
            const root = c.spanned(first.at, try c.expr());
            const after = c.next();
            if (after.kind != .newline and after.kind != .end) return c.fail(after.at, "expected the end of the line, found {s}", .{c.describe(after)});
            if (c.colour != none and (c.colour != root or !std.mem.eql(u8, name, "color")))
                return c.fail(c.terms[c.colour].at, "a colour (hsv, rgb) can only be the whole color line", .{});
            if (c.name_count == max_names) return c.fail(first.at, "more than {d} names", .{max_names});
            c.names[c.name_count] = .{ .text = name, .term = root, .at = first.at };
            c.name_count += 1;
        }
    }

    fn enter(c: *Compiler, at: u32) !void {
        if (c.depth == max_depth) return c.fail(at, "nested more than {d} deep", .{max_depth});
        c.depth += 1;
    }

    fn expr(c: *Compiler) error{Problem}!u16 {
        const from = c.peek().at;
        try c.enter(from);
        defer c.depth -= 1;
        var left = try c.product();
        while (true) {
            const tok = c.peek();
            const op: Op = if (tok.is('+')) .add else if (tok.is('-')) .sub else return left;
            _ = c.next();
            left = c.spanned(from, try c.call(op, tok.at, &.{ left, try c.product() }));
        }
    }

    fn product(c: *Compiler) !u16 {
        const from = c.peek().at;
        var left = try c.unary();
        while (true) {
            const tok = c.peek();
            const op: Op = if (tok.is('*')) .mul else if (tok.is('/')) .div else return left;
            _ = c.next();
            left = c.spanned(from, try c.call(op, tok.at, &.{ left, try c.unary() }));
        }
    }

    fn unary(c: *Compiler) error{Problem}!u16 {
        const tok = c.peek();
        if (!tok.is('-')) return c.primary();
        _ = c.next();
        try c.enter(tok.at);
        defer c.depth -= 1;
        const a = try c.unary();
        // A negative number is a number (each literal is a term of its own).
        if (c.terms[a].op == .constant) {
            c.terms[a].value = -c.terms[a].value;
            return c.spanned(tok.at, a);
        }
        return c.spanned(tok.at, try c.call(.neg, tok.at, &.{a}));
    }

    fn primary(c: *Compiler) !u16 {
        const tok = c.next();
        switch (tok.kind) {
            .number => {
                const value = std.fmt.parseFloat(f32, c.span(tok)) catch return c.fail(tok.at, "{s} is not a number", .{c.span(tok)});
                return c.spanned(tok.at, try c.term(.{ .op = .constant, .value = value, .at = tok.at }));
            },
            .name => {
                const name = c.span(tok);
                if (c.peek().is('(')) return c.spanned(tok.at, try c.callOf(tok));
                if (c.lookup(name)) |n| {
                    if (c.terms[n.term].op == .hsv or c.terms[n.term].op == .rgb) return c.fail(tok.at, "{s} is a colour: only the color line can be one", .{name});
                    return c.spanned(tok.at, n.term);
                }
                const b = builtin(name) orelse return c.fail(tok.at, "{s} is not defined above", .{name});
                if (b.max > 0) return c.fail(tok.at, "{s} takes arguments: {s}", .{ name, b.call });
                const input: ?usize = switch (b.op) {
                    .t => 0,
                    .x => 1,
                    .y => 2,
                    else => null,
                };
                const i = input orelse return c.spanned(tok.at, try c.term(.{ .op = b.op, .value = b.value, .at = tok.at }));
                if (c.inputs[i] == none) c.inputs[i] = try c.term(.{ .op = b.op, .at = tok.at });
                return c.spanned(tok.at, c.inputs[i]);
            },
            .newline, .end => return c.fail(tok.at, "expected an expression before the end of the line", .{}),
            .symbol => {
                if (!tok.is('(')) {
                    if (c.text[tok.at] < 0x20 or c.text[tok.at] > 0x7e) return c.fail(tok.at, "byte 0x{x:0>2} is not part of the language", .{c.text[tok.at]});
                    return c.fail(tok.at, "expected an expression, found {s}", .{c.span(tok)});
                }
                const inner = try c.expr();
                const close = c.next();
                if (!close.is(')')) return c.fail(close.at, "expected ) to close the ( at byte {d}, found {s}", .{ tok.at, c.describe(close) });
                return c.spanned(tok.at, inner);
            },
        }
    }

    /// `name(args)`, `name` being `tok`.
    fn callOf(c: *Compiler, tok: Token) !u16 {
        const name = c.span(tok);
        _ = c.next();
        const b = builtin(name) orelse {
            if (c.lookup(name) != null) return c.fail(tok.at, "{s} is a name, not a builtin: it takes no ( )", .{name});
            return c.fail(tok.at, "{s} is not a builtin", .{name});
        };
        if (b.max == 0) return c.fail(tok.at, "{s} takes no arguments", .{name});
        var args: [max_args]u16 = undefined;
        var n: u8 = 0;
        if (c.peek().is(')')) {
            _ = c.next();
        } else while (true) {
            const at = c.peek().at;
            if (n == b.max) return c.fail(at, "{s} takes at most {d} arguments: {s}", .{ name, b.max, b.call });
            args[n] = try c.expr();
            n += 1;
            const sep = c.next();
            if (sep.is(')')) break;
            if (!sep.is(',')) return c.fail(sep.at, "expected , or ) in {s}(...), found {s}", .{ name, c.describe(sep) });
        }
        if (n < b.min) return c.fail(tok.at, "{s} takes {d} arguments, not {d}: {s}", .{ name, b.min, n, b.call });
        if (b.op == .noise) while (n < 3) : (n += 1) {
            args[n] = try c.term(.{ .op = .constant, .at = tok.at });
        };
        const t = try c.call(b.op, tok.at, args[0..n]);
        if (b.op == .hsv or b.op == .rgb) c.colour = t;
        return t;
    }

    fn push(into: *Tape, i: Instruction) !u32 {
        if (into.len == max_tape) return error.Full;
        into.code[into.len] = i;
        into.len += 1;
        return into.len - 1;
    }

    fn emit(c: *const Compiler, into: *Tape, at: u16, registers: *[max_terms]u16) error{Full}!u32 {
        if (registers[at] != none) return registers[at];
        const t = c.terms[at];
        var r: [max_args]u32 = @splat(0);
        for (t.args[0..t.len], 0..) |arg, i| r[i] = try c.emit(into, arg, registers);
        const i: Instruction = switch (t.op) {
            .constant => .{ .op = .constant, .a = @bitCast(t.value) },
            .seq => seq: {
                // The values in registers side by side: as they are when
                // each was emitted just now, else copied.
                const values = r[1..t.len];
                var first = values[0];
                for (values, 0..) |v, k| {
                    if (v != values[0] + k) {
                        first = @intCast(into.len);
                        for (values) |each| _ = try push(into, .{ .op = .copy, .a = each });
                        break;
                    }
                }
                break :seq .{ .op = .seq, .a = r[0], .b = first, .c = @intCast(values.len) };
            },
            else => .{ .op = t.op, .a = r[0], .b = r[1], .c = r[2] },
        };
        const register = try push(into, i);
        registers[at] = @intCast(register);
        return register;
    }
};

/// picture.frag's uniforms (SDL_GPU's fragment set).
pub const Picture = extern struct {
    tape: [max_tape][4]u32,
    len: u32,
    /// Seconds.
    time: f32,
    /// The target, pixels.
    size: [2]f32,

    pub const glsl = .{ .uniform = .{ .set = 3, .instance = "u" } };
};

/// synth.comp's uniforms (SDL_GPU's compute set). Its tapes, the new one
/// and the one it replaces, which the first `fade` samples cross from, are
/// a storage buffer: SDL_GPU's Vulkan backend binds a uniform block 4 KiB
/// at a time, and two tapes are 4 KiB alone.
pub const Synth = extern struct {
    len: u32,
    old_len: u32,
    /// Samples in the block.
    count: u32,
    fade: u32,
    /// The block's first sample, seconds; the old tape's, which differs
    /// after a jump (a seek: the old tape where the device was).
    start: f32,
    old_start: f32,
    rate: f32,
    pad: f32 = 0,

    pub const glsl = .{ .uniform = .{ .set = 2, .instance = "u" } };
};

// ---------------------------------------------------------------------------
// Tests.

const testing = std.testing;

fn compiled(text: []const u8) !Program {
    return switch (compile(text, null)) {
        .program => |p| p,
        .problem => |p| {
            std.debug.print("unexpected problem at {d}: {s}\n", .{ p.at, p.text() });
            return error.TestUnexpectedResult;
        },
    };
}

fn ops(tape: Tape) [max_tape]Op {
    var out: [max_tape]Op = @splat(.constant);
    for (tape.slice(), 0..) |i, k| out[k] = i.op;
    return out;
}

fn expectOps(tape: Tape, want: []const Op) !void {
    try testing.expectEqualSlices(Op, want, ops(tape)[0..tape.len]);
}

/// The survey's program (reports/demo1.md, §1 A); main.zig's test of the
/// grammar parses it too.
pub const survey =
    \\# the beat, shared by sound and picture
    \\bpm   = 120
    \\beat  = t * bpm / 60
    \\kick  = exp(-7 * fract(beat))
    \\bar   = beat / 4
    \\# sound: out is what you hear, -1..1
    \\root  = seq(bar, 55, 55, 65.4, 49)
    \\bass  = saw(root * t) * (1 - kick) * 0.25
    \\thump = sin(tau * 48 * t * (1 + 2 * kick)) * kick * 0.5
    \\hat   = noise(t * 9000) * exp(-30 * fract(beat * 2 + 0.5)) * 0.08
    \\out   = bass + thump + hat
    \\# picture: color is what you see; x and y run 0..1
    \\dx    = x - 0.5
    \\dy    = y - 0.5
    \\r     = sqrt(dx * dx + dy * dy)
    \\ring  = smoothstep(0.03, 0, abs(r - 0.2 - 0.1 * kick))
    \\glow  = 0.15 * noise(x * 6, y * 6, t * 0.5)
    \\color = hsv(fract(bar / 4 + r), 0.6, ring + glow)
    \\
;

test "a tone, instruction by instruction" {
    const p = try compiled("out = sin(tau * 220 * t) * 0.3");
    try expectOps(p.out, &.{ .constant, .constant, .mul, .t, .mul, .sin, .constant, .mul });
    const code = p.out.slice();
    try testing.expectEqual(@as(u32, @bitCast(@as(f32, std.math.tau))), code[0].a);
    try testing.expectEqual(@as(u32, @bitCast(@as(f32, 220))), code[1].a);
    try testing.expectEqual(Instruction{ .op = .mul, .a = 0, .b = 1 }, code[2]);
    try testing.expectEqual(Instruction{ .op = .mul, .a = 2, .b = 3 }, code[4]);
    try testing.expectEqual(Instruction{ .op = .sin, .a = 4 }, code[5]);
    try testing.expectEqual(Instruction{ .op = .mul, .a = 5, .b = 6 }, code[7]);
    try testing.expectEqual(@as(u32, 0), p.color.len);
}

test "the survey's program: each tape holds only what its line reaches" {
    const p = try compiled(survey);
    const heard = ops(p.out)[0..p.out.len];
    const seen = ops(p.color)[0..p.color.len];
    // The sound never reads x or y, nor is coloured; the picture has no
    // bass line or hat.
    for (heard) |op| try testing.expect(op != .x and op != .y and op != .hsv);
    for (seen) |op| try testing.expect(op != .saw and op != .seq and op != .sin);
    try testing.expectEqual(Op.add, heard[heard.len - 1]);
    try testing.expectEqual(Op.hsv, seen[seen.len - 1]);
    // t is one instruction however often it is named; seq's four numbers
    // were emitted side by side, so there are no copies.
    try testing.expectEqual(@as(usize, 1), std.mem.count(Op, heard, &.{.t}));
    try testing.expectEqual(@as(usize, 0), std.mem.count(Op, heard, &.{.copy}));
    try testing.expectEqual(@as(u32, 54), p.out.len);
    try testing.expectEqual(@as(u32, 46), p.color.len);
    // Every operand is an earlier register.
    for ([_]Tape{ p.out, p.color }) |tape| for (tape.slice(), 0..) |i, k| {
        if (@backingInt(i.op) < @backingInt(Op.neg)) continue;
        try testing.expect(i.a < k);
        if (i.op == .seq) {
            try testing.expect(i.b + i.c <= k);
        } else if (@backingInt(i.op) >= @backingInt(Op.add)) try testing.expect(i.b < k);
    };
}

test "every builtin" {
    for (builtins) |b| {
        var buf: [128]u8 = undefined;
        var w: std.Io.Writer = .fixed(&buf);
        try w.print("{s} = {s}", .{ if (b.op == .hsv or b.op == .rgb) "color" else "out", b.name() });
        if (b.max > 0) {
            try w.writeAll("(t");
            for (1..b.min) |_| try w.writeAll(", t * 2");
            try w.writeAll(")");
        }
        const p = try compiled(w.buffered());
        const tape = if (b.op == .hsv or b.op == .rgb) p.color else p.out;
        const last = tape.slice()[tape.len - 1];
        try testing.expectEqual(b.op, last.op);
        if (b.op == .constant) try testing.expectEqual(@as(u32, @bitCast(b.value)), last.a);
    }
    // noise's missing arguments are 0; seq copies values that were not
    // emitted side by side.
    const p = try compiled("a = t * 3\nout = noise(t) + seq(t, 1, a, 2)");
    try expectOps(p.out, &.{ .t, .constant, .constant, .noise, .constant, .constant, .mul, .constant, .copy, .copy, .copy, .seq, .add });
    try testing.expectEqual(Instruction{ .op = .seq, .a = 0, .b = 8, .c = 3 }, p.out.slice()[11]);
    try testing.expectEqual(Instruction{ .op = .copy, .a = 6 }, p.out.slice()[9]);
}

test "precedence, unary minus, numbers, comments, blank lines" {
    const p = try compiled("\n  # nothing\n a = 1 + 2 * -t / 4 - (5 - -6) # trailing\n\nout = a + 1e-3\n");
    // 1 + ((2 * -t) / 4) - (5 - -6)
    try expectOps(p.out, &.{ .constant, .constant, .t, .neg, .mul, .constant, .div, .add, .constant, .constant, .sub, .sub, .constant, .add });
    try testing.expectEqual(@as(u32, @bitCast(@as(f32, -6))), p.out.slice()[9].a);
    try testing.expectEqual(@as(u32, @bitCast(@as(f32, 1e-3))), p.out.slice()[12].a);
}

test "every problem, with its byte" {
    const cases = [_]struct { text: []const u8, at: u32, words: []const u8 }{
        .{ .text = "= 1", .at = 0, .words = "a line is a name, =, and an expression" },
        .{ .text = "out 1", .at = 4, .words = "expected = after out, found 1" },
        .{ .text = "out", .at = 3, .words = "expected = after out, found the end of the line" },
        .{ .text = "sin = 1", .at = 0, .words = "sin is a builtin: call yours something else" },
        .{ .text = "a = 1\na = 2", .at = 6, .words = "a is defined twice: a name is given once" },
        .{ .text = "out = 1 2", .at = 8, .words = "expected the end of the line, found 2" },
        .{ .text = "out = rgb(1, 1, 1)", .at = 6, .words = "a colour (hsv, rgb) can only be the whole color line" },
        .{ .text = "color = hsv(1, 1, 1) * 2", .at = 8, .words = "a colour (hsv, rgb) can only be the whole color line" },
        .{ .text = "color = hsv(1, 1, 1)\nout = color", .at = 27, .words = "color is a colour: only the color line can be one" },
        .{ .text = "out = 1.2.3", .at = 6, .words = "1.2.3 is not a number" },
        .{ .text = "out = kick\nkick = 1", .at = 6, .words = "kick is not defined above" },
        .{ .text = "out = sin", .at = 6, .words = "sin takes arguments: sin(a)" },
        .{ .text = "out = 1 +", .at = 9, .words = "expected an expression before the end of the line" },
        .{ .text = "out = * 2", .at = 6, .words = "expected an expression, found *" },
        .{ .text = "out = 1 $ 2", .at = 8, .words = "expected the end of the line, found $" },
        .{ .text = "out = \x01", .at = 6, .words = "byte 0x01 is not part of the language" },
        .{ .text = "out = (1 + 2", .at = 12, .words = "expected ) to close the ( at byte 6, found the end of the line" },
        .{ .text = "a = 1\nout = a(2)", .at = 12, .words = "a is a name, not a builtin: it takes no ( )" },
        .{ .text = "out = foo(2)", .at = 6, .words = "foo is not a builtin" },
        .{ .text = "out = t(2)", .at = 6, .words = "t takes no arguments" },
        .{ .text = "out = sin(1, 2)", .at = 13, .words = "sin takes at most 1 arguments: sin(a)" },
        .{ .text = "out = sin(1 2)", .at = 12, .words = "expected , or ) in sin(...), found 2" },
        .{ .text = "out = mix(1, 2)", .at = 6, .words = "mix takes 3 arguments, not 2: mix(a, b, w)" },
        .{ .text = "out = sin()", .at = 6, .words = "sin takes 1 arguments, not 0: sin(a)" },
    };
    for (cases) |case| switch (compile(case.text, null)) {
        .program => {
            std.debug.print("{s}: no problem\n", .{case.text});
            return error.TestUnexpectedResult;
        },
        .problem => |p| {
            testing.expectEqualStrings(case.words, p.text()) catch |e| {
                std.debug.print("in {s}\n", .{case.text});
                return e;
            };
            try testing.expectEqual(case.at, p.at);
        },
    };
}

test "past the capacities: problems in words" {
    var buf: [8192]u8 = undefined;
    // A tape of 128 fits; one more instruction does not.
    var w: std.Io.Writer = .fixed(&buf);
    try w.writeAll("out = t");
    for (0..63) |_| try w.writeAll(" + 1");
    const fits = try compiled(w.buffered());
    try testing.expectEqual(@as(u32, 127), fits.out.len);
    try w.writeAll(" + 1");
    switch (compile(w.buffered(), null)) {
        .program => return error.TestUnexpectedResult,
        .problem => |p| {
            try testing.expectEqualStrings("the out line needs more than 128 instructions", p.text());
            try testing.expectEqual(@as(u32, 0), p.at);
        },
    }
    // More terms than the compiler keeps, though no tape reaches them.
    w = .fixed(&buf);
    for (0..300) |_| try w.writeAll("1+");
    try w.writeAll("1");
    const long = w.buffered();
    var text: [8192]u8 = undefined;
    const unused = try std.fmt.bufPrint(&text, "a = {s}\n", .{long});
    switch (compile(unused, null)) {
        .program => return error.TestUnexpectedResult,
        .problem => |p| try testing.expectEqualStrings("the program is longer than 512 terms", p.text()),
    }
    // Names.
    w = .fixed(&buf);
    for (0..max_names + 1) |i| try w.print("n{d} = {d}\n", .{ i, i });
    switch (compile(w.buffered(), null)) {
        .program => return error.TestUnexpectedResult,
        .problem => |p| try testing.expectEqualStrings("more than 128 names", p.text()),
    }
    // Depth.
    w = .fixed(&buf);
    try w.writeAll("out = ");
    for (0..40) |_| try w.writeAll("(");
    try w.writeAll("1");
    for (0..40) |_| try w.writeAll(")");
    switch (compile(w.buffered(), null)) {
        .program => return error.TestUnexpectedResult,
        .problem => |p| try testing.expectEqualStrings("nested more than 32 deep", p.text()),
    }
}

test "a probe: the smallest expression holding the bytes, its own tape" {
    const text = "kick = exp(-7 * fract(t * 2))\nout = sin(tau * 220 * t) * kick";
    for ([_]struct { [2]u32, []const Op }{
        // `tau * 220 * t`, a selection Alt-o grew to
        .{ .{ 40, 53 }, &.{ .constant, .constant, .mul, .t, .mul } },
        // `220` alone, and a cursor on its `2`
        .{ .{ 46, 49 }, &.{.constant} },
        .{ .{ 46, 47 }, &.{.constant} },
        // `kick` where it is used: the line that defines it
        .{ .{ 57, 61 }, &.{ .constant, .t, .constant, .mul, .fract, .mul, .exp } },
        // an argument
        .{ .{ 22, 27 }, &.{ .t, .constant, .mul } },
        // the out line from its name, and the whole of it
        .{ .{ 30, 33 }, &.{ .constant, .constant, .mul, .t, .mul, .sin, .constant, .constant, .mul, .fract, .mul, .exp, .mul } },
    }) |case| {
        const p = try switch (compile(text, case[0])) {
            .program => |p| p,
            .problem => error.TestUnexpectedResult,
        };
        expectOps(p.probe, case[1]) catch |e| {
            std.debug.print("probe {any}\n", .{case[0]});
            return e;
        };
    }
    // nothing holds the newline between the lines: no probe
    try testing.expectEqual(@as(u32, 0), compile(text, .{ 29, 30 }).program.probe.len);
}