summaryrefslogtreecommitdiff
path: root/examples/live
diff options
context:
space:
mode:
Diffstat (limited to 'examples/live')
-rw-r--r--examples/live/src/Lang.zig115
-rw-r--r--examples/live/src/main.zig36
-rw-r--r--examples/live/test/grammar.zig2
-rw-r--r--examples/live/test/live.script13
4 files changed, 124 insertions, 42 deletions
diff --git a/examples/live/src/Lang.zig b/examples/live/src/Lang.zig
index cc6280f..6ad1f40 100644
--- a/examples/live/src/Lang.zig
+++ b/examples/live/src/Lang.zig
@@ -155,16 +155,31 @@ pub const Problem = struct {
}
};
-pub const Program = struct { out: Tape = .{}, color: Tape = .{} };
+/// `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 };
-pub fn compile(text: []const u8) Result {
- var c: Compiler = .{ .text = text };
+/// `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 };
- c.tape(&program.out, "out") catch return .{ .problem = c.problem };
- c.tape(&program.color, "color") 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 };
}
@@ -205,6 +220,21 @@ const Compiler = struct {
/// 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 };
@@ -293,7 +323,7 @@ const Compiler = struct {
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 = try c.expr();
+ 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")))
@@ -310,24 +340,26 @@ const Compiler = struct {
}
fn expr(c: *Compiler) error{Problem}!u16 {
- try c.enter(c.peek().at);
+ 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 = try c.call(op, tok.at, &.{ left, try c.product() });
+ 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 = try c.call(op, tok.at, &.{ left, try c.unary() });
+ left = c.spanned(from, try c.call(op, tok.at, &.{ left, try c.unary() }));
}
}
@@ -341,9 +373,9 @@ const Compiler = struct {
// 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 a;
+ return c.spanned(tok.at, a);
}
- return c.call(.neg, tok.at, &.{a});
+ return c.spanned(tok.at, try c.call(.neg, tok.at, &.{a}));
}
fn primary(c: *Compiler) !u16 {
@@ -351,14 +383,14 @@ const Compiler = struct {
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.term(.{ .op = .constant, .value = value, .at = tok.at });
+ 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.callOf(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 n.term;
+ 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 });
@@ -368,9 +400,9 @@ const Compiler = struct {
.y => 2,
else => null,
};
- const i = input orelse return c.term(.{ .op = b.op, .value = b.value, .at = tok.at });
+ 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.inputs[i];
+ 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 => {
@@ -381,7 +413,7 @@ const Compiler = struct {
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 inner;
+ return c.spanned(tok.at, inner);
},
}
}
@@ -417,15 +449,6 @@ const Compiler = struct {
return t;
}
- /// The tape of the line named `name` (empty without one).
- fn tape(c: *Compiler, into: *Tape, name: []const u8) !void {
- into.* = .{};
- const line = c.lookup(name) orelse return;
- var registers: [max_terms]u16 = @splat(none);
- _ = c.emit(into, line.term, &registers) catch
- return c.fail(line.at, "the {s} line needs more than {d} instructions", .{ name, max_tape });
- }
-
fn push(into: *Tape, i: Instruction) !u32 {
if (into.len == max_tape) return error.Full;
into.code[into.len] = i;
@@ -500,7 +523,7 @@ pub const Synth = extern struct {
const testing = std.testing;
fn compiled(text: []const u8) !Program {
- return switch (compile(text)) {
+ return switch (compile(text, null)) {
.program => |p| p,
.problem => |p| {
std.debug.print("unexpected problem at {d}: {s}\n", .{ p.at, p.text() });
@@ -641,7 +664,7 @@ test "every problem, with its byte" {
.{ .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)) {
+ for (cases) |case| switch (compile(case.text, null)) {
.program => {
std.debug.print("{s}: no problem\n", .{case.text});
return error.TestUnexpectedResult;
@@ -665,7 +688,7 @@ test "past the capacities: problems in words" {
const fits = try compiled(w.buffered());
try testing.expectEqual(@as(u32, 127), fits.out.len);
try w.writeAll(" + 1");
- switch (compile(w.buffered())) {
+ switch (compile(w.buffered(), null)) {
.program => return error.TestUnexpectedResult,
.problem => |p| {
try testing.expectEqualStrings("the out line needs more than 128 instructions", p.text());
@@ -679,14 +702,14 @@ test "past the capacities: problems in words" {
const long = w.buffered();
var text: [8192]u8 = undefined;
const unused = try std.fmt.bufPrint(&text, "a = {s}\n", .{long});
- switch (compile(unused)) {
+ 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())) {
+ switch (compile(w.buffered(), null)) {
.program => return error.TestUnexpectedResult,
.problem => |p| try testing.expectEqualStrings("more than 128 names", p.text()),
}
@@ -696,8 +719,36 @@ test "past the capacities: problems in words" {
for (0..40) |_| try w.writeAll("(");
try w.writeAll("1");
for (0..40) |_| try w.writeAll(")");
- switch (compile(w.buffered())) {
+ 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);
+}
diff --git a/examples/live/src/main.zig b/examples/live/src/main.zig
index d6bc8d6..cc11dbe 100644
--- a/examples/live/src/main.zig
+++ b/examples/live/src/main.zig
@@ -44,6 +44,10 @@ pub const State = struct {
/// The last program that parsed.
out: Lang.Tape = .{},
color: Lang.Tape = .{},
+ /// Hear this: after a node walk (Alt-o, Alt-i, Alt-n, Alt-p), the
+ /// expression the primary range is on, heard and seen (grey) instead of
+ /// out and color until the next key; empty otherwise.
+ probe: Lang.Tape = .{},
/// What is wrong with the text, if it does not parse (`len` 0: nothing).
problem: Lang.Problem = .{},
/// Seconds, from recorded ticks: a replay draws the same frames.
@@ -127,11 +131,23 @@ pub fn update(s: *State, in: *const sk.Input) void {
var fba: std.heap.FixedBufferAllocator = .init(&scratch);
// ponytail: a key the text has no room for is dropped, as part 1's
// buffer dropped it; the editor leaves the value as it was.
- _ = s.ed.key(fba.allocator(), &syn, k);
+ const outcome = s.ed.key(fba.allocator(), &syn, k);
+ s.probe = .{};
+ if (k.alt and outcome == .done and (k.cp == 'o' or k.cp == 'i' or k.cp == 'n' or k.cp == 'p')) probe: {
+ fba.reset();
+ const ranges = fba.allocator().create([pe.max_selections]pe.Selection) catch break :probe;
+ const got = s.ed.ranges(fba.allocator(), ranges) catch break :probe;
+ const r = ranges[got.primary];
+ var text: [Editor.capacity.text]u8 = undefined;
+ switch (Lang.compile(s.ed.read(&text), .{ @intCast(@min(r.anchor, r.head)), @intCast(@max(r.anchor, r.head)) })) {
+ .program => |p| s.probe = p.probe,
+ .problem => {},
+ }
+ }
}
if (s.ed.revision == revision) return;
var text: [Editor.capacity.text]u8 = undefined;
- switch (Lang.compile(s.ed.read(&text))) {
+ switch (Lang.compile(s.ed.read(&text), null)) {
.program => |p| {
s.out = p.out;
s.color = p.color;
@@ -204,7 +220,8 @@ pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
}
// A tape past 64 instructions is drawn at half resolution: at 1280x720
// 128 instructions took 2.7 ms of the GPU, at half 0.85 (the probe).
- const half: u32 = if (s.color.len > 64) 2 else 1;
+ const seen = if (s.probe.len > 0) &s.probe else &s.color;
+ const half: u32 = if (seen.len > 64) 2 else 1;
const size: [2]u32 = .{ width / half, height / half };
if (!std.meta.eql(ss.size, size)) {
if (ss.picture != .none) f.host.freeImage(ss.picture);
@@ -218,8 +235,8 @@ pub fn draw(s: *const State, ss: *Session, f: *sk.Frame) void {
.height = size[1],
.pipelines = &.{picture_pipeline},
.draws = &.{.{ .pipeline = 0, .vertex_count = 3, .fragment_uniforms = gpu.uniform(f.scratch, Lang.Picture{
- .tape = std.mem.bytesToValue([Lang.max_tape][4]u32, &s.color.code),
- .len = s.color.len,
+ .tape = std.mem.bytesToValue([Lang.max_tape][4]u32, &seen.code),
+ .len = seen.len,
.time = s.time,
.size = .{ @floatFromInt(size[0]), @floatFromInt(size[1]) },
}) }},
@@ -255,10 +272,11 @@ fn sound(s: *const State, ss: *Session, f: *sk.Frame) void {
}
const want: u32 = @min(in.lead -| queued, max_block);
if (want > 0) {
- const new = std.mem.sliceAsBytes(s.out.slice());
+ const heard = if (s.probe.len > 0) &s.probe else &s.out;
+ const new = std.mem.sliceAsBytes(heard.slice());
const changed = in.jumped or !std.mem.eql(u8, new, std.mem.sliceAsBytes(ss.heard.slice()));
const tapes = f.scratch.create([2]Lang.Tape.Code) catch return;
- tapes.* = .{ s.out.code, ss.heard.code };
+ tapes.* = .{ heard.code, ss.heard.code };
f.upload(ss.tapes, 0, std.mem.asBytes(tapes));
f.compute(.{
.label = "synth",
@@ -266,7 +284,7 @@ fn sound(s: *const State, ss: *Session, f: *sk.Frame) void {
.readonly = &.{ss.tapes},
.readwrite = &.{ss.block},
.uniforms = gpu.uniform(f.scratch, Lang.Synth{
- .len = s.out.len,
+ .len = heard.len,
.old_len = ss.heard.len,
.count = want,
.fade = if (changed and s.crossfade) want else 0,
@@ -279,7 +297,7 @@ fn sound(s: *const State, ss: *Session, f: *sk.Frame) void {
f.audioBuffer(stream, ss.block, .{ .count = want });
f.download(ss.block, .{ .size = want * @sizeOf(f32), .key = stream });
ss.clock += @as(f64, @floatFromInt(want)) / rate;
- ss.heard = s.out;
+ ss.heard = heard.*;
}
ss.scope.draw(f, .{
.oscilloscope = .{ .rect = .{ .x = 16, .y = height - 104, .w = 480, .h = 88 }, .samples = 1024 },
diff --git a/examples/live/test/grammar.zig b/examples/live/test/grammar.zig
index 497c05d..2fa982f 100644
--- a/examples/live/test/grammar.zig
+++ b/examples/live/test/grammar.zig
@@ -41,7 +41,7 @@ test "the grammar and Lang.zig agree: both take a program, both refuse a broken
}) |case| {
const tree = parser.parseString(case.text, null) orelse return error.NoTree;
defer tree.destroy();
- const lang = Lang.compile(case.text) == .program;
+ const lang = Lang.compile(case.text, null) == .program;
std.testing.expectEqual(case.grammar, !tree.rootNode().hasError()) catch |e| {
std.debug.print("the grammar on {s}\n", .{case.text});
return e;
diff --git a/examples/live/test/live.script b/examples/live/test/live.script
index ecf3d77..a06ed97 100644
--- a/examples/live/test/live.script
+++ b/examples/live/test/live.script
@@ -68,3 +68,16 @@ console stop
expect ed.front 53
expect ed.back 0
expect color.code[3].op hsv
+# Hear this: Alt-o from the 2 of 220 to the number, then to `tau * 220`,
+# which alone is heard and seen until the next key.
+type gg
+type 16l
+hold left_alt
+key o
+expect probe.len 1
+key o
+release left_alt
+expect probe.len 3
+expect probe.code[2].op mul
+key escape
+expect probe.len 0