government / gov2lisp / gov2lisp.go

@ b16190dee4ae781544f8119bec44f00f5224c810 | history


// Package gov2lisp turns a decoded program back into Lisp source text.
package gov2lisp

import (
	"strings"

	"government/ast"
	"government/sexpr"
)

// Decompile prints one top-level form per line. The output is source in
// normal form: the printer's spelling, so 'x comes back as (quote x) and
// 3.10 as 3.1. Reading it gives exactly the forms that were decoded.
func Decompile(forms []sexpr.Value) string {
	var b strings.Builder
	for _, f := range forms {
		b.WriteString(sexpr.Print(f))
		b.WriteByte('\n')
	}
	return b.String()
}

// DecompileTree is Decompile that also restores notes as comments. Each
// note goes on the lines just before its node, so reading the output
// attaches it to the same node again. A form with no notes inside it stays
// on one line; a list with a noted element inside is broken across lines,
// one element per line, so the comment has a line of its own.
func DecompileTree(t *ast.Tree) string {
	var b strings.Builder
	for _, f := range t.Forms {
		writeNote(&b, f.Note, "")
		writeNode(&b, f, "")
		b.WriteByte('\n')
	}
	return b.String()
}

func writeNode(b *strings.Builder, n *ast.Node, indent string) {
	if !n.IsList() || !hasNotesInside(n) {
		b.WriteString(compact(n))
		return
	}
	inner := indent + "  "
	b.WriteByte('(')
	for i, c := range n.Children {
		if i > 0 || c.Note != "" {
			b.WriteString("\n" + inner)
		}
		if c.Note != "" {
			writeNote(b, c.Note, inner)
		}
		writeNode(b, c, inner)
	}
	b.WriteByte(')')
}

// writeNote writes a note as comment lines, each ending in a newline and
// the indent the node will start at.
func writeNote(b *strings.Builder, note, indent string) {
	if note == "" {
		return
	}
	for _, line := range strings.Split(note, "\n") {
		if line == "" {
			b.WriteString(";\n" + indent)
		} else {
			b.WriteString("; " + line + "\n" + indent)
		}
	}
}

func hasNotesInside(n *ast.Node) bool {
	for _, c := range n.Children {
		if c.Note != "" || hasNotesInside(c) {
			return true
		}
	}
	return false
}

// compact prints a node on one line, as the printer would print its value.
func compact(n *ast.Node) string {
	if n.IsList() {
		forms, _, err := ast.FromTree(&ast.Tree{Forms: []*ast.Node{n}})
		if err == nil {
			return sexpr.Print(forms[0])
		}
	}
	if n.NS == ast.NSString {
		return sexpr.Print(sexpr.String(n.Text))
	}
	return n.Text
}