government

commit 675167640370859e58d24a1f76126760c2e61968

tree

parent:
a94ce18dbaa3c27d01f1491d51ec12c5767daf6d

nmyk <nick@nmyk.io>

2026-11-15T15:35:38-05:00

improve tree printer

diff --git a/SPEC.md b/SPEC.md
index 559d386a64f696b8b63f89345bfaf27d437299e4..1c4d00e4c72fa0fa15d24a942a0edb0833545ff5 100644
--- a/SPEC.md
+++ b/SPEC.md
@@ -523,26 +523,28 @@ | 1           | `GOV.0.1.1`         | `GOV.0.1.1` → `GOV.0.2.21`, `GOV.0.1.1` → `GOV.2.3.49`, `GOV.0.1.1` → `GOV.0.4.1`  |
 | 2           | `anyPolicy`         | `GOV.0.4.1` → `GOV.0.5.23`, `GOV.0.4.1` → `GOV.2.6.50`, `GOV.0.4.1` → `GOV.2.7.51` |
 | 3           | `anyPolicy`         | None                                                                               |
 
-Policy processing makes this graph. A `'` marks a copy:
+Policy processing makes this graph, as `government tree` prints it. Each line
+gives the depth, the node (`()` for a list node), its id and its OID. A `'`
+after the id marks a copy:
 
 ```
-depth 0  anyPolicy
-depth 1  `-- (...)#1       GOV.0.1.1
-depth 2      |-- +#2       GOV.0.2.21
-depth 3      |   `-- +#2'  copy
-depth 2      |-- 1#3       GOV.2.3.49
-depth 3      |   `-- 1#3'  copy
-depth 2      `-- (...)#4   GOV.0.4.1
-depth 3          |-- *#5   GOV.0.5.23
-depth 3          |-- 2#6   GOV.2.6.50
-depth 3          `-- 3#7   GOV.2.7.51
+depth 0 anyPolicy
+depth 1 `-- ()         1  GOV.0.1.1
+depth 2     |-- +      2  GOV.0.2.21
+depth 3     |   `-- +  2' copy
+depth 2     |-- 1      3  GOV.2.3.49
+depth 3     |   `-- 1  3' copy
+depth 2     `-- ()     4  GOV.0.4.1
+depth 3         |-- *  5  GOV.0.5.23
+depth 3         |-- 2  6  GOV.2.6.50
+depth 3         `-- 3  7  GOV.2.7.51
 ```
 
 Certificate 1's policy attaches to the root. In certificate 2, `anyPolicy` makes
-the three nodes that #1 expects. In certificate 3, it makes the three nodes that
-#4 expects, and copies `+` and `1`, which expect only themselves. Nothing is
-pruned. Decoding skips the copies and gives `(+ 1 (* 2 3))`, which evaluates to
-`7`.
+the three nodes that node 1 expects. In certificate 3, it makes the three nodes
+that node 4 expects, and copies `+` and `1`, which expect only themselves.
+Nothing is pruned. Decoding skips the copies and gives `(+ 1 (* 2 3))`, which
+evaluates to `7`.
 
 ## Repeal
 
diff --git a/src/cmd/government/inspect.go b/src/cmd/government/inspect.go
index d1d5761bd44e2acf5e3f49da83c40226bcb39388..92ee8dfd2cb4b129c18d1860944166af8ad7ec8a 100644
--- a/src/cmd/government/inspect.go
+++ b/src/cmd/government/inspect.go
@@ -15,6 +15,7 @@ // show a graph whose shape the decoder would reject. That makes it the
 // tool for looking at a broken program.
 func newTreeCmd() *cobra.Command {
 	var lf loadFlags
+	var draw policy.DrawOptions
 	cmd := &cobra.Command{
 		Use:   "tree prog.gov",
 		Short: "Print the policy tree",
@@ -34,11 +35,12 @@ 			g, err := policy.Program(certs, policy.Options{MaxNodes: opts.MaxNodes})
 			if err != nil {
 				return refused("%s: %v", path, err)
 			}
-			fmt.Fprint(cmd.OutOrStdout(), g.Draw())
+			fmt.Fprint(cmd.OutOrStdout(), g.Draw(draw))
 			return nil
 		},
 	}
 	lf = addLoadFlags(cmd.Flags())
+	cmd.Flags().BoolVar(&draw.NoCopies, "no-copies", false, "leave out the copies that carry atoms down to the bottom")
 	return cmd
 }
 
