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

111 lines
2.8 KiB
Go

package parser_test
import (
"testing"
"git.sharkk.net/Sharkk/Mako/parser"
)
func TestAssignStatements(t *testing.T) {
tests := []struct {
input string
expectedIdentifier string
expectedValue any
isExpression bool
}{
{"x = 42", "x", 42.0, false},
{"name = \"test\"", "name", "test", false},
{"flag = true", "flag", true, false},
{"ptr = nil", "ptr", nil, false},
{"result = 3 + 4", "result", "(3.00 + 4.00)", true},
}
for _, tt := range tests {
t.Run(tt.input, func(t *testing.T) {
l := parser.NewLexer(tt.input)
p := parser.NewParser(l)
program := p.ParseProgram()
checkParserErrors(t, p)
if len(program.Statements) != 1 {
t.Fatalf("expected 1 statement, got %d", len(program.Statements))
}
stmt, ok := program.Statements[0].(*parser.AssignStatement)
if !ok {
t.Fatalf("expected AssignStatement, got %T", program.Statements[0])
}
if stmt.Name.Value != tt.expectedIdentifier {
t.Errorf("expected identifier %s, got %s", tt.expectedIdentifier, stmt.Name.Value)
}
if tt.isExpression {
if stmt.Value.String() != tt.expectedValue.(string) {
t.Errorf("expected expression %s, got %s", tt.expectedValue.(string), stmt.Value.String())
}
} else {
switch expected := tt.expectedValue.(type) {
case float64:
testNumberLiteral(t, stmt.Value, expected)
case string:
testStringLiteral(t, stmt.Value, expected)
case bool:
testBooleanLiteral(t, stmt.Value, expected)
case nil:
testNilLiteral(t, stmt.Value)
}
}
})
}
}
func TestTableAssignments(t *testing.T) {
tests := []struct {
input string
identifier string
pairCount int
isArray bool
description string
}{
{"arr = {1, 2, 3}", "arr", 3, true, "array assignment"},
{"hash = {x = 1, y = 2}", "hash", 2, false, "hash assignment"},
{"empty = {}", "empty", 0, true, "empty table assignment"},
}
for _, tt := range tests {
t.Run(tt.description, func(t *testing.T) {
l := parser.NewLexer(tt.input)
p := parser.NewParser(l)
program := p.ParseProgram()
checkParserErrors(t, p)
if len(program.Statements) != 1 {
t.Fatalf("expected 1 statement, got %d", len(program.Statements))
}
stmt, ok := program.Statements[0].(*parser.AssignStatement)
if !ok {
t.Fatalf("expected AssignStatement, got %T", program.Statements[0])
}
if stmt.Name.Value != tt.identifier {
t.Errorf("expected identifier %s, got %s", tt.identifier, stmt.Name.Value)
}
table, ok := stmt.Value.(*parser.TableLiteral)
if !ok {
t.Fatalf("expected TableLiteral, got %T", stmt.Value)
}
if len(table.Pairs) != tt.pairCount {
t.Errorf("expected %d pairs, got %d", tt.pairCount, len(table.Pairs))
}
if table.IsArray() != tt.isArray {
t.Errorf("expected IsArray() = %t, got %t", tt.isArray, table.IsArray())
}
})
}
}