government / src / builtin / builtin_test.go

@ 425eee5ae0d898d1e8c0558a56c41f58d7a05028 | history


package builtin

import "testing"

// TestCodesArePinned is a deliberate second copy of the codes. Published
// codes must never change; an accidental edit to All fails here.
func TestCodesArePinned(t *testing.T) {
	want := map[string]uint64{
		ListNode: 1, Dot: 2, True: 3, False: 4, Empty: 5,
		"quote": 10, "if": 11, "define": 12, "lambda": 13, "and": 14, "or": 15,
		"not": 20, "+": 21, "-": 22, "*": 23, "/": 24, "<": 25, ">": 26,
		"<=": 27, ">=": 28, "==": 29, "!=": 30, "cons": 31, "car": 32,
		"cdr": 33, "strlen": 34, "strcat": 35, "str?": 36,
	}
	if len(All) != len(want) {
		t.Errorf("%d builtins, want %d", len(All), len(want))
	}
	for _, s := range All {
		if want[s.Name] != s.Code {
			t.Errorf("%s has code %d, want %d", s.Name, s.Code, want[s.Name])
		}
	}
}

func TestCodeRanges(t *testing.T) {
	ranges := map[Kind][2]uint64{Structural: {1, 2}, Constant: {3, 5}, SpecialForm: {10, 15}, Function: {20, 1 << 63}}
	for _, s := range All {
		r := ranges[s.Kind]
		if s.Code < r[0] || s.Code > r[1] {
			t.Errorf("%s is a %s with code %d, outside %d-%d", s.Name, s.Kind, s.Code, r[0], r[1])
		}
	}
}

func TestReserved(t *testing.T) {
	for name, want := range map[string]bool{"if": true, "+": true, "str?": true, ListNode: false, True: false, Empty: false, "foo": false} {
		if IsReserved(name) != want {
			t.Errorf("IsReserved(%q) = %v", name, !want)
		}
	}
}

func TestCheckCount(t *testing.T) {
	spec := func(name string) Spec { s, _ := Lookup(name); return s }
	tests := []struct {
		name, noun string
		n          int
		want       string
	}{
		{"quote", "operand", 0, "quote takes 1 operand, got 0"},
		{"if", "operand", 4, "if takes 2 or 3 operands, got 4"},
		{"define", "operand", 1, "define takes 2 operands, got 1"},
		{"lambda", "operand", 1, "lambda takes at least 2 operands, got 1"},
		{"-", "argument", 0, "- takes at least 1 argument, got 0"},
		{"cons", "argument", 3, "cons takes 2 arguments, got 3"},
	}
	for _, tt := range tests {
		err := spec(tt.name).CheckCount(tt.n, tt.noun)
		if err == nil || err.Error() != tt.want {
			t.Errorf("%s with %d: %v, want %q", tt.name, tt.n, err, tt.want)
		}
	}
	for _, ok := range []struct {
		name string
		n    int
	}{{"and", 0}, {"or", 7}, {"if", 2}, {"if", 3}, {"+", 0}, {"strcat", 9}} {
		if err := spec(ok.name).CheckCount(ok.n, "operand"); err != nil {
			t.Errorf("%s with %d: %v", ok.name, ok.n, err)
		}
	}
}