government

commit bb4fd939071a383f99c69ff44ab41ee227afef87

tree

parent:
85540daf315b2c9c2d0ade2cb4f2d1fb8249ecdc

nmyk <nick@nmyk.io>

2026-11-14T11:03:17-05:00

add boilerplate, Value, Print

diff --git a/Makefile b/Makefile
new file mode 100644
index 0000000000000000000000000000000000000000..95047882cff6075133c17a679014bd9f299233ec
--- /dev/null
+++ b/Makefile
@@ -0,0 +1,13 @@
+.PHONY: check test vet fmt
+
+check: fmt vet test
+
+test:
+	go test ./...
+
+vet:
+	go vet ./...
+
+fmt:
+	@unformatted="$$(gofmt -l .)"; \
+	if [ -n "$$unformatted" ]; then echo "gofmt needed:"; echo "$$unformatted"; exit 1; fi
\ No newline at end of file
diff --git a/cmd/government/main.go b/cmd/government/main.go
new file mode 100644
index 0000000000000000000000000000000000000000..a6b99a21b0548a6fb159734cc27532d965408d50
--- /dev/null
+++ b/cmd/government/main.go
@@ -0,0 +1,26 @@
+// Command government runs GOVERNMENT programs.
+//
+// Only the usage message exists so far. The subcommands (run, verify, tree,
+// decompile, compile, repeal) arrive in later steps of PLAN.md.
+package main
+
+import (
+	"fmt"
+	"os"
+)
+
+const usage = `usage: government <command> [arguments]
+
+commands (not yet implemented):
+  run        ratify, decode and evaluate a .gov program
+  verify     ratify and decode only
+  tree       print the policy tree
+  decompile  print equivalent Lisp source
+  compile    transpile Lisp source to .gov
+  repeal     write a CRL repealing one depth of a program
+`
+
+func main() {
+	fmt.Fprint(os.Stderr, usage)
+	os.Exit(2)
+}
diff --git a/eval/doc.go b/eval/doc.go
new file mode 100644
index 0000000000000000000000000000000000000000..359616321216ae12dda24c91911472d00566518e
--- /dev/null
+++ b/eval/doc.go
@@ -0,0 +1,2 @@
+// Package eval evaluates GOVERNMENT programs over sexpr values.
+package eval
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000000000000000000000000000000000000..81389d6b8ad42fd056b61e099fd6ad3d81a91ebc
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,3 @@
+module government
+
+go 1.24
diff --git a/sexpr/doc.go b/sexpr/doc.go
new file mode 100644
index 0000000000000000000000000000000000000000..14e577f00c6ed7b7676c64674bca629393e50d9b
--- /dev/null
+++ b/sexpr/doc.go
@@ -0,0 +1,4 @@
+// Package sexpr defines GOVERNMENT's values and their text form. The reader
+// produces the same values the evaluator computes with (code is data), so
+// the transpiler, decompiler and tests share one representation.
+package sexpr
diff --git a/sexpr/print.go b/sexpr/print.go
new file mode 100644
index 0000000000000000000000000000000000000000..ee63d41d751c5857759453637a99c3df4e01cbcb
--- /dev/null
+++ b/sexpr/print.go
@@ -0,0 +1,121 @@
+package sexpr
+
+import (
+	"fmt"
+	"math"
+	"strconv"
+	"strings"
+)
+
+// Print returns the text form of v. For everything except functions, the
+// output reads back (step 1.4) as an equal value.
+func Print(v Value) string {
+	var b strings.Builder
+	write(&b, v)
+	return b.String()
+}
+
+func write(b *strings.Builder, v Value) {
+	switch v := v.(type) {
+	case Int:
+		b.WriteString(strconv.FormatInt(int64(v), 10))
+	case Float:
+		b.WriteString(formatFloat(float64(v)))
+	case String:
+		writeString(b, string(v))
+	case Bool:
+		if v {
+			b.WriteString("T")
+		} else {
+			b.WriteString("F")
+		}
+	case Symbol:
+		b.WriteString(string(v))
+	case Empty:
+		b.WriteString("()")
+	case *Pair:
+		writePair(b, v)
+	case Function:
+		if name := v.Name(); name != "" {
+			fmt.Fprintf(b, "#<builtin %s>", name)
+		} else {
+			b.WriteString("#<lambda>")
+		}
+	default:
+		panic(fmt.Sprintf("sexpr: unknown value type %T", v))
+	}
+}
+
+// writePair loops along the cdr chain and recurses only into cars, so stack
+// depth follows nesting, not list length.
+func writePair(b *strings.Builder, p *Pair) {
+	b.WriteByte('(')
+	write(b, p.Car)
+	rest := p.Cdr
+	for {
+		switch r := rest.(type) {
+		case *Pair:
+			b.WriteByte(' ')
+			write(b, r.Car)
+			rest = r.Cdr
+			continue
+		case Empty:
+		default:
+			b.WriteString(" . ")
+			write(b, r)
+		}
+		break
+	}
+	b.WriteByte(')')
+}
+
+// formatFloat guarantees a dot in the mantissa, because the reader's float
+// grammar requires one: "1" would read back as an Int. Magnitudes outside
+// [1e-6, 1e21) use an exponent, as JavaScript does (1e21 prints as
+// "1.0e+21").
+func formatFloat(f float64) string {
+	if math.IsNaN(f) || math.IsInf(f, 0) {
+		// Unreachable from the evaluator; must not print as a readable value.
+		return fmt.Sprintf("#<float %v>", f)
+	}
+
+	abs := math.Abs(f)
+	format := byte('f')
+	if abs != 0 && (abs < 1e-6 || abs >= 1e21) {
+		format = 'e'
+	}
+	s := strconv.FormatFloat(f, format, -1, 64)
+
+	mantissa, exponent, _ := strings.Cut(s, "e")
+	if !strings.Contains(mantissa, ".") {
+		mantissa += ".0"
+	}
+	if exponent != "" {
+		return mantissa + "e" + exponent
+	}
+	return mantissa
+}
+
+// writeString uses the reader's escapes: short forms for quote, backslash,
+// newline and tab, \u{hex} for other control characters, and raw UTF-8 for
+// everything else.
+func writeString(b *strings.Builder, s string) {
+	b.WriteByte('"')
+	for _, r := range s {
+		switch {
+		case r == '"':
+			b.WriteString(`\"`)
+		case r == '\\':
+			b.WriteString(`\\`)
+		case r == '\n':
+			b.WriteString(`\n`)
+		case r == '\t':
+			b.WriteString(`\t`)
+		case r < 0x20 || r == 0x7f:
+			fmt.Fprintf(b, `\u{%x}`, r)
+		default:
+			b.WriteRune(r)
+		}
+	}
+	b.WriteByte('"')
+}
diff --git a/sexpr/print_test.go b/sexpr/print_test.go
new file mode 100644
index 0000000000000000000000000000000000000000..8d503f668b027534a2e10eee07dca695db5f631c
--- /dev/null
+++ b/sexpr/print_test.go
@@ -0,0 +1,87 @@
+package sexpr
+
+import (
+	"math"
+	"testing"
+)
+
+type testFunc struct{ name string }
+
+func (testFunc) isValue()       {}
+func (f testFunc) Name() string { return f.name }
+
+func TestPrint(t *testing.T) {
+	tests := []struct {
+		name  string
+		value Value
+		want  string
+	}{
+		{"zero", Int(0), "0"},
+		{"negative int", Int(-42), "-42"},
+		{"max int", Int(math.MaxInt64), "9223372036854775807"},
+		{"min int", Int(math.MinInt64), "-9223372036854775808"},
+
+		// Floats always carry a dot so they never read back as Ints.
+		{"whole float", Float(1), "1.0"},
+		{"fraction", Float(3.14), "3.14"},
+		{"negative float", Float(-0.5), "-0.5"},
+		{"zero float", Float(0), "0.0"},
+		{"negative zero", Float(math.Copysign(0, -1)), "-0.0"},
+		{"large float", Float(1e20), "100000000000000000000.0"},
+		{"huge float", Float(1e21), "1.0e+21"},
+		{"tiny float", Float(1.5e-7), "1.5e-07"},
+		{"shortest digits", Float(0.1), "0.1"},
+		{"empty string", String(""), `""`},
+		{"plain string", String("hello"), `"hello"`},
+		{"quote escape", String(`a"b`), `"a\"b"`},
+		{"backslash escape", String(`a\b`), `"a\\b"`},
+		{"newline and tab", String("a\nb\tc"), `"a\nb\tc"`},
+		{"other control char", String("bell\a"), `"bell\u{7}"`},
+		{"unicode kept as is", String("héllo 😀"), `"héllo 😀"`},
+		{"true", T, "T"},
+		{"false", F, "F"},
+		{"symbol", Symbol("foo"), "foo"},
+		{"operator symbol", Symbol("+"), "+"},
+		{"empty list", Nil, "()"},
+		{"one element", List(Int(1)), "(1)"},
+		{"proper list", List(Int(1), Int(2), Int(3)), "(1 2 3)"},
+		{"mixed list", List(Symbol("+"), Int(1), Float(2), String("x")), `(+ 1 2.0 "x")`},
+		{"nested list", List(Int(1), List(Int(2), Int(3)), Nil), "(1 (2 3) ())"},
+		{"list of empty", List(Nil), "(())"},
+		{"dotted pair", Cons(Int(1), Int(2)), "(1 . 2)"},
+		{"improper list", ListWithTail(Int(3), Int(1), Int(2)), "(1 2 . 3)"},
+		{"pair of lists", Cons(List(Int(1)), List(Int(2))), "((1) 2)"},
+		{"dotted to symbol", Cons(Symbol("a"), Symbol("b")), "(a . b)"},
+		{"quote form", List(Symbol("quote"), Symbol("x")), "(quote x)"},
+		{"builtin", testFunc{"+"}, "#<builtin +>"},
+		{"closure", testFunc{""}, "#<lambda>"},
+	}
+	for _, tt := range tests {
+		t.Run(tt.name, func(t *testing.T) {
+			if got := Print(tt.value); got != tt.want {
+				t.Errorf("Print() = %s, want %s", got, tt.want)
+			}
+		})
+	}
+}
+
+func TestListHelpers(t *testing.T) {
+	if List() != Value(Nil) {
+		t.Errorf("List() = %s, want ()", Print(List()))
+	}
+	if got := ListWithTail(Int(9)); got != Value(Int(9)) {
+		t.Errorf("ListWithTail with no items = %s, want 9", Print(got))
+	}
+}
+
+// Guards writePair against recursing on cdrs.
+func TestPrintLongList(t *testing.T) {
+	items := make([]Value, 1_000_000)
+	for i := range items {
+		items[i] = Int(0)
+	}
+	got := Print(List(items...))
+	if want := 2*len(items) + 1; len(got) != want {
+		t.Errorf("printed length = %d, want %d", len(got), want)
+	}
+}
diff --git a/sexpr/value.go b/sexpr/value.go
new file mode 100644
index 0000000000000000000000000000000000000000..56a5907da89bea768340526d1c159a1dc1ce4b0d
--- /dev/null
+++ b/sexpr/value.go
@@ -0,0 +1,75 @@
+package sexpr
+
+// Value is any GOVERNMENT value. The interface is sealed by isValue, except
+// for Function, which package eval implements.
+type Value interface {
+	isValue()
+}
+
+// Int overflow is an error raised by the evaluator, never wraparound.
+type Int int64
+
+// Float is always finite: operations that would produce NaN or an infinity
+// are errors.
+type Float float64
+
+// String holds UTF-8; character counts (strlen) are in runes, not bytes.
+type String string
+
+// Bool is T or F. For truthiness only F is false; every other value,
+// including 0 and (), is true.
+type Bool bool
+
+// Symbol equality is name equality, so a string type is already interned.
+type Symbol string
+
+// Pair is a cons cell. A list is a chain of pairs whose last cdr is Nil;
+// any other final cdr makes an improper (dotted) list.
+//
+// Pairs are immutable, so no pair can reach itself: every list is finite
+// and acyclic, and the printer and equality never need cycle detection.
+type Pair struct {
+	Car, Cdr Value
+}
+
+type Empty struct{}
+
+// Nil is the empty list, ().
+var Nil = Empty{}
+
+// Function is implemented by eval's closures and builtins.
+type Function interface {
+	Value
+	// Name is the builtin's name, or "" for a closure.
+	Name() string
+}
+
+func (Int) isValue()    {}
+func (Float) isValue()  {}
+func (String) isValue() {}
+func (Bool) isValue()   {}
+func (Symbol) isValue() {}
+func (*Pair) isValue()  {}
+func (Empty) isValue()  {}
+
+const (
+	T = Bool(true)
+	F = Bool(false)
+)
+
+func Cons(car, cdr Value) *Pair {
+	return &Pair{Car: car, Cdr: cdr}
+}
+
+func List(items ...Value) Value {
+	return ListWithTail(Nil, items...)
+}
+
+// ListWithTail(Int(3), Int(1), Int(2)) is (1 2 . 3).
+func ListWithTail(tail Value, items ...Value) Value {
+	result := tail
+	for i := len(items) - 1; i >= 0; i-- {
+		result = Cons(items[i], result)
+	}
+	return result
+}