Guest User

Untitled

a guest
Dec 13th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.73 KB | None | 0 0
  1. package main
  2.  
  3. import (
  4. "github.com/Lebonesco/go-compiler/ast"
  5. "github.com/Lebonesco/go-compiler/checker"
  6. "github.com/Lebonesco/go-compiler/lexer"
  7. "github.com/Lebonesco/go-compiler/parser"
  8. "testing"
  9. )
  10.  
  11. type Test struct {
  12. src string
  13. Success bool
  14. }
  15.  
  16. func TestOperations(t *testing.T) {
  17. tests := []Test{
  18. {`5 + 5;`, true},
  19. {`5 + "5";`, false},
  20. {`5 * 5;`, true},
  21. {`5 * 5 + 9;`, true},
  22. {`5 < 10;`, true},
  23. {`true and true;`, true},
  24. {`4 and 2;`, false},
  25. {`true or false;`, true}}
  26.  
  27. runTests(tests, t)
  28. }
  29.  
  30. func TestIdents(t *testing.T) {
  31. tests := []Test{
  32. {`let x = 5;`, true},
  33. {`
  34. let x = 6;
  35. let x = 8;`, false},
  36. {
  37. `let x = 5;
  38. x = "hello";`, false},
  39. {
  40. `let y = "hey";
  41. y = "cool";`, true},
  42. {
  43. `let x = "hello ";
  44. let y = "world";
  45. let z = x + y;`, true},
  46. {
  47. `x = 5;`, false}}
  48.  
  49. runTests(tests, t)
  50. }
  51.  
  52. func TestFunctions(t *testing.T) {
  53. tests := []Test{
  54. {
  55. `func add(x Int, y Int) Int {
  56. return x + y;
  57. }
  58.  
  59. let a = add(1, 3);`, true},
  60. {
  61. `func add(x Int, y Int) Int {
  62. return x + y;
  63. }
  64.  
  65. let z = add("test", 3);`, false},
  66. {
  67. `func one() Int {
  68. return "test";
  69. }`, false},
  70. }
  71.  
  72. runTests(tests, t)
  73. }
  74.  
  75. func runTests(tests []Test, t *testing.T) {
  76. for i, test := range tests {
  77. err := stringToChecker(test.src)
  78.  
  79. if err != nil && !test.Success {
  80. continue
  81. } else if err != nil {
  82. t.Fatalf("test %d fail: "+err.Error(), i)
  83. } else if !test.Success {
  84. t.Fatalf("test %d should have failed", i)
  85. }
  86. }
  87. }
  88.  
  89. func stringToChecker(input string) error {
  90. l := lexer.NewLexer([]byte(input))
  91. p := parser.NewParser()
  92. res, err := p.Parse(l)
  93. if err != nil {
  94. return err
  95. }
  96.  
  97. program, _ := res.(*ast.Program)
  98. err = checker.Checker(program)
  99. if err != nil {
  100. return err
  101. }
  102. return nil
  103. }
Add Comment
Please, Sign In to add comment