government / eval / builtin.go

@ 594cab6ae95854c36078bb56c8f0f51ffc68b05e | history


package eval

import (
	"fmt"

	"government/builtin"
	"government/sexpr"
)

// Builtin is a function implemented in Go. Builtins are ordinary values:
// they live in the environment under their names, so (define add +) works
// and + can be passed to a higher-order function.
type Builtin struct {
	sexpr.FunctionBase
	spec builtin.Spec
	fn   func(args []sexpr.Value) (sexpr.Value, error)
}

func (b *Builtin) Builtin() bool { return true }
func (b *Builtin) Name() string  { return b.spec.Name }

// functions are the builtin functions' implementations. Their names,
// codes and argument counts are in package builtin; builtins pairs the two
// and refuses to start if either side has a name the other lacks.
var functions = map[string]func(args []sexpr.Value) (sexpr.Value, error){
	"+":      add,
	"-":      subtract,
	"*":      multiply,
	"/":      divide,
	"<":      less,
	">":      greater,
	"<=":     lessEq,
	">=":     greaterEq,
	"==":     equal,
	"!=":     notEqual,
	"not":    not,
	"cons":   cons,
	"car":    car,
	"cdr":    cdr,
	"strlen": strlen,
	"strcat": strcat,
	"str?":   isString,
}

var builtins = func() []*Builtin {
	var bs []*Builtin
	for _, spec := range builtin.All {
		if spec.Kind != builtin.Function {
			continue
		}
		fn, ok := functions[spec.Name]
		if !ok {
			panic("eval: builtin function " + spec.Name + " has no implementation")
		}
		bs = append(bs, &Builtin{spec: spec, fn: fn})
	}
	if len(bs) != len(functions) {
		panic("eval: an implemented function is not in package builtin")
	}
	return bs
}()

// Builtins returns the top-level environment: every builtin bound to its
// name.
func Builtins() *Env {
	var env *Env
	for _, b := range builtins {
		env = env.Extend(sexpr.Symbol(b.spec.Name), b)
	}
	return env
}

func checkArity(b *Builtin, n int) error {
	if err := b.spec.CheckCount(n, "argument"); err != nil {
		return errorf(ErrArity, "%v", err)
	}
	return nil
}

func plural(n int, noun string) string {
	if n == 1 {
		return "1 " + noun
	}
	return fmt.Sprintf("%d %ss", n, noun)
}