parser_test.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. package parser
  2. import (
  3. "code.osinet.fr/fgm/waiig15/ast"
  4. "code.osinet.fr/fgm/waiig15/lexer"
  5. "testing"
  6. )
  7. func TestLetStatements(t *testing.T) {
  8. input := `
  9. let x = 5;
  10. let y = 10;
  11. let foobar = 838383;
  12. `
  13. l := lexer.New(input)
  14. p := New(l)
  15. program := p.ParseProgram()
  16. if program == nil {
  17. t.Fatalf("ParseProgram() returned nil.")
  18. }
  19. if len(program.Statements) != 3 {
  20. t.Fatalf("program.Statements does not contain 3 statements, got=%d",
  21. len(program.Statements))
  22. }
  23. tests := []struct {
  24. expectedIdentifier string
  25. }{
  26. {"x"},
  27. {"y"},
  28. {"foobar"},
  29. }
  30. for i, tt := range tests {
  31. stmt := program.Statements[i]
  32. if !testLetStatement(t, stmt, tt.expectedIdentifier) {
  33. return
  34. }
  35. }
  36. }
  37. func testLetStatement(t *testing.T, s ast.Statement, name string) bool {
  38. if s.TokenLiteral() != "let" {
  39. t.Errorf("s.TokenLiteral not 'let', got=%q", s.TokenLiteral())
  40. return false
  41. }
  42. // Statement is an interface, we need a concrete type for the value, and we
  43. // just determined this looked like a LetStatement.
  44. letStmt, ok := s.(*ast.LetStatement)
  45. if !ok {
  46. t.Errorf("s not *ast.LetStatement{}, got=%T", s)
  47. }
  48. if letStmt.Name.Value != name {
  49. t.Errorf("letStmt.Name.Value not %s, got=%s",
  50. name, letStmt.Name.Value)
  51. return false
  52. }
  53. if letStmt.Name.TokenLiteral() != name {
  54. t.Errorf("letStmt.Name.TokenLiteral not %s, got=%s",
  55. name, letStmt.Name.TokenLiteral())
  56. return false
  57. }
  58. return true
  59. }