lexer_test.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. package muesli
  2. import (
  3. _ "strings"
  4. "testing"
  5. )
  6. func LexText(input string) []Token {
  7. lexer := NewLexerFromInputString(input)
  8. tokens := lexer.LexAll()
  9. return tokens
  10. }
  11. func Assert(test *testing.T, ok bool, text string) bool {
  12. if !ok {
  13. test.Errorf(text)
  14. }
  15. return ok
  16. }
  17. func HelperTryLexText(input string, test *testing.T) {
  18. tokens := LexText(input)
  19. for i := 0; i < len(tokens); i++ {
  20. // test.Logf("%d: %s", i, tokens[i].String())
  21. }
  22. }
  23. func HelperLexExpect(input string, wantKind TokenKind, wantValue Value, test *testing.T) {
  24. lexer := NewLexerFromInputString(input)
  25. token := lexer.Lex()
  26. if (token.TokenKind == wantKind) && (token.Value == wantValue) {
  27. test.Logf("Token as expected %v %v", token.TokenKind, token.Value)
  28. } else {
  29. test.Errorf("Unexpected token kind or value: %v %v >%v< >%v<",
  30. token.TokenKind, wantKind, token.Value, wantValue)
  31. }
  32. }
  33. func TestLex(test *testing.T) {
  34. HelperLexExpect("word\n", TokenKindWord, StringValue("word"), test)
  35. HelperLexExpect(":symbol\n", TokenKindSymbol, StringValue("symbol"), test)
  36. HelperLexExpect("1234\n", TokenKindInteger, IntValue(1234), test)
  37. HelperLexExpect("-3.14\n", TokenKindFloat, FloatValue(-3.14), test)
  38. HelperLexExpect(`"Hello \"world" \n`, TokenKindString, StringValue(`Hello "world`), test)
  39. HelperLexExpect("true\n", TokenKindBoolean, TrueValue, test)
  40. HelperLexExpect("false\n", TokenKindBoolean, FalseValue, test)
  41. }
  42. func TestLexing(test *testing.T) {
  43. const input = `
  44. greet "hi there"
  45. add 5 10
  46. mulf -2.0 3.1415
  47. say1 "unicode « ❤ 🂱"
  48. say2 "hello world"
  49. say3 "quote \" endquote"
  50. say4 "escape \a\b\e\f\n\r\t\"\\"
  51. say5 "numescape \xab \u2764 \U01f0b1"
  52. say_6 "hello \"world\\"
  53. :❤a_symbol❤
  54. define open a door {
  55. set (door open) true
  56. }
  57. def increment variable by value {
  58. =variable (add variable $value)
  59. }
  60. `
  61. test.Log("Hi test!")
  62. HelperTryLexText(input, test)
  63. }