diff --git a/src/cmd/government/inspect_test.go b/src/cmd/government/inspect_test.go
index 007b23c76249b86a52c616e3fd3a8813d765c3a0..43abf713df262d6d6454608a2077b44e06dca921 100644
--- a/src/cmd/government/inspect_test.go
+++ b/src/cmd/government/inspect_test.go
@@ -11,10 +11,18 @@ 	code, stdout, stderr := runCmd("tree", gov)
 	if code != exitOK {
 		t.Fatalf("exit %d: %s", code, stderr)
 	}
-	for _, want := range []string{"depth 0  anyPolicy\n", "`-- (...)#1", "+#2'  copy", "`-- 3#7   GOV.2.7.51\n"} {
+	for _, want := range []string{"depth 0 anyPolicy\n", "`-- ()         1  GOV.0.1.1\n", "`-- +  2' copy\n", "`-- 3  7  GOV.2.7.51\n"} {
 		if !strings.Contains(stdout, want) {
 			t.Errorf("missing %q in\n%s", want, stdout)
 		}
+	}
+
+	code, stdout, stderr = runCmd("tree", "--no-copies", gov)
+	if code != exitOK {
+		t.Fatalf("--no-copies: exit %d: %s", code, stderr)
+	}
+	if strings.Contains(stdout, "copy") || strings.Count(stdout, "\n") != 8 {
+		t.Errorf("--no-copies still shows copies:\n%s", stdout)
 	}
 }
 
diff --git a/src/policy/draw.go b/src/policy/draw.go
index a77567ca28846603b89d6ee81dc4d9717047b7fa..b353fdf0b296120fe77cb93343ef38dc7a2dee83 100644
--- a/src/policy/draw.go
+++ b/src/policy/draw.go
@@ -8,38 +8,50 @@ 	"strconv"
 	"strings"
 
 	"nmyk.io/government/ast"
+	"nmyk.io/government/builtin"
 	"nmyk.io/government/sexpr"
 )
 
+// DrawOptions controls Draw.
+type DrawOptions struct {
+	// NoCopies leaves out the copies, so only the program's own nodes are
+	// drawn.
+	NoCopies bool
+}
+
 // Draw prints the graph as a tree, one node per line, with each node's
-// depth, its decoded label and its OID:
+// depth, its decoded label, its id and its OID:
 //
-//	depth 1  `-- (...)#1     GOV.0.1.1
-//	depth 2      |-- +#2     GOV.0.2.21
-//	depth 3      |   `-- +#2'  copy
+//	depth 1 `-- ()         1  GOV.0.1.1
+//	depth 2     |-- +      2  GOV.0.2.21
+//	depth 3     |   `-- +  2' copy
 //
-// A trailing ' marks a copy the validator made, which carries an atom down
-// to the bottom; a chain of copies is one line giving the depths it spans.
-// A node with several parents is drawn in full under the first and named
-// again, without its children, under the others. A note follows its node's
-// OID after a ";", with its line breaks shown as " / ".
-func (g *Graph) Draw() string {
+// A list node is drawn as (). A ' after the id marks a copy the validator
+// made, which carries an atom down to the bottom; a chain of copies is one
+// line giving the depths it spans. A node with several parents is drawn in
+// full under the first and named again, without its children, under the
+// others. A note follows its node's OID after a ";", with its line breaks
+// shown as " / ".
+func (g *Graph) Draw(opts DrawOptions) string {
 	type line struct {
-		depth       int
-		tree, where string
+		depth           int
+		tree, id, where string
+		copy            bool
 	}
 	var lines []line
 	drawn := map[*Node]bool{}
 
 	var walk func(n *Node, parent *Node, prefix, branch string)
 	walk = func(n *Node, parent *Node, prefix, branch string) {
-		label, where := describe(n, parent)
+		d := describe(n, parent)
+		l := line{depth: n.Depth, tree: prefix + branch + d.label, id: d.id, where: d.where, copy: d.copy}
 		if drawn[n] {
-			lines = append(lines, line{n.Depth, prefix + branch + label, where + "  (shared, drawn above)"})
+			l.where += "  (shared, drawn above)"
+			lines = append(lines, l)
 			return
 		}
 		drawn[n] = true
-		if where == "copy" {
+		if d.copy {
 			// A copy can only have more copies of itself below it, down to
 			// the bottom; one line says how far the chain goes.
 			last := n
@@ -47,16 +59,22 @@ 			for len(last.Children) == 1 && last.Children[0].Policy.Equal(n.Policy) {
 				last = last.Children[0]
 			}
 			if last != n {
-				where = fmt.Sprintf("copy, depths %d-%d", n.Depth, last.Depth)
+				l.where = fmt.Sprintf("copy, depths %d-%d", n.Depth, last.Depth)
 			}
-			lines = append(lines, line{n.Depth, prefix + branch + label, where})
+			lines = append(lines, l)
 			return
 		}
 		if n.Note != "" {
-			where += "  ; " + strings.ReplaceAll(n.Note, "\n", " / ")
+			l.where += "  ; " + strings.ReplaceAll(n.Note, "\n", " / ")
+		}
+		lines = append(lines, l)
+		var children []*Node
+		for _, c := range n.Children {
+			if opts.NoCopies && c.Policy.Equal(n.Policy) {
+				continue
+			}
+			children = append(children, c)
 		}
-		lines = append(lines, line{n.Depth, prefix + branch + label, where})
-		children := slices.Clone(n.Children)
 		slices.SortStableFunc(children, func(a, b *Node) int { return cmp.Compare(nodeID(a), nodeID(b)) })
 		childPrefix := prefix
 		switch branch {
@@ -75,37 +93,56 @@ 		}
 	}
 	walk(g.Levels[0][0], nil, "", "")
 
-	width := 0
+	var depthWidth, treeWidth, idWidth int
 	for _, l := range lines {
-		width = max(width, len(l.tree))
+		depthWidth = max(depthWidth, len(strconv.Itoa(l.depth)))
+		treeWidth = max(treeWidth, len(l.tree))
+		idWidth = max(idWidth, len(l.id))
 	}
 	var b strings.Builder
 	for _, l := range lines {
-		row := fmt.Sprintf("depth %d  %-*s  %s", l.depth, width, l.tree, l.where)
+		row := fmt.Sprintf("depth %*d %s", depthWidth, l.depth, l.tree)
+		if l.id != "" || l.where != "" {
+			// The ' of a copy sits in the gap after the id, so ids stay
+			// aligned with and without it.
+			mark := " "
+			if l.copy {
+				mark = "'"
+			}
+			row = fmt.Sprintf("depth %*d %-*s  %*s%s %s", depthWidth, l.depth, treeWidth, l.tree, idWidth, l.id, mark, l.where)
+		}
 		b.WriteString(strings.TrimRight(row, " "))
 		b.WriteByte('\n')
 	}
 	return b.String()
 }
 
-// describe gives a node's label, e.g. +#2 or "hi"#11, and what to show
+type description struct {
+	label, id, where string
+	copy             bool
+}
+
+// describe gives a node's label, e.g. + or "hi", its id, and what to show
 // beside it: its OID, or "copy" for a copy of its parent.
-func describe(n, parent *Node) (label, where string) {
+func describe(n, parent *Node) description {
 	if n.Policy.Equal(AnyPolicy) {
-		return "anyPolicy", ""
+		return description{label: "anyPolicy"}
 	}
 	ns, id, text, err := ast.DecodeOID(n.Policy)
 	if err != nil {
-		return n.Policy.String(), "(not a GOVERNMENT node)"
+		return description{label: n.Policy.String(), where: "(not a GOVERNMENT node)"}
 	}
-	if ns == ast.NSString {
+	switch {
+	case ns == ast.NSString:
 		text = sexpr.Print(sexpr.String(text))
+	case ns == ast.NSBuiltin && text == builtin.ListNode:
+		text = "()"
 	}
-	label = text + "#" + strconv.FormatUint(id, 10)
+	d := description{label: text, id: strconv.FormatUint(id, 10), where: short(n.Policy)}
 	if parent != nil && parent.Policy.Equal(n.Policy) {
-		return label + "'", "copy"
+		d.copy, d.where = true, "copy"
 	}
-	return label, short(n.Policy)
+	return d
 }
 
 func nodeID(n *Node) uint64 {
diff --git a/src/policy/draw_test.go b/src/policy/draw_test.go
index f66b09b8b09d90efaaa9453f19043d261d3cb6cb..b097406d7ff6ead7397fc2e8ea69afdac1433730 100644
--- a/src/policy/draw_test.go
+++ b/src/policy/draw_test.go
@@ -7,18 +7,18 @@ )
 
 // TestDrawWorkedExample is the design doc's drawing of (+ 1 (* 2 3)).
 func TestDrawWorkedExample(t *testing.T) {
-	got := compiledGraph(t, "(+ 1 (* 2 3))").Draw()
+	got := compiledGraph(t, "(+ 1 (* 2 3))").Draw(DrawOptions{})
 	want := strings.Join([]string{
-		"depth 0  anyPolicy",
-		"depth 1  `-- (...)#1       GOV.0.1.1",
-		"depth 2      |-- +#2       GOV.0.2.21",
-		"depth 3      |   `-- +#2'  copy",
-		"depth 2      |-- 1#3       GOV.2.3.49",
-		"depth 3      |   `-- 1#3'  copy",
-		"depth 2      `-- (...)#4   GOV.0.4.1",
-		"depth 3          |-- *#5   GOV.0.5.23",
-		"depth 3          |-- 2#6   GOV.2.6.50",
-		"depth 3          `-- 3#7   GOV.2.7.51",
+		"depth 0 anyPolicy",
+		"depth 1 `-- ()         1  GOV.0.1.1",
+		"depth 2     |-- +      2  GOV.0.2.21",
+		"depth 3     |   `-- +  2' copy",
+		"depth 2     |-- 1      3  GOV.2.3.49",
+		"depth 3     |   `-- 1  3' copy",
+		"depth 2     `-- ()     4  GOV.0.4.1",
+		"depth 3         |-- *  5  GOV.0.5.23",
+		"depth 3         |-- 2  6  GOV.2.6.50",
+		"depth 3         `-- 3  7  GOV.2.7.51",
 		"",
 	}, "\n")
 	if got != want {
@@ -26,9 +26,41 @@ 		t.Errorf("got\n%s\nwant\n%s", got, want)
 	}
 }
 
+func TestDrawNoCopies(t *testing.T) {
+	got := compiledGraph(t, "(+ 1 (* 2 3))").Draw(DrawOptions{NoCopies: true})
+	want := strings.Join([]string{
+		"depth 0 anyPolicy",
+		"depth 1 `-- ()         1  GOV.0.1.1",
+		"depth 2     |-- +      2  GOV.0.2.21",
+		"depth 2     |-- 1      3  GOV.2.3.49",
+		"depth 2     `-- ()     4  GOV.0.4.1",
+		"depth 3         |-- *  5  GOV.0.5.23",
+		"depth 3         |-- 2  6  GOV.2.6.50",
+		"depth 3         `-- 3  7  GOV.2.7.51",
+		"",
+	}, "\n")
+	if got != want {
+		t.Errorf("got\n%s\nwant\n%s", got, want)
+	}
+}
+
+// Ids and depths with more digits keep their columns aligned.
+func TestDrawAlignsWideColumns(t *testing.T) {
+	got := compiledGraph(t, "(a (b (c (d (e (f (g (h (i (j)))))))))) (k l)").Draw(DrawOptions{NoCopies: true})
+	for _, want := range []string{
+		"depth  1 |-- ()                                          1  GOV.0.1.1",
+		"depth 11 |                                       `-- j  20  GOV.1.20.106",
+		"depth  2     `-- l                                      23  GOV.1.23.108",
+	} {
+		if !strings.Contains(got, want) {
+			t.Errorf("missing %q in\n%s", want, got)
+		}
+	}
+}
+
 func TestDrawLabelsAndSharing(t *testing.T) {
-	got := compiledGraph(t, `(f "hi" 2.5 'x)`).Draw()
-	for _, want := range []string{`"hi"#3`, "2.5#4", "quote#6", "x#7"} {
+	got := compiledGraph(t, `(f "hi" 2.5 'x)`).Draw(DrawOptions{})
+	for _, want := range []string{`"hi"   3`, "2.5    4", "quote  6", "x      7"} {
 		if !strings.Contains(got, want) {
 			t.Errorf("missing %s in\n%s", want, got)
 		}
@@ -36,15 +68,15 @@ 	}
 	shared := mustProcess(t, path(
 		mapping(fakeCert("1.2.3", "1.2.4"), "1.2.3>1.2.5", "1.2.4>1.2.5"),
 		fakeCert("any"),
-	)).Draw()
+	)).Draw(DrawOptions{})
 	if strings.Count(shared, "1.2.5") != 2 || !strings.Contains(shared, "(shared, drawn above)") {
 		t.Errorf("shared node:\n%s", shared)
 	}
 }
 
 func TestDrawFoldsCopyChains(t *testing.T) {
-	got := compiledGraph(t, "1 (a (b (c)))").Draw()
-	if !strings.Contains(got, "`-- 1#1'") || !strings.Contains(got, "copy, depths 2-4") {
+	got := compiledGraph(t, "1 (a (b (c)))").Draw(DrawOptions{})
+	if !strings.Contains(got, "1' copy, depths 2-4") {
 		t.Errorf("chain of copies not folded:\n%s", got)
 	}
 	if n := strings.Count(got, "\n"); n != 11 {
@@ -53,7 +85,7 @@ 	}
 }
 
 func TestDrawShowsNotes(t *testing.T) {
-	got := compiledGraph(t, "; the sum\n(+ 1\n  ; two\n  ; lines\n  2)").Draw()
+	got := compiledGraph(t, "; the sum\n(+ 1\n  ; two\n  ; lines\n  2)").Draw(DrawOptions{})
 	if !strings.Contains(got, "GOV.0.1.1  ; the sum") || !strings.Contains(got, "GOV.2.4.50  ; two / lines") {
 		t.Errorf("notes missing:\n%s", got)
 	}