parser_test.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package parser
  2. import (
  3. "testing"
  4. "code.osinet.fr/fgm/waiig15/lexer"
  5. )
  6. func checkParserErrors(t *testing.T, p *Parser) {
  7. errors := p.Errors()
  8. if len(errors) == 0 {
  9. return
  10. }
  11. t.Errorf("parser has %d errors", len(errors))
  12. for _, msg := range errors {
  13. t.Errorf("parser error: %q", msg)
  14. }
  15. t.FailNow()
  16. }
  17. func TestOperatorPrecedenceParsing(t *testing.T) {
  18. tests := []struct {
  19. input string
  20. expected string
  21. }{
  22. {
  23. "-a * b",
  24. "((-a) * b)",
  25. },
  26. {
  27. "!-a",
  28. "(!(-a))",
  29. },
  30. {
  31. "a + b + c",
  32. "((a + b) + c)",
  33. },
  34. {
  35. "a + b - c",
  36. "((a + b) - c)",
  37. },
  38. {
  39. "a * b * c",
  40. "((a * b) * c)",
  41. },
  42. {
  43. "a * b / c",
  44. "((a * b) / c)",
  45. },
  46. {
  47. "a + b / c",
  48. "(a + (b / c))",
  49. },
  50. {
  51. "a + b * c + d / e - f",
  52. "(((a + (b * c)) + (d / e)) - f)",
  53. },
  54. {
  55. "3 + 4; -5 * 5",
  56. "(3 + 4)((-5) * 5)",
  57. },
  58. {
  59. "5 > 4 == 3 < 4",
  60. "((5 > 4) == (3 < 4))",
  61. },
  62. {
  63. "5 < 4 != 3 > 4",
  64. "((5 < 4) != (3 > 4))",
  65. },
  66. {
  67. "3 + 4 * 5 == 3 * 1 + 4 * 5",
  68. "((3 + (4 * 5)) == ((3 * 1) + (4 * 5)))",
  69. },
  70. }
  71. for _, tt := range tests {
  72. l := lexer.New(tt.input)
  73. p := New(l)
  74. program := p.ParseProgram()
  75. checkParserErrors(t, p)
  76. actual := program.String()
  77. if actual != tt.expected {
  78. t.Errorf("expected=%q, got=%q", tt.expected, actual)
  79. }
  80. }
  81. }