government / eval / lists_test.go

@ bf971275d54b7235006309f4e84fd06723f4f70e | history


package eval

import "testing"

func TestLists(t *testing.T) {
	runEvalCases(t, []evalCase{
		{"(cons 1 2)", "(1 . 2)"},
		{"(cons 1 ())", "(1)"},
		{"(cons 1 '(2 3))", "(1 2 3)"},
		{"(cons '(1) '(2))", "((1) 2)"},
		{"(cons (+ 1 1) (cons 3 ()))", "(2 3)"},
		{"(cons + ())", "(#<builtin +>)"},
		{"(car '(1 2 3))", "1"},
		{"(cdr '(1 2 3))", "(2 3)"},
		{"(cdr '(1))", "()"},
		{"(car '((1 2) 3))", "(1 2)"},
		{"(car (cdr '(1 2 3)))", "2"},
		{"(car '(1 . 2))", "1"},
		{"(cdr '(1 . 2))", "2"},
		{"(car (cons 'a 'b))", "a"},
		{"(cdr (cons 'a 'b))", "b"},

		// The tripwire used throughout the tests: car of () is an error, so
		// it only appears in branches that must not run.
		{"(if T 1 (car '()))", "1"},
	})
}

func TestListErrors(t *testing.T) {
	runErrorCases(t, []errorCase{
		{"(car '())", ErrType, "car needs a pair, got ()"},
		{"(cdr '())", ErrType, "cdr needs a pair, got ()"},
		{"(car 1)", ErrType, "car needs a pair, got 1"},
		{`(cdr "ab")`, ErrType, `cdr needs a pair, got "ab"`},
		{"(car (cdr '(1)))", ErrType, "car needs a pair, got ()"},
		{"(cons 1)", ErrArity, "cons takes 2 arguments, got 1"},
		{"(cons 1 2 3)", ErrArity, "cons takes 2 arguments, got 3"},
		{"(car)", ErrArity, "car takes 1 argument, got 0"},
		{"(cdr '(1) '(2))", ErrArity, "cdr takes 1 argument, got 2"},
	})
}

func TestStrings(t *testing.T) {
	runEvalCases(t, []evalCase{
		{`(strlen "")`, "0"},
		{`(strlen "hello")`, "5"},
		{`(strlen "héllo")`, "5"},
		{`(strlen "😀")`, "1"},
		{`(strlen "a\nb")`, "3"},
		{`(strcat)`, `""`},
		{`(strcat "gov")`, `"gov"`},
		{`(strcat "gov" "ern" "ment")`, `"government"`},
		{`(strcat "" "a" "")`, `"a"`},
		{`(strcat "é" "😀")`, `"é😀"`},
		{`(strlen (strcat "ab" "cd"))`, "4"},
		{`(str? "")`, "T"},
		{`(str? "x")`, "T"},
		{`(str? 'x)`, "F"},
		{`(str? 1)`, "F"},
		{`(str? ())`, "F"},
		{`(str? '("x"))`, "F"},
		{`(str? str?)`, "F"},
	})
}

func TestStringErrors(t *testing.T) {
	runErrorCases(t, []errorCase{
		{"(strlen 'abc)", ErrType, "argument 1 of strlen must be a string, got abc"},
		{"(strlen 1)", ErrType, "argument 1 of strlen must be a string, got 1"},
		{`(strcat "a" 1)`, ErrType, "argument 2 of strcat must be a string, got 1"},
		{`(strcat "a" "b" '(c))`, ErrType, "argument 3 of strcat must be a string, got (c)"},
		{"(strlen)", ErrArity, "strlen takes 1 argument, got 0"},
		{`(str? "a" "b")`, ErrArity, "str? takes 1 argument, got 2"},
	})
}