Playground
bf.gno
// Package bf is a Brainfuck machine for gno.land, and the measuring stick the
// rest of the guest-VM work is calibrated against.
//
// It ships two things that look alike and are not:
//
// - [Execute], the naive interpreter: a switch over the source bytes, a
// brace matcher that rescans the program on every loop edge. It is kept
// verbatim as rung 0 of the optimization ladder, because a baseline you
// have edited is not a baseline.
// - [Compile] plus [Machine], the real one: the program is compiled to an
// op array with resolved jumps, runs of identical operators are fused,
// the common loop idioms become single ops, and execution is metered by
// a caller-supplied fuel budget against a
// [vmkit](/p/nym-moultest123/x/vm/vmkit/v0) Host, so a program can pause when it
// runs out and resume in a later transaction.
//
// The ladder between them is measured, not asserted: see the README for the
// table, and ladder_test.gno for the harness that produces it.
//
// Live demo: [r/moul/x/vm/bfdemo](/r/nym-moultest123/x/vm/bfdemo/v0).
package bf
import "strings"
// NaiveTapeSize is the tape length used by [Execute]. It is 30,000 because
// that is what the original had, and rung 0 is not allowed to drift.
const NaiveTapeSize = 30000
// Execute runs code on a fresh tape and returns everything it wrote, using
// the original 2023 implementation: no compilation step, one switch per
// source byte, and a brace matcher that rescans the source every time a loop
// opens or closes.
//
// It is rung 0 of the ladder and exists to be measured. Two of its properties
// are bugs that are deliberately preserved, and are the reason nothing should
// call it on untrusted input:
//
// - `,` panics with "unsupported": there is no input.
// - unbalanced brackets run the scan off the end of the source and panic
// with an index out of range.
//
// Use [Compile] and [Machine] for anything real: they reject a malformed
// program up front, read input from the host, and cannot run unbounded.
func Execute(code string) string {
var (
memory = make([]byte, NaiveTapeSize) // memory tape
pointer = 0 // initial memory pointer
buf strings.Builder
)
// Loop through each character in the code
for i := 0; i < len(code); i++ {
switch code[i] {
case '>':
// Increment memory pointer
pointer++
if pointer >= NaiveTapeSize {
pointer = 0
}
case '<':
// Decrement memory pointer
pointer--
if pointer < 0 {
pointer = NaiveTapeSize - 1
}
case '+':
// Increment the byte at the memory pointer
memory[pointer]++
case '-':
// Decrement the byte at the memory pointer
memory[pointer]--
case '.':
// Output the byte at the memory pointer
buf.WriteByte(memory[pointer])
case ',':
// Input a byte and store it in the memory
panic("unsupported")
case '[':
// Jump forward past the matching ']' if the byte at the memory pointer is zero
if memory[pointer] == 0 {
braceCount := 1
for braceCount > 0 {
i++
if code[i] == '[' {
braceCount++
} else if code[i] == ']' {
braceCount--
}
}
}
case ']':
// Jump backward to the matching '[' if the byte at the memory pointer is nonzero
if memory[pointer] != 0 {
braceCount := 1
for braceCount > 0 {
i--
if code[i] == ']' {
braceCount++
} else if code[i] == '[' {
braceCount--
}
}
i-- // Move back one more to compensate for the upcoming increment in the loop
}
}
}
return buf.String()
}
bf_test.gno
package bf
import (
"testing"
"gno.land/p/nym-moultest123/x/vm/vmkit/v0"
"gno.land/p/nt/uassert/v0"
)
// hello is the classic 106 byte hello-world. It writes "Hello World", 11
// bytes: the original run.gno comment was optimistic about the trailing "!\n".
const hello = "++++++++++[>+++++++>++++++++++>+++>+<<<<-]>++.>+.+++++++..+++.>++.<<+++++++++++++++.>.+++.------.--------."
// corpus is the set of programs every ladder level must agree on. Each one is
// here because it exercises a rewrite that could plausibly be wrong.
var corpus = []struct {
name string
src string
want string
}{
{"empty", "", ""},
{"comment only", "this is not brainfuck", ""},
{"hello", hello, "Hello World"},
{"clear idiom", "+++++[-]+++++++++++++++++++++++++++++++++++++++++++++++.", "/"},
{"move idiom", "+++++++++++++++++++++++++++++++++++++++++++++++++++[->+<]>.", "3"},
{"multiply idiom", "+++++[->++++++++++<]>++.", "4"},
{"two targets", "+++[->+>++<<]>+++++++++++++++++++++++++++++++++++++++.>+++++++++++++++++++++++++++++++++++++++++.", "*/"},
{"scan walks", ">+>+>+>+[<]++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.", "H"},
{"scan right", ">>>+++++++++<<<[>]+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++.", "?"},
{"nested loops", "++[>++[>+<-]<-]>>+++++++++++++++++++++++++++++++++++++++++++++++++.", "5"},
{"dead run", "+++--+++--+++++++++++++++++++++++++++++++++++++++++++.", "-"},
{"skipped loop", "[++++++++++++++++++++]+++++++++++++++++++++++++++++++++++++++++++++++.", "/"},
{"wraps under zero", "-[>+<-]>++++++++++.", "\t"},
}
func runLevel(t *testing.T, src string, lvl Level, input string) string {
t.Helper()
prog, err := Compile(src, lvl)
uassert.NoError(t, err)
if prog == nil {
return ""
}
h := vmkit.NewTestHost().WithInput([]byte(input))
m := NewMachine(prog)
_, status := m.Step(h, vmkit.Unmetered)
uassert.Equal(t, "halted", status.String())
return h.OutString()
}
// TestLadderLevelsAgree is the test the whole ladder rests on: an
// optimization that changes the output is not an optimization.
func TestLadderLevelsAgree(t *testing.T) {
for _, tc := range corpus {
naive := Execute(tc.src)
uassert.Equal(t, tc.want, naive)
for _, lvl := range []Level{LevelJumps, LevelFuse, LevelIdioms} {
got := runLevel(t, tc.src, lvl, "")
if got != tc.want {
t.Errorf("%s at level %s: got %q, want %q",
tc.name, lvl.String(), got, tc.want)
}
}
}
}
func TestExecuteBaseline(t *testing.T) {
// Rung 0 is kept verbatim, so this is also a regression test on the
// thing the published cycles-per-op number was measured against.
uassert.Equal(t, "Hello World", Execute(hello))
uassert.Equal(t, 11, len(Execute(hello)))
}
func TestCompileRejectsUnbalanced(t *testing.T) {
cases := []string{"[", "]", "[[]", "+[->+<", "][", "[[[]]"}
for _, src := range cases {
_, err := CompileDefault(src)
if err == nil {
t.Errorf("Compile(%q) should have failed", src)
}
}
}
func TestCompileRejectsOversizeSource(t *testing.T) {
src := "+"
for len(src) <= MaxSource {
src += src // doubling, not O(n^2) appending
}
_, err := CompileDefault(src)
uassert.ErrorIs(t, err, ErrSourceTooLong)
}
func TestCompileRejectsUnknownLevel(t *testing.T) {
_, err := Compile("+", Level(42))
uassert.Error(t, err)
_, err = Compile("+", Level(-1))
uassert.Error(t, err)
}
// TestLadderShrinksTheOpStream is the compile-time half of the ladder: each
// rung has to produce strictly fewer ops than the one below it, or it is not
// buying anything.
func TestLadderShrinksTheOpStream(t *testing.T) {
jumps, err := Compile(hello, LevelJumps)
uassert.NoError(t, err)
fuse, err := Compile(hello, LevelFuse)
uassert.NoError(t, err)
idioms, err := Compile(hello, LevelIdioms)
uassert.NoError(t, err)
uassert.True(t, jumps.Len() > fuse.Len())
uassert.True(t, fuse.Len() > idioms.Len())
uassert.Equal(t, "jumps", jumps.Level().String())
uassert.Equal(t, hello, idioms.Source())
}
func TestIdiomRecognition(t *testing.T) {
cases := []struct {
name string
src string
want int // ops, excluding the trailing halt
}{
{"clear", "[-]", 1}, // opSet
{"move", "[->+<]", 2}, // opAddMul, opSet
{"multiply two", "[->++>+++<<]", 3}, // two opAddMul, opSet
{"scan right", "[>]", 1}, // opScan
{"scan left", "[<]", 1}, // opScan
}
for _, tc := range cases {
prog, err := Compile(tc.src, LevelIdioms)
uassert.NoError(t, err)
if prog == nil {
continue
}
if got := prog.Len() - 1; got != tc.want {
t.Errorf("%s: %q compiled to %d ops, want %d",
tc.name, tc.src, got, tc.want)
}
}
}
// TestPlusLoopIsNotRewritten pins the conservative half of the rewrite: a
// loop that adds one per iteration still reaches zero by wrapping, but only
// after 256 iterations, and folding it would be a different program. It has
// to stay a real loop.
func TestPlusLoopIsNotRewritten(t *testing.T) {
prog, err := Compile("[+]", LevelIdioms)
uassert.NoError(t, err)
// opJmpZ, opAdd, opJmpNZ, opHalt: untouched.
uassert.Equal(t, 4, prog.Len())
}
func TestInputThroughTheHost(t *testing.T) {
// Read three bytes and echo them back.
const echo3 = ",.,.,."
h := vmkit.NewTestHost().WithInput([]byte("gno"))
m, err := Load(echo3)
uassert.NoError(t, err)
_, status := m.Step(h, vmkit.Unmetered)
uassert.Equal(t, "halted", status.String())
uassert.Equal(t, "gno", h.OutString())
}
func TestInputEndsAsZero(t *testing.T) {
// Past the end of input, `,` yields a zero cell. Without input at all,
// the naive interpreter would have panicked here.
h := vmkit.NewTestHost().WithInput([]byte("a"))
m, err := Load(",.+++++++++++++++++++++++++++++++++++++++++++++++.,+++++++++++++++++++++++++++++++++++++++++++++++++.")
uassert.NoError(t, err)
_, status := m.Step(h, vmkit.Unmetered)
uassert.Equal(t, "halted", status.String())
uassert.Equal(t, "a\x901", h.OutString())
}
func TestExecutePanicsOnInput(cur realm, t *testing.T) {
// Rung 0's second preserved bug, pinned so nobody "fixes" the baseline.
uassert.PanicsWithMessage(t, cur, "unsupported", func() { Execute(",") })
}
func TestMachineWithoutProgram(t *testing.T) {
m := &Machine{status: vmkit.Running}
used, status := m.Step(vmkit.NewTestHost(), 10)
uassert.Equal(t, int64(0), used)
uassert.Equal(t, "trapped", status.String())
uassert.Equal(t, "no program", m.Trap())
}
compile.gno
package bf
import (
"errors"
"gno.land/p/nt/ufmt/v0"
)
// TapeSize is the tape length of a compiled [Machine]. It matches
// [NaiveTapeSize] so that the ladder compares like with like: a rung that
// changed the semantics would not be a rung, it would be a different program.
const TapeSize = 30000
// MaxSource bounds the program a realm will accept. Compilation is linear in
// the source, but the op array and every snapshot of it are consensus state,
// so the size has to be bounded somewhere the caller can see.
const MaxSource = 64 * 1024
// ErrSourceTooLong is returned by [Compile] for a program above [MaxSource].
var ErrSourceTooLong = errors.New("bf: source too long")
// Level selects how far up the optimization ladder [Compile] goes.
//
// Every level produces the same output for the same program: the levels exist
// so the cost of each optimization can be measured in isolation, which is the
// published result this package is really for. Rung 0 of the ladder is
// [Execute] and has no compiler at all.
type Level int
const (
// LevelJumps is rung 1: one op per source byte, with the jump targets
// resolved at compile time. This is the rung that kills the brace
// rescan, which in [Execute] costs O(loop body) on every iteration.
LevelJumps Level = iota
// LevelFuse is rung 2: runs of identical operators collapse, so
// "+++++" is one add-5 and ">>>" is one move-3. Real programs are
// mostly runs.
LevelFuse
// LevelIdioms is rung 3: a loop whose body only moves and adds, and
// which returns to where it started while decrementing the current
// cell by one, is replaced by the multiply-adds it performs plus a
// clear. "[-]" becomes one op, "[->+<]" becomes two.
LevelIdioms
)
// Default is the level [CompileDefault] uses, and the one a realm should
// want: every optimization this package knows, same semantics.
const Default = LevelIdioms
// String names the level, for the ladder table and for realm output.
func (l Level) String() string {
switch l {
case LevelJumps:
return "jumps"
case LevelFuse:
return "fuse"
case LevelIdioms:
return "idioms"
}
return "unknown"
}
type opcode byte
const (
opAdd opcode = iota // tape[p] += arg (arg normalized to 0..255)
opMove // p += arg
opOut // write tape[p] to the host
opIn // read one input byte into tape[p]
opJmpZ // if tape[p] == 0 { pc = arg }
opJmpNZ // if tape[p] != 0 { pc = arg }
opSet // tape[p] = byte(arg)
opAddMul // tape[p+off] += tape[p] * byte(arg)
opScan // while tape[p] != 0 { p += arg }
opHalt // end of program
)
// op is one compiled instruction. It is a flat struct on purpose: the
// execution loop indexes an array of these, and an op that owned a slice
// would allocate in the hot path.
type op struct {
code opcode
arg int
off int
}
// Program is compiled Brainfuck, ready to run on a [Machine].
type Program struct {
ops []op
src string
level Level
}
// Source returns the program text the [Program] was compiled from.
func (p *Program) Source() string { return p.src }
// Level returns the ladder rung this program was compiled at.
func (p *Program) Level() Level { return p.level }
// Len returns the number of compiled ops, including the trailing halt. It is
// the number worth quoting next to the source length: the ratio is exactly
// what the ladder buys.
func (p *Program) Len() int { return len(p.ops) }
// CompileDefault compiles at [Default].
func CompileDefault(src string) (*Program, error) { return Compile(src, Default) }
// Compile turns Brainfuck source into a [Program] at the requested ladder
// level. Everything that is not one of the eight operators is a comment, as
// the language requires.
//
// It fails on unbalanced brackets rather than trusting the runtime to notice,
// which is the first thing that separates it from [Execute]: a malformed
// program is rejected before anybody pays to run it.
func Compile(src string, lvl Level) (*Program, error) {
if len(src) > MaxSource {
return nil, ErrSourceTooLong
}
if lvl < LevelJumps || lvl > LevelIdioms {
return nil, ufmt.Errorf("bf: unknown level %d", int(lvl))
}
ops := []op{}
opens := []int{} // pc of each unclosed opJmpZ
for i := 0; i < len(src); i++ {
c := src[i]
switch c {
case '+', '-':
delta := 1
if c == '-' {
delta = -1
}
if lvl >= LevelFuse {
n := 1
for i+n < len(src) && (src[i+n] == '+' || src[i+n] == '-') {
if src[i+n] == '+' {
delta++
} else {
delta--
}
n++
}
i += n - 1
}
if a := normAdd(delta); a != 0 {
ops = append(ops, op{code: opAdd, arg: a})
}
case '>', '<':
delta := 1
if c == '<' {
delta = -1
}
if lvl >= LevelFuse {
n := 1
for i+n < len(src) && (src[i+n] == '>' || src[i+n] == '<') {
if src[i+n] == '>' {
delta++
} else {
delta--
}
n++
}
i += n - 1
}
if d := normMove(delta); d != 0 {
ops = append(ops, op{code: opMove, arg: d})
}
case '.':
ops = append(ops, op{code: opOut})
case ',':
ops = append(ops, op{code: opIn})
case '[':
opens = append(opens, len(ops))
ops = append(ops, op{code: opJmpZ})
case ']':
if len(opens) == 0 {
return nil, ufmt.Errorf("bf: unmatched ']' at byte %d", i)
}
open := opens[len(opens)-1]
opens = opens[:len(opens)-1]
if lvl >= LevelIdioms {
if idiom, ok := simpleLoop(ops[open+1:]); ok {
ops = append(ops[:open], idiom...)
continue
}
}
// pc lands on the op after the jump, so a jump target is
// the index of the partner op itself.
ops = append(ops, op{code: opJmpNZ, arg: open})
ops[open].arg = len(ops) - 1
}
}
if len(opens) != 0 {
return nil, ufmt.Errorf("bf: %d unmatched '['", len(opens))
}
ops = append(ops, op{code: opHalt})
return &Program{ops: ops, src: src, level: lvl}, nil
}
// normAdd folds a signed delta into the 0..255 the byte tape actually sees,
// so the execution loop never has to convert a negative int to a byte.
func normAdd(d int) int {
d %= 256
if d < 0 {
d += 256
}
return d
}
// normMove folds a pointer delta into one lap of the tape. Moving right
// TapeSize times is a no-op on a wrapping tape, in the naive interpreter as
// much as here, so collapsing it changes nothing but the op count.
func normMove(d int) int {
d %= TapeSize
if d < 0 {
d += TapeSize
}
if d > TapeSize/2 {
d -= TapeSize
}
return d
}
// cell is one offset the body of a simple loop writes to.
type cell struct {
off int
delta int
}
// simpleLoop decides whether a loop body can be replaced by straight-line
// code, and returns that code.
//
// Two shapes qualify, and they are the two that dominate real programs:
//
// - The body only moves, and ends somewhere other than where it started:
// that is a scan, "[>]" walking to the next zero cell.
// - The body only moves and adds, ends where it started, and takes exactly
// one off the current cell: that is a multiply-add. The loop runs
// tape[p] times, so every other cell it touches gains its delta times
// tape[p], and the current cell ends at zero. "[-]" is the degenerate
// case with no other cells.
//
// Anything else, including any body containing I/O or a nested loop that was
// itself rewritten, is left alone. Being conservative here costs a few ops in
// rare programs and is the only reason this rewrite is safe at all: a loop
// whose current cell does not reach zero in steps of one is not guaranteed to
// terminate, and constant-folding it would change the program.
func simpleLoop(body []op) ([]op, bool) {
cursor := 0
cells := []cell{}
adds := 0
for _, o := range body {
switch o.code {
case opMove:
cursor += o.arg
case opAdd:
adds++
// Carry the delta as a signed value; it is normalized
// back into 0..255 when it is emitted.
d := o.arg
if d > 128 {
d -= 256
}
cells = addCell(cells, cursor, d)
default:
return nil, false
}
}
if cursor != 0 {
// Net movement: only a pure scan qualifies, and only when the
// step is not zero (which normMove already guarantees here).
if adds != 0 {
return nil, false
}
return []op{{code: opScan, arg: cursor}}, true
}
// Balanced. The current cell must fall by exactly one per iteration,
// or the loop is not a counted multiply-add.
if delta(cells, 0) != -1 {
return nil, false
}
out := []op{}
for _, c := range cells {
if c.off == 0 || c.delta == 0 {
continue
}
out = append(out, op{code: opAddMul, arg: normAdd(c.delta), off: c.off})
}
out = append(out, op{code: opSet, arg: 0})
return out, true
}
// addCell accumulates a delta at an offset, keeping cells sorted by offset so
// that the op stream a program compiles to is identical on every node.
func addCell(cells []cell, off, d int) []cell {
for i := range cells {
if cells[i].off == off {
cells[i].delta += d
return cells
}
if cells[i].off > off {
cells = append(cells, cell{})
copy(cells[i+1:], cells[i:])
cells[i] = cell{off: off, delta: d}
return cells
}
}
return append(cells, cell{off: off, delta: d})
}
func delta(cells []cell, off int) int {
for _, c := range cells {
if c.off == off {
return c.delta
}
}
return 0
}
gnomod.toml
module = "gno.land/p/nym-moultest123/x/vm/bf/v0" gno = "0.9" [addpkg] creator = "g1ml9grtwnpzqn3hre5ve5vjdlmv2srrmpmc0dsv" height = 186409 max_deposit = "21000000ugnot"
ladder_test.gno
package bf
import (
"testing"
"gno.land/p/nym-moultest123/x/vm/vmkit/v0"
"gno.land/p/nt/uassert/v0"
)
// heavy is the benchmark program: 200 increments, then an outer loop that on
// each of its 200 iterations moves right, adds 200, clears that cell with the
// "[-]" idiom, and moves back.
//
// It writes nothing, so a measurement of it is a measurement of the dispatch
// loop and not of the output path.
var heavy = rep("+", 200) + "[" + "-" + ">" + rep("+", 200) + "[-]" + "<" + "]"
// GuestOps and NaiveDispatches are the two counts for [heavy], and the
// difference between them is the reason the ladder needs both named.
//
// A guest instruction is one operator the language executes, counted the way
// any jump-table interpreter counts it. The naive interpreter dispatches more
// often than that for the same program: its "]" handler scans back to the
// matching "[" and lands on it, so "[" is re-evaluated on every iteration of
// every loop. On heavy that is 1.33 dispatches per guest instruction.
//
// Rung 1 removes exactly that excess, so a ladder that used the naive
// dispatch count as its denominator would be crediting rung 1 twice. Both
// numbers come from an independent simulator, not from this package, so the
// denominator is not derived from the thing being measured.
const (
GuestOps = 121201
NaiveDispatches = 161200
)
func rep(s string, n int) string {
out := ""
for i := 0; i < n; i++ {
out += s
}
return out
}
// nullHost is a Host that costs as close to nothing as a Host can, so the
// ladder measures the dispatch loop rather than the storage or output path.
type nullHost struct{}
func (nullHost) Caller() address { return address("") }
func (nullHost) Origin() address { return address("") }
func (nullHost) Now() int64 { return 0 }
func (nullHost) Height() int64 { return 0 }
func (nullHost) Get(key []byte) []byte { return nil }
func (nullHost) Set(key, val []byte) {}
func (nullHost) Input() []byte { return nil }
func (nullHost) Output(p []byte) {}
func (nullHost) Emit(typ string, kv ...string) {}
func (nullHost) Send(to address, amount int64) error { return vmkit.ErrNotGranted }
func (nullHost) Log(msg string) {}
// runHeavy compiles heavy at lvl and runs it on the shipped machine,
// returning how many machine ops it executed. The count is the fuel the
// machine charged itself, so the ladder's "machine ops" column is measured by
// the machine and not counted by hand.
func runHeavy(t *testing.T, lvl Level) int64 {
t.Helper()
prog, err := Compile(heavy, lvl)
uassert.NoError(t, err)
if prog == nil {
return 0
}
m := NewMachine(prog)
used, status := m.Step(nullHost{}, vmkit.Unmetered)
uassert.Equal(t, "halted", status.String())
return used
}
// The rungs. One test each, so `gno test -print-runtime-metrics` prints one
// cycle count per rung and the README's table is a transcription rather than
// an estimate. They assert that the run completed and how many machine ops it
// took: what is being recorded is the metric line.
func TestRung0Naive(t *testing.T) {
uassert.Equal(t, "", Execute(heavy))
}
func TestRung0Naive4x(t *testing.T) {
for i := 0; i < 4; i++ {
Execute(heavy)
}
}
func TestRung1Jumps(t *testing.T) {
uassert.Equal(t, int64(GuestOps+1), runHeavy(t, LevelJumps))
}
func TestRung2Fuse(t *testing.T) {
uassert.True(t, runHeavy(t, LevelFuse) < GuestOps)
}
func TestRung3Idioms(t *testing.T) {
uassert.True(t, runHeavy(t, LevelIdioms) < GuestOps)
}
func TestRung3Idioms4x(t *testing.T) {
for i := 0; i < 4; i++ {
runHeavy(t, LevelIdioms)
}
}
func TestRung5Metered(t *testing.T) {
// Same program, same rung, but every op goes through the fuel meter's
// budget branch instead of its unmetered one. The delta against
// TestRung3Idioms is the price of being a machine that can be stopped.
prog, err := Compile(heavy, LevelIdioms)
uassert.NoError(t, err)
m := NewMachine(prog)
_, status := m.Step(nullHost{}, 1<<40)
uassert.Equal(t, "halted", status.String())
}
// TestLadderOpCounts records the compile-time half of the ladder: how many
// machine ops each rung executes for the same 121,201 guest instructions.
// These are the numbers the README's table quotes, asserted here so the table
// cannot silently go stale.
func TestLadderOpCounts(t *testing.T) {
jumps := runHeavy(t, LevelJumps)
fuse := runHeavy(t, LevelFuse)
idioms := runHeavy(t, LevelIdioms)
// Rung 1 executes exactly one machine op per guest instruction, plus
// the halt: the independent simulator and this machine agree to the op.
uassert.Equal(t, int64(121202), jumps)
// Fusing runs of + and > collapses the two 200-long runs.
uassert.Equal(t, int64(81203), fuse)
// Recognizing "[-]" turns the inner clear loop into a single op.
uassert.Equal(t, int64(1203), idioms)
uassert.True(t, fuse < jumps)
uassert.True(t, idioms < fuse)
}
machine.gno
package bf
import (
"errors"
"gno.land/p/nym-moultest123/x/vm/vmkit/v0"
)
// VMName is the identifier this machine registers under in a
// [vmkit.Instance].
const VMName = "bf"
// snapMagic and snapVersion tag a snapshot so a machine refuses bytes that
// were not written by this machine at this version, instead of decoding them
// into a plausible-looking wrong state.
const (
snapMagic uint32 = 0x62660001 // "bf" 0001
snapVersion byte = 1
)
// ErrNoProgram is returned when a [Machine] is stepped without a program.
var ErrNoProgram = errors.New("bf: machine has no program")
// Machine is a compiled Brainfuck program, mid-execution: a
// [vmkit.Machine] with a fixed tape, a fuel-metered step loop, input and
// output through the host, and a snapshot small enough that pausing is
// cheaper than starting over.
//
// The tape is a fixed-size array rather than a slice: that is rung 4 of the
// ladder, and the README reports what it actually bought.
type Machine struct {
prog *Program
tape [TapeSize]byte
ptr int
pc int
inPos int // read cursor into Host.Input, carried across slices
status vmkit.Status
trap string
// hi is the highest tape index written so far, so a snapshot can stop
// there instead of carrying 30,000 bytes of zeros.
hi int
}
// NewMachine returns a machine ready to run prog from the start.
func NewMachine(prog *Program) *Machine {
return &Machine{prog: prog, status: vmkit.Running}
}
// Load compiles src at [Default] and returns a machine for it.
func Load(src string) (*Machine, error) {
prog, err := CompileDefault(src)
if err != nil {
return nil, err
}
return NewMachine(prog), nil
}
// Program returns the program the machine is running.
func (m *Machine) Program() *Program { return m.prog }
// Status returns the machine's current status.
func (m *Machine) Status() vmkit.Status { return m.status }
// Trap returns the reason the machine trapped, or "". It makes Machine a
// [vmkit.Trapper].
func (m *Machine) Trap() string { return m.trap }
// Pointer returns the tape pointer.
func (m *Machine) Pointer() int { return m.ptr }
// PC returns the index of the next op to execute.
func (m *Machine) PC() int { return m.pc }
// Cell returns the tape byte at i, wrapped into range.
func (m *Machine) Cell(i int) byte { return m.tape[wrap(i)] }
// Touched returns how many tape cells the program has reached, which is the
// length a snapshot has to carry.
func (m *Machine) Touched() int { return m.hi + 1 }
// Step runs until the program halts, traps, or spends `fuel` units, charging
// one unit per op executed and one per cell a scan walks over. Pass
// [vmkit.Unmetered] to run to completion.
//
// Fuel is charged before the op runs, so a machine that stops for lack of
// fuel has not half-executed anything: it is exactly at the op it could not
// pay for, and resuming re-executes that op and nothing else.
//
// Three things in here are written the way they are because the alternative
// was measured and lost. The README has the table.
//
// - The fuel counter is two locals, not a [vmkit.Meter]. Calling
// Meter.Charge once per instruction costs 86% on top of the whole
// dispatch loop and triples the allocation count. Meter stays the type
// at the API boundary, where it is called once; it is not a hot-path
// type, and no guest VM should treat it as one.
// - The program counter and the tape pointer are locals, written back once
// by the deferred closure. Reaching through m. for them on every
// instruction costs 16%.
// - The pc range check happens once, before the loop, not per op. Every
// jump target is produced by [Compile] and every restored pc is
// validated by [Machine.Restore], so per-op checking buys nothing.
func (m *Machine) Step(h vmkit.Host, fuel int64) (int64, vmkit.Status) {
if m.prog == nil {
m.status, m.trap = vmkit.Trapped, "no program"
return 0, m.status
}
if m.status != vmkit.Running {
return 0, m.status
}
ops := m.prog.ops
pc, ptr, hi := m.pc, m.ptr, m.hi
// One write-back, on every return path, including a panic.
defer func() { m.pc, m.ptr, m.hi = pc, ptr, hi }()
if pc < 0 || pc >= len(ops) {
m.status, m.trap = vmkit.Trapped, "pc out of range"
return 0, m.status
}
// budget < 0 is vmkit.Unmetered.
budget := fuel
if budget < 0 {
budget = vmkit.Unmetered
}
var used int64
for {
if budget != vmkit.Unmetered && used >= budget {
return used, vmkit.Running
}
used++
switch ops[pc].code {
case opAdd:
m.tape[ptr] += byte(ops[pc].arg)
case opMove:
ptr = wrap(ptr + ops[pc].arg)
if ptr > hi {
hi = ptr
}
case opSet:
m.tape[ptr] = byte(ops[pc].arg)
case opAddMul:
if v := m.tape[ptr]; v != 0 {
t := wrap(ptr + ops[pc].off)
m.tape[t] += v * byte(ops[pc].arg)
if t > hi {
hi = t
}
}
case opScan:
// A scan is charged per cell, so it cannot be a way to
// buy unbounded work for one unit of fuel. Stopping
// mid-scan is safe: the pointer has moved, the pc has
// not, so resuming continues the same walk.
for m.tape[ptr] != 0 {
if budget != vmkit.Unmetered && used >= budget {
return used, vmkit.Running
}
used++
ptr = wrap(ptr + ops[pc].arg)
if ptr > hi {
hi = ptr
}
}
case opOut:
h.Output([]byte{m.tape[ptr]})
case opIn:
in := h.Input()
if m.inPos < len(in) {
m.tape[ptr] = in[m.inPos]
m.inPos++
} else {
// End of input is a zero cell, the most common
// of the three conventions the language never
// settled.
m.tape[ptr] = 0
}
case opJmpZ:
if m.tape[ptr] == 0 {
pc = ops[pc].arg
}
case opJmpNZ:
if m.tape[ptr] != 0 {
pc = ops[pc].arg
}
case opHalt:
m.status = vmkit.Halted
return used, m.status
default:
m.status, m.trap = vmkit.Trapped, "unknown opcode"
return used, m.status
}
pc++
}
}
// Snapshot serializes the machine. The tape is truncated at the highest cell
// the program has reached, which is what makes pausing affordable: a hello
// world that touched six cells snapshots six bytes of tape, not 30,000.
func (m *Machine) Snapshot() []byte {
w := vmkit.NewWriter(m.hi + 48)
w.Uint32(snapMagic)
w.Byte(snapVersion)
w.Int(int64(m.pc))
w.Int(int64(m.ptr))
w.Int(int64(m.inPos))
w.Byte(byte(m.status))
w.String(m.trap)
n := m.hi + 1
if n > TapeSize {
n = TapeSize
}
w.Bytes(m.tape[:n])
return w.Out()
}
// Restore loads a snapshot into a machine that already carries the program
// the snapshot was taken from. The program is not in the snapshot: a realm
// stores it once, beside the instance, instead of once per pause.
func (m *Machine) Restore(b []byte) error {
r := vmkit.NewReader(b)
if r.Uint32() != snapMagic {
return vmkit.ErrBadSnapshot
}
if r.Byte() != snapVersion {
return vmkit.ErrBadSnapshot
}
pc := int(r.Int())
ptr := int(r.Int())
inPos := int(r.Int())
status := vmkit.Status(r.Byte())
trap := r.String()
tape := r.Bytes()
if err := r.Err(); err != nil {
return err
}
if len(tape) > TapeSize || ptr < 0 || ptr >= TapeSize || inPos < 0 {
return vmkit.ErrBadSnapshot
}
if m.prog != nil && (pc < 0 || pc > len(m.prog.ops)) {
return vmkit.ErrBadSnapshot
}
m.pc, m.ptr, m.inPos = pc, ptr, inPos
m.status, m.trap = status, trap
// Zero only what this machine could have written: hi bounds every
// write it has made, and a 30,000 element composite literal is not
// something to put in a restore path.
for i := 0; i <= m.hi && i < TapeSize; i++ {
m.tape[i] = 0
}
copy(m.tape[:], tape)
m.hi = len(tape) - 1
if m.hi < 0 {
m.hi = 0
}
return nil
}
// Run compiles src at [Default] and runs it to completion against h, with no
// fuel bound. It is the one-shot path: convenient for a test or a small
// program, and exactly the thing a realm should not do with untrusted input.
func Run(src string, h vmkit.Host) (vmkit.Status, error) {
m, err := Load(src)
if err != nil {
return vmkit.Trapped, err
}
_, status := m.Step(h, vmkit.Unmetered)
return status, nil
}
// wrap folds a tape index into range, the way the naive interpreter does one
// step at a time.
func wrap(i int) int {
i %= TapeSize
if i < 0 {
i += TapeSize
}
return i
}
machine_test.gno
package bf
import (
"testing"
"gno.land/p/nym-moultest123/x/vm/vmkit/v0"
"gno.land/p/nt/uassert/v0"
)
// oneShot runs src to completion and returns what it wrote.
func oneShot(t *testing.T, src string) string {
t.Helper()
h := vmkit.NewTestHost()
status, err := Run(src, h)
uassert.NoError(t, err)
uassert.Equal(t, "halted", status.String())
return h.OutString()
}
// TestSlicedRunEqualsOneShot is the property that makes a guest program a
// contract rather than a function call: chopping the execution into fuel
// slices, snapshotting between each, must produce exactly the single run.
func TestSlicedRunEqualsOneShot(t *testing.T) {
for _, slice := range []int64{1, 2, 7, 64} {
prog, err := CompileDefault(hello)
uassert.NoError(t, err)
h := vmkit.NewTestHost()
snap := []byte(nil)
status := vmkit.Running
slices := 0
for status == vmkit.Running && slices < 10000 {
m := NewMachine(prog) // a realm holds bytes, not a machine
if snap != nil {
uassert.NoError(t, m.Restore(snap))
}
_, status = m.Step(h, slice)
snap = m.Snapshot()
slices++
}
uassert.Equal(t, "halted", status.String())
uassert.Equal(t, "Hello World", h.OutString())
}
}
func TestSlicedRunAgreesAcrossTheCorpus(t *testing.T) {
for _, tc := range corpus {
prog, err := CompileDefault(tc.src)
uassert.NoError(t, err)
if prog == nil {
continue
}
h := vmkit.NewTestHost()
snap := []byte(nil)
status := vmkit.Running
n := 0
for status == vmkit.Running && n < 20000 {
m := NewMachine(prog)
if snap != nil {
uassert.NoError(t, m.Restore(snap))
}
_, status = m.Step(h, 3)
snap = m.Snapshot()
n++
}
if h.OutString() != tc.want {
t.Errorf("%s sliced: got %q, want %q", tc.name, h.OutString(), tc.want)
}
}
}
func TestFuelStopsTheMachine(t *testing.T) {
prog, err := CompileDefault(hello)
uassert.NoError(t, err)
m := NewMachine(prog)
h := vmkit.NewTestHost()
used, status := m.Step(h, 5)
uassert.Equal(t, int64(5), used)
uassert.Equal(t, "running", status.String())
uassert.Equal(t, "", h.OutString()) // not far enough to print anything
}
// TestScanIsChargedPerCell pins the thing that would otherwise be a way to
// buy unbounded work for one unit: a scan walks one cell per unit of fuel,
// and stopping mid-scan resumes the same walk.
func TestScanIsChargedPerCell(t *testing.T) {
// 20 non-zero cells, then scan left back to the zero at cell 0.
src := ">+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+>+[<]"
prog, err := CompileDefault(src)
uassert.NoError(t, err)
m := NewMachine(prog)
h := vmkit.NewTestHost()
used, status := m.Step(h, 45)
uassert.Equal(t, int64(45), used)
uassert.Equal(t, "running", status.String())
uassert.True(t, m.Pointer() > 0) // stopped part way down the scan
// Resuming finishes the same walk and lands on the zero cell.
_, status = m.Step(h, vmkit.Unmetered)
uassert.Equal(t, "halted", status.String())
uassert.Equal(t, 0, m.Pointer())
}
func TestSnapshotRoundTrip(t *testing.T) {
prog, err := CompileDefault(hello)
uassert.NoError(t, err)
a := NewMachine(prog)
h := vmkit.NewTestHost()
a.Step(h, 40)
b := NewMachine(prog)
uassert.NoError(t, b.Restore(a.Snapshot()))
uassert.Equal(t, a.PC(), b.PC())
uassert.Equal(t, a.Pointer(), b.Pointer())
uassert.Equal(t, a.Touched(), b.Touched())
for i := 0; i < a.Touched(); i++ {
uassert.Equal(t, uint64(a.Cell(i)), uint64(b.Cell(i)))
}
uassert.Equal(t, string(a.Snapshot()), string(b.Snapshot()))
}
// TestSnapshotIsTrimmed is the continuation kill criterion in test form: if a
// pause carried the whole 30,000 byte tape, resuming would cost more than
// re-running and continuations would be theater.
func TestSnapshotIsTrimmed(t *testing.T) {
m, err := Load(hello)
uassert.NoError(t, err)
h := vmkit.NewTestHost()
m.Step(h, vmkit.Unmetered)
uassert.Equal(t, 5, m.Touched()) // hello world uses five cells
snap := m.Snapshot()
// 4 magic + 1 version + 3x8 zig-zag ints + 1 status + 4 empty trap
// + 4 length + 5 tape. The README quotes this number.
uassert.Equal(t, 43, len(snap))
uassert.True(t, len(snap) < TapeSize/100)
}
func TestRestoreRejectsJunk(t *testing.T) {
prog, err := CompileDefault(hello)
uassert.NoError(t, err)
good := NewMachine(prog)
good.Step(vmkit.NewTestHost(), 20)
snap := good.Snapshot()
cases := []struct {
name string
b []byte
}{
{"empty", []byte{}},
{"truncated", snap[:len(snap)-3]},
{"bad magic", append([]byte{0, 0, 0, 0}, snap[4:]...)},
}
for _, tc := range cases {
m := NewMachine(prog)
if err := m.Restore(tc.b); err == nil {
t.Errorf("Restore(%s) should have failed", tc.name)
}
}
// A snapshot with a wrong version byte is refused rather than decoded
// into a plausible-looking wrong state.
bad := make([]byte, len(snap))
copy(bad, snap)
bad[4] = 99
m := NewMachine(prog)
uassert.ErrorIs(t, m.Restore(bad), vmkit.ErrBadSnapshot)
}
func TestRestoreRejectsAnOutOfRangePC(t *testing.T) {
small, err := CompileDefault("+")
uassert.NoError(t, err)
big, err := CompileDefault(hello)
uassert.NoError(t, err)
m := NewMachine(big)
m.Step(vmkit.NewTestHost(), 30)
snap := m.Snapshot()
// The same snapshot against a two-op program points past the end.
other := NewMachine(small)
uassert.ErrorIs(t, other.Restore(snap), vmkit.ErrBadSnapshot)
}
func TestHaltedMachineStaysHalted(t *testing.T) {
m, err := Load("+++.")
uassert.NoError(t, err)
h := vmkit.NewTestHost()
m.Step(h, vmkit.Unmetered)
uassert.Equal(t, "halted", m.Status().String())
used, status := m.Step(h, vmkit.Unmetered)
uassert.Equal(t, int64(0), used)
uassert.Equal(t, "halted", status.String())
uassert.Equal(t, "\x03", h.OutString()) // still only one write
}
func TestLoadRejectsBadSource(t *testing.T) {
_, err := Load("[[")
uassert.Error(t, err)
status, err := Run("]", vmkit.NewTestHost())
uassert.Error(t, err)
uassert.Equal(t, "trapped", status.String())
}
// TestInstanceIntegration wires the machine through vmkit's realm-facing
// plumbing, which is the shape the demo realm uses.
func TestInstanceIntegration(t *testing.T) {
prog, err := CompileDefault(hello)
uassert.NoError(t, err)
inst := vmkit.NewInstance("001", address("g1x"), VMName, []byte(hello), vmkit.Unmetered)
h := vmkit.NewTestHost()
for i := 0; i < 200 && inst.Status == vmkit.Running; i++ {
uassert.NoError(t, inst.Run(NewMachine(prog), h, 8))
}
uassert.Equal(t, "halted", inst.Status.String())
uassert.Equal(t, "Hello World", h.OutString())
uassert.True(t, inst.Slices > 1)
uassert.True(t, inst.FuelUsed > 0)
}
func TestInstanceHonoursItsBudget(t *testing.T) {
prog, err := CompileDefault(hello)
uassert.NoError(t, err)
inst := vmkit.NewInstance("002", address("g1x"), VMName, []byte(hello), 10)
h := vmkit.NewTestHost()
uassert.NoError(t, inst.Run(NewMachine(prog), h, vmkit.Unmetered))
uassert.Equal(t, "out of fuel", inst.Status.String())
uassert.Equal(t, int64(10), inst.FuelUsed)
uassert.ErrorIs(t, inst.Run(NewMachine(prog), h, vmkit.Unmetered), vmkit.ErrBudgetExhausted)
}
micro_test.gno
package bf
import (
"testing"
"gno.land/p/nym-moultest123/x/vm/vmkit/v0"
)
// The microarchitecture matrix.
//
// The rungs in ladder_test.gno are the classic interpreter optimizations:
// fewer instructions for the same program. These are the other axis, and on
// the GnoVM they matter as much: the same instruction stream, executed by
// loops that differ from each other by exactly one line.
//
// They are deliberately simplified (no host, no snapshot, no scan) so that
// the one line is the only difference. They are comparable to each other and
// not to the shipped machine, which does more. What the shipped machine took
// from them is documented on [Machine.Step].
type vm struct {
prog *Program
tape [TapeSize]byte
ptr int
pc int
}
// V0: cursors as struct fields. No meter, no bounds check, no defer.
func (m *vm) runFields() int64 {
ops := m.prog.ops
var used int64
for {
used++
switch ops[m.pc].code {
case opAdd:
m.tape[m.ptr] += byte(ops[m.pc].arg)
case opMove:
m.ptr = wrap(m.ptr + ops[m.pc].arg)
case opSet:
m.tape[m.ptr] = byte(ops[m.pc].arg)
case opAddMul:
if v := m.tape[m.ptr]; v != 0 {
m.tape[wrap(m.ptr+ops[m.pc].off)] += v * byte(ops[m.pc].arg)
}
case opJmpZ:
if m.tape[m.ptr] == 0 {
m.pc = ops[m.pc].arg
}
case opJmpNZ:
if m.tape[m.ptr] != 0 {
m.pc = ops[m.pc].arg
}
case opHalt:
return used
}
m.pc++
}
}
// V1: V0 with the two cursors hoisted into locals. Only change.
func (m *vm) runLocals() int64 {
ops := m.prog.ops
pc, ptr := m.pc, m.ptr
var used int64
for {
used++
switch ops[pc].code {
case opAdd:
m.tape[ptr] += byte(ops[pc].arg)
case opMove:
ptr = wrap(ptr + ops[pc].arg)
case opSet:
m.tape[ptr] = byte(ops[pc].arg)
case opAddMul:
if v := m.tape[ptr]; v != 0 {
m.tape[wrap(ptr+ops[pc].off)] += v * byte(ops[pc].arg)
}
case opJmpZ:
if m.tape[ptr] == 0 {
pc = ops[pc].arg
}
case opJmpNZ:
if m.tape[ptr] != 0 {
pc = ops[pc].arg
}
case opHalt:
m.pc, m.ptr = pc, ptr
return used
}
pc++
}
}
// V2: V1 plus a vmkit.Meter charged once per op. Only change.
func (m *vm) runLocalsMeter(fuel int64) int64 {
ops := m.prog.ops
meter := vmkit.NewMeter(fuel)
pc, ptr := m.pc, m.ptr
for {
if !meter.Charge(1) {
m.pc, m.ptr = pc, ptr
return meter.Used()
}
switch ops[pc].code {
case opAdd:
m.tape[ptr] += byte(ops[pc].arg)
case opMove:
ptr = wrap(ptr + ops[pc].arg)
case opSet:
m.tape[ptr] = byte(ops[pc].arg)
case opAddMul:
if v := m.tape[ptr]; v != 0 {
m.tape[wrap(ptr+ops[pc].off)] += v * byte(ops[pc].arg)
}
case opJmpZ:
if m.tape[ptr] == 0 {
pc = ops[pc].arg
}
case opJmpNZ:
if m.tape[ptr] != 0 {
pc = ops[pc].arg
}
case opHalt:
m.pc, m.ptr = pc, ptr
return meter.Used()
}
pc++
}
}
// V3: V1 plus an inline fuel counter instead of the Meter object. Isolates
// the cost of the method call from the cost of metering at all.
func (m *vm) runLocalsInlineFuel(fuel int64) int64 {
ops := m.prog.ops
pc, ptr := m.pc, m.ptr
var used int64
for {
if used >= fuel {
m.pc, m.ptr = pc, ptr
return used
}
used++
switch ops[pc].code {
case opAdd:
m.tape[ptr] += byte(ops[pc].arg)
case opMove:
ptr = wrap(ptr + ops[pc].arg)
case opSet:
m.tape[ptr] = byte(ops[pc].arg)
case opAddMul:
if v := m.tape[ptr]; v != 0 {
m.tape[wrap(ptr+ops[pc].off)] += v * byte(ops[pc].arg)
}
case opJmpZ:
if m.tape[ptr] == 0 {
pc = ops[pc].arg
}
case opJmpNZ:
if m.tape[ptr] != 0 {
pc = ops[pc].arg
}
case opHalt:
m.pc, m.ptr = pc, ptr
return used
}
pc++
}
}
// V4: V3 with the tape as a local slice instead of an array field. Only
// change, so this settles the "a fixed array removes a bounds check" claim.
func (m *vm) runLocalsInlineFuelSliceTape(fuel int64) int64 {
ops := m.prog.ops
tape := make([]byte, TapeSize)
pc, ptr := m.pc, m.ptr
var used int64
for {
if used >= fuel {
m.pc, m.ptr = pc, ptr
return used
}
used++
switch ops[pc].code {
case opAdd:
tape[ptr] += byte(ops[pc].arg)
case opMove:
ptr = wrap(ptr + ops[pc].arg)
case opSet:
tape[ptr] = byte(ops[pc].arg)
case opAddMul:
if v := tape[ptr]; v != 0 {
tape[wrap(ptr+ops[pc].off)] += v * byte(ops[pc].arg)
}
case opJmpZ:
if tape[ptr] == 0 {
pc = ops[pc].arg
}
case opJmpNZ:
if tape[ptr] != 0 {
pc = ops[pc].arg
}
case opHalt:
m.pc, m.ptr = pc, ptr
return used
}
pc++
}
}
func microProg(lvl Level) *Program {
p, err := Compile(heavy, lvl)
if err != nil {
panic(err)
}
return p
}
// Rung 1's instruction stream, 121,202 ops, under each loop.
func TestMicroJumpsCursorsAsFields(t *testing.T) {
(&vm{prog: microProg(LevelJumps)}).runFields()
}
func TestMicroJumpsCursorsInLocals(t *testing.T) {
(&vm{prog: microProg(LevelJumps)}).runLocals()
}
func TestMicroJumpsMeterPerOp(t *testing.T) {
(&vm{prog: microProg(LevelJumps)}).runLocalsMeter(vmkit.Unmetered)
}
func TestMicroJumpsInlineFuel(t *testing.T) {
(&vm{prog: microProg(LevelJumps)}).runLocalsInlineFuel(1 << 40)
}
// Rung 3's instruction stream, 1,203 ops, under the same loops.
func TestMicroJumpsSliceTape(t *testing.T) {
(&vm{prog: microProg(LevelJumps)}).runLocalsInlineFuelSliceTape(1 << 40)
}
func TestMicroIdiomsCursorsAsFields(t *testing.T) {
(&vm{prog: microProg(LevelIdioms)}).runFields()
}
func TestMicroIdiomsCursorsInLocals(t *testing.T) {
(&vm{prog: microProg(LevelIdioms)}).runLocals()
}
func TestMicroIdiomsMeterPerOp(t *testing.T) {
(&vm{prog: microProg(LevelIdioms)}).runLocalsMeter(vmkit.Unmetered)
}
func TestMicroIdiomsInlineFuel(t *testing.T) {
(&vm{prog: microProg(LevelIdioms)}).runLocalsInlineFuel(1 << 40)
}
func TestMicroIdiomsSliceTape(t *testing.T) {
(&vm{prog: microProg(LevelIdioms)}).runLocalsInlineFuelSliceTape(1 << 40)
}