Mako/parser/tests/tables_test.go
2025-06-10 09:36:17 -05:00

97 lines
2.3 KiB
Go

package parser_test
import (
"testing"
"git.sharkk.net/Sharkk/Mako/parser"
)
func TestTableLiterals(t *testing.T) {
tests := []struct {
input string
expectedPairs int
isArray bool
description string
}{
{"{}", 0, true, "empty table"},
{"{1, 2, 3}", 3, true, "array-like table"},
{"{a = 1, b = 2}", 2, false, "hash-like table"},
{`{"hello", "world"}`, 2, true, "string array"},
{"{x = true, y = false}", 2, false, "boolean hash"},
{"{1}", 1, true, "single element array"},
{"{key = nil}", 1, false, "nil value hash"},
}
for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) {
l := parser.NewLexer(tt.input)
p := parser.NewParser(l)
expr := p.ParseExpression(parser.LOWEST)
checkParserErrors(t, p)
table, ok := expr.(*parser.TableLiteral)
if !ok {
t.Fatalf("expected TableLiteral, got %T", expr)
}
if len(table.Pairs) != tt.expectedPairs {
t.Errorf("expected %d pairs, got %d", tt.expectedPairs, len(table.Pairs))
}
if table.IsArray() != tt.isArray {
t.Errorf("expected IsArray() = %t, got %t", tt.isArray, table.IsArray())
}
})
}
}
func TestTableStringRepresentation(t *testing.T) {
tests := []struct {
input string
expected string
}{
{"{}", "{}"},
{"{1, 2}", "{1.00, 2.00}"},
{"{x = 1}", "{x = 1.00}"},
{"{a = 1, b = 2}", "{a = 1.00, b = 2.00}"},
}
for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
l := parser.NewLexer(tt.input)
p := parser.NewParser(l)
expr := p.ParseExpression(parser.LOWEST)
checkParserErrors(t, p)
if expr.String() != tt.expected {
t.Errorf("expected %s, got %s", tt.expected, expr.String())
}
})
}
}
func TestTableWithExtendedNumbers(t *testing.T) {
tests := []struct {
input string
expected string
desc string
}{
{"{0xFF, 0b1010}", "{255.00, 10.00}", "array with hex and binary"},
{"{hex = 0xFF, bin = 0b1010}", "{hex = 255.00, bin = 10.00}", "hash with extended numbers"},
{"{1e2, 0x10, 0b10}", "{100.00, 16.00, 2.00}", "mixed number formats"},
}
for _, tt := range tests {
t.Run(tt.desc, func(t *testing.T) {
l := parser.NewLexer(tt.input)
p := parser.NewParser(l)
expr := p.ParseExpression(parser.LOWEST)
checkParserErrors(t, p)
if expr.String() != tt.expected {
t.Errorf("expected %s, got %s", tt.expected, expr.String())
}
})
}
}