@ 0a6d0b45c9b0e3f50876896c1c597c24311ceb7b | history
package lisptest
import (
"fmt"
"strings"
"testing"
"government/eval"
)
type recorder struct{ errors []string }
func (r *recorder) Helper() {}
func (r *recorder) Errorf(format string, args ...any) {
r.errors = append(r.errors, fmt.Sprintf(format, args...))
}
func TestAnnotationsAttachToPrecedingForm(t *testing.T) {
f, err := Parse("t.lisp", `
(define x 1)
x ;=> 1
(car
'())
; a plain comment
;=! needs a pair
(+ x 1) (+ x 2) ;=> 3
`)
if err != nil {
t.Fatal(err)
}
got := []string{}
for _, c := range f.Cases {
got = append(got, fmt.Sprintf("%v %d %q", c.Pos, c.Expect, c.Want))
}
want := []string{
`2:1 0 ""`,
`3:1 1 "1"`,
`4:1 2 "needs a pair"`,
`8:1 0 ""`,
`8:9 1 "3"`,
}
if strings.Join(got, "\n") != strings.Join(want, "\n") {
t.Errorf("cases:\n%s\nwant:\n%s", strings.Join(got, "\n"), strings.Join(want, "\n"))
}
}
func TestParseErrors(t *testing.T) {
tests := []struct{ src, want string }{
{";=> 1\n(+ 1 0)", "t.lisp:1:1: annotation before any form"},
{"1 ;=> 1\n;=> 1", "t.lisp:2:1: second annotation for the form at 1:1"},
{"1 ;=>", "t.lisp:1:3: empty annotation"},
{"(1", "t.lisp:1:1: unterminated list"},
}
for _, tt := range tests {
if _, err := Parse("t.lisp", tt.src); err == nil || err.Error() != tt.want {
t.Errorf("Parse(%q) error = %v, want %q", tt.src, err, tt.want)
}
}
}
// Every kind of mismatch is reported, with the failing subexpression's
// position, and evaluation continues past failures.
func TestRunReportsFailures(t *testing.T) {
f, err := Parse("t.lisp", `(+ 1 1) ;=> 3
(+ 1 1) ;=! overflow
(car '()) ;=> 1
(/ 1 0) ;=! not a function
(+ 1
(car 5))
(+ 2 2) ;=> 4
`)
if err != nil {
t.Fatal(err)
}
r := &recorder{}
Run(r, f, eval.NewTopLevel())
want := []string{
"t.lisp:1:1: (+ 1 1)\n\tgot 2\n\twant 3",
"t.lisp:2:1: (+ 1 1)\n\tgot value 2, want an error containing \"overflow\"",
"t.lisp:3:1: (car (quote ()))\n\tunexpected error E-TYPE: car needs a pair, got () (at 3:1: (car (quote ())))",
"t.lisp:4:1: (/ 1 0)\n\tgot error E-ARITH: division by zero (at 4:1: (/ 1 0)), want one containing \"not a function\"",
"t.lisp:5:1: (+ 1 (car 5))\n\tunexpected error E-TYPE: car needs a pair, got 5 (at 6:4: (car 5))",
}
if strings.Join(r.errors, "\n---\n") != strings.Join(want, "\n---\n") {
t.Errorf("reported:\n%s\n\nwant:\n%s", strings.Join(r.errors, "\n---\n"), strings.Join(want, "\n---\n"))
}
}