test-invalid-unicode-js.cpp 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /*
  2. * Copyright (c) 2021, David Tuin <davidot@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Parser.h>
  7. #include <LibTest/TestCase.h>
  8. TEST_CASE(invalid_unicode_only)
  9. {
  10. char const* code = "\xEA\xFD";
  11. auto lexer = JS::Lexer(code);
  12. auto token = lexer.next();
  13. EXPECT_EQ(token.type(), JS::TokenType::Invalid);
  14. // After this we can get as many eof tokens as we like.
  15. for (auto i = 0; i < 10; i++) {
  16. auto eof_token = lexer.next();
  17. EXPECT_EQ(eof_token.type(), JS::TokenType::Eof);
  18. }
  19. }
  20. TEST_CASE(long_invalid_unicode)
  21. {
  22. char const* code = "\xF7";
  23. auto lexer = JS::Lexer(code);
  24. auto token = lexer.next();
  25. EXPECT_EQ(token.type(), JS::TokenType::Invalid);
  26. // After this we can get as many eof tokens as we like.
  27. for (auto i = 0; i < 10; i++) {
  28. auto eof_token = lexer.next();
  29. EXPECT_EQ(eof_token.type(), JS::TokenType::Eof);
  30. }
  31. }
  32. TEST_CASE(invalid_unicode_and_valid_code)
  33. {
  34. char const* code = "\xEA\xFDthrow 1;";
  35. auto lexer = JS::Lexer(code);
  36. auto invalid_token = lexer.next();
  37. EXPECT_EQ(invalid_token.type(), JS::TokenType::Invalid);
  38. // 0xEA is the start of a three character unicode code point thus it consumes the 't'.
  39. auto token_after = lexer.next();
  40. EXPECT_EQ(token_after.value(), "hrow");
  41. }
  42. TEST_CASE(long_invalid_unicode_and_valid_code)
  43. {
  44. char const* code = "\xF7throw 1;";
  45. auto lexer = JS::Lexer(code);
  46. auto invalid_token = lexer.next();
  47. EXPECT_EQ(invalid_token.type(), JS::TokenType::Invalid);
  48. // 0xF7 is the start of a four character unicode code point thus it consumes 'thr'.
  49. auto token_after = lexer.next();
  50. EXPECT_EQ(token_after.value(), "ow");
  51. }
  52. TEST_CASE(invalid_unicode_after_valid_code_and_before_eof)
  53. {
  54. char const* code = "let \xEA\xFD;";
  55. auto lexer = JS::Lexer(code);
  56. auto let_token = lexer.next();
  57. EXPECT_EQ(let_token.type(), JS::TokenType::Let);
  58. auto invalid_token = lexer.next();
  59. EXPECT_EQ(invalid_token.type(), JS::TokenType::Invalid);
  60. // It should still get the valid trivia in front.
  61. EXPECT_EQ(invalid_token.trivia(), " ");
  62. // After this we can get as many eof tokens as we like.
  63. for (auto i = 0; i < 10; i++) {
  64. auto eof_token = lexer.next();
  65. EXPECT_EQ(eof_token.type(), JS::TokenType::Eof);
  66. }
  67. }