@ 5907b855a9838ebf99230949b5fc2a535b09f3ad | history
package sexpr
import (
"math"
"testing"
)
type testFunc struct {
FunctionBase
builtin bool
name string
}
func (f testFunc) Builtin() bool { return f.builtin }
func (f testFunc) Name() string { return f.name }
func TestPrint(t *testing.T) {
tests := []struct {
name string
value Value
want string
}{
{"zero", Int(0), "0"},
{"negative int", Int(-42), "-42"},
{"max int", Int(math.MaxInt64), "9223372036854775807"},
{"min int", Int(math.MinInt64), "-9223372036854775808"},
// Floats always carry a dot so they never read back as Ints.
{"whole float", Float(1), "1.0"},
{"fraction", Float(3.14), "3.14"},
{"negative float", Float(-0.5), "-0.5"},
{"zero float", Float(0), "0.0"},
{"negative zero", Float(math.Copysign(0, -1)), "-0.0"},
{"large float", Float(1e20), "100000000000000000000.0"},
{"huge float", Float(1e21), "1.0e+21"},
{"tiny float", Float(1.5e-7), "1.5e-07"},
{"shortest digits", Float(0.1), "0.1"},
{"empty string", String(""), `""`},
{"plain string", String("hello"), `"hello"`},
{"quote escape", String(`a"b`), `"a\"b"`},
{"backslash escape", String(`a\b`), `"a\\b"`},
{"newline and tab", String("a\nb\tc"), `"a\nb\tc"`},
{"other control char", String("bell\a"), `"bell\u{7}"`},
{"unicode kept as is", String("héllo 😀"), `"héllo 😀"`},
{"true", T, "T"},
{"false", F, "F"},
{"symbol", Symbol("foo"), "foo"},
{"operator symbol", Symbol("+"), "+"},
{"empty list", Nil, "()"},
{"one element", List(Int(1)), "(1)"},
{"proper list", List(Int(1), Int(2), Int(3)), "(1 2 3)"},
{"mixed list", List(Symbol("+"), Int(1), Float(2), String("x")), `(+ 1 2.0 "x")`},
{"nested list", List(Int(1), List(Int(2), Int(3)), Nil), "(1 (2 3) ())"},
{"list of empty", List(Nil), "(())"},
{"dotted pair", Cons(Int(1), Int(2)), "(1 . 2)"},
{"improper list", ListWithTail(Int(3), Int(1), Int(2)), "(1 2 . 3)"},
{"pair of lists", Cons(List(Int(1)), List(Int(2))), "((1) 2)"},
{"dotted to symbol", Cons(Symbol("a"), Symbol("b")), "(a . b)"},
{"quote form", List(Symbol("quote"), Symbol("x")), "(quote x)"},
{"builtin", testFunc{builtin: true, name: "+"}, "#<builtin +>"},
{"named closure", testFunc{name: "fact"}, "#<lambda fact>"},
{"closure", testFunc{}, "#<lambda>"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := Print(tt.value); got != tt.want {
t.Errorf("Print() = %s, want %s", got, tt.want)
}
})
}
}
func TestListHelpers(t *testing.T) {
if List() != Value(Nil) {
t.Errorf("List() = %s, want ()", Print(List()))
}
if got := ListWithTail(Int(9)); got != Value(Int(9)) {
t.Errorf("ListWithTail with no items = %s, want 9", Print(got))
}
}
// Guards writePair against recursing on cdrs.
func TestPrintLongList(t *testing.T) {
items := make([]Value, 1_000_000)
for i := range items {
items[i] = Int(0)
}
got := Print(List(items...))
if want := 2*len(items) + 1; len(got) != want {
t.Errorf("printed length = %d, want %d", len(got), want)
}
}