government / src / eval / error.go

@ 761f3b207460ae5814dd76a326ce14777e29e659 | history


package eval

import (
	"fmt"

	"government/sexpr"
)

// Error codes.
const (
	ErrUnbound      = "E-UNBOUND"
	ErrSyntax       = "E-SYNTAX"
	ErrSpecialForm  = "E-SPECIAL-FORM"
	ErrNotAFunction = "E-NOT-A-FUNCTION"
	ErrArity        = "E-ARITY"
	ErrType         = "E-TYPE"
	ErrArith        = "E-ARITH"
	ErrImmutable    = "E-IMMUTABLE"
)

type Error struct {
	Code string
	Msg  string
	// Expr is the innermost list being evaluated when the error arose. The
	// evaluator does not know about source text; whoever produced the code
	// maps Expr back to a location (the reader gives line:col, and a .gov
	// program will give the node's OID).
	Expr sexpr.Value
}

func (e *Error) Error() string { return e.Code + ": " + e.Msg }

// at records expr as the error's location unless an inner expression was
// already recorded.
func at(err error, expr sexpr.Value) error {
	if e, ok := err.(*Error); ok && e.Expr == nil {
		e.Expr = expr
	}
	return err
}

func errorf(code, format string, args ...any) *Error {
	return &Error{Code: code, Msg: fmt.Sprintf(format, args...)}
}