government / src / cmd / govlisp / main.go

@ 18f7f5ebceecb0e295c3daf959d352ed8b8b9694 | history


// Command govlisp runs GOVERNMENT programs straight from GovLisp source,
// with no certificates involved.
//
//	govlisp                  interactive REPL
//	govlisp prog.gov.lisp    run a file, printing the value of each non-define form
package main

import (
	"errors"
	"fmt"
	"io"
	"os"

	"github.com/spf13/cobra"

	"nmyk.io/government/eval"
	"nmyk.io/government/sexpr"
)

const (
	exitOK      = 0
	exitRuntime = 1
	exitSyntax  = 2
)

func main() {
	os.Exit(run(os.Args[1:], os.Stdin, os.Stdout, os.Stderr))
}

// exitCode carries a file run's exit code out through cobra; the file run
// has already reported the error itself.
type exitCode int

func (c exitCode) Error() string { return fmt.Sprintf("exit %d", int(c)) }

func run(args []string, stdin *os.File, stdout, stderr io.Writer) int {
	root := &cobra.Command{
		Use:   "govlisp [prog.gov.lisp]",
		Short: "Run GovLisp source directly, with no certificates",
		Long: "govlisp runs GovLisp source directly, with no certificates.\n\n" +
			"With a file, it evaluates each top-level form in order, prints the value of each\n" +
			"one that is not a define, and stops at the first error.\n\n" +
			"With no file, it starts a REPL. On a terminal the REPL has line editing, history\n" +
			"(kept in ~/.govlisp_history), tab completion of names in scope, and Ctrl-C to\n" +
			"discard the form being typed; Ctrl-D ends the session.",
		Args:              cobra.MaximumNArgs(1),
		SilenceUsage:      true,
		SilenceErrors:     true,
		CompletionOptions: cobra.CompletionOptions{DisableDefaultCmd: true},
		RunE: func(cmd *cobra.Command, args []string) error {
			if len(args) == 1 {
				if code := runFile(args[0], cmd.OutOrStdout(), cmd.ErrOrStderr()); code != exitOK {
					return exitCode(code)
				}
				return nil
			}
			top := eval.NewTopLevel()
			src, err := newSource(stdin, top)
			if err != nil {
				return err
			}
			defer src.Close()
			repl(top, src, cmd.OutOrStdout())
			return nil
		},
	}
	root.SetArgs(args)
	root.SetOut(stdout)
	root.SetErr(stderr)
	err := root.Execute()
	var code exitCode
	switch {
	case err == nil:
		return exitOK
	case errors.As(err, &code):
		return int(code)
	}
	fmt.Fprintf(stderr, "govlisp: %v\nRun 'govlisp --help' for usage.\n", err)
	return exitSyntax
}

// runFile evaluates every top-level form in path, printing each non-define
// value. It stops at the first error, which it reports with the source
// position of the subexpression that failed.
func runFile(path string, stdout, stderr io.Writer) int {
	src, err := os.ReadFile(path)
	if err != nil {
		fmt.Fprintln(stderr, err)
		return exitSyntax
	}
	r := sexpr.NewReader(string(src))
	var forms []sexpr.Value
	var starts []sexpr.Pos
	for {
		v, pos, err := r.ReadWithPos()
		if err != nil {
			fmt.Fprintf(stderr, "%s:%v\n", path, err)
			return exitSyntax
		}
		if v == nil {
			break
		}
		forms = append(forms, v)
		starts = append(starts, pos)
	}

	top := eval.NewTopLevel()
	for i, form := range forms {
		v, err := top.Eval(form)
		if err != nil {
			pos := starts[i]
			if e, ok := err.(*eval.Error); ok {
				if p, ok := r.Position(e.Expr); ok {
					pos = p
				}
			}
			fmt.Fprintf(stderr, "%s:%v: %v\n", path, pos, err)
			return exitRuntime
		}
		if !isDefine(form) {
			fmt.Fprintln(stdout, sexpr.Print(v))
		}
	}
	return exitOK
}

func isDefine(form sexpr.Value) bool {
	p, ok := form.(*sexpr.Pair)
	return ok && p.Car == sexpr.Value(sexpr.Symbol("define"))
}