government / eval / error_test.go

@ da006f04d8870dcf444b3b0380729d78f076b2ea | history


package eval

import (
	"errors"
	"testing"

	"government/sexpr"
)

// Errors record the innermost list being evaluated, so a caller can point
// at the exact subexpression that failed.
func TestErrorLocation(t *testing.T) {
	tests := []struct{ src, where string }{
		{"(car '())", "(car (quote ()))"},
		{"(+ 1 (car '()))", "(car (quote ()))"},
		{"(+ 1 (* 2 (car '())))", "(car (quote ()))"},
		{"(+ 1 boom)", "(+ 1 boom)"},
		{"(if)", "(if)"},
		{"(if T (if))", "(if)"},
		{"(1 2)", "(1 2)"},
		{"(define 1 2)", "(define 1 2)"},
		{"(define f (lambda (x) (car x))) (f 1)", "(car x)"},
		{"(define f (lambda (x) (define y (car x)) y)) (f 1)", "(car x)"},
		{"(define f (lambda () (define 1 2) 3)) (f)", "(define 1 2)"},
		{"(and T (/ 1 0))", "(/ 1 0)"},
		{"((lambda (x) x))", "((lambda (x) x))"},
	}
	for _, tt := range tests {
		t.Run(tt.src, func(t *testing.T) {
			_, err := evalString(t, tt.src)
			var e *Error
			if !errors.As(err, &e) {
				t.Fatalf("Eval(%s) error = %v, want *Error", tt.src, err)
			}
			if e.Expr == nil {
				t.Fatalf("Eval(%s): error %v has no location", tt.src, err)
			}
			if got := sexpr.Print(e.Expr); got != tt.where {
				t.Errorf("Eval(%s) error location = %s, want %s", tt.src, got, tt.where)
			}
		})
	}
}