Token.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252
  1. /*
  2. * Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@serenityos.org>
  3. * Copyright (c) 2020, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include "Token.h"
  8. #include <AK/Assertions.h>
  9. #include <AK/GenericLexer.h>
  10. #include <AK/StringBuilder.h>
  11. #include <ctype.h>
  12. namespace JS {
  13. const char* Token::name(TokenType type)
  14. {
  15. switch (type) {
  16. #define __ENUMERATE_JS_TOKEN(type, category) \
  17. case TokenType::type: \
  18. return #type;
  19. ENUMERATE_JS_TOKENS
  20. #undef __ENUMERATE_JS_TOKEN
  21. default:
  22. VERIFY_NOT_REACHED();
  23. return "<Unknown>";
  24. }
  25. }
  26. const char* Token::name() const
  27. {
  28. return name(m_type);
  29. }
  30. TokenCategory Token::category(TokenType type)
  31. {
  32. switch (type) {
  33. #define __ENUMERATE_JS_TOKEN(type, category) \
  34. case TokenType::type: \
  35. return TokenCategory::category;
  36. ENUMERATE_JS_TOKENS
  37. #undef __ENUMERATE_JS_TOKEN
  38. default:
  39. VERIFY_NOT_REACHED();
  40. }
  41. }
  42. TokenCategory Token::category() const
  43. {
  44. return category(m_type);
  45. }
  46. double Token::double_value() const
  47. {
  48. VERIFY(type() == TokenType::NumericLiteral);
  49. String value_string(m_value);
  50. if (value_string[0] == '0' && value_string.length() >= 2) {
  51. if (value_string[1] == 'x' || value_string[1] == 'X') {
  52. // hexadecimal
  53. return static_cast<double>(strtoul(value_string.characters() + 2, nullptr, 16));
  54. } else if (value_string[1] == 'o' || value_string[1] == 'O') {
  55. // octal
  56. return static_cast<double>(strtoul(value_string.characters() + 2, nullptr, 8));
  57. } else if (value_string[1] == 'b' || value_string[1] == 'B') {
  58. // binary
  59. return static_cast<double>(strtoul(value_string.characters() + 2, nullptr, 2));
  60. } else if (isdigit(value_string[1])) {
  61. // also octal, but syntax error in strict mode
  62. if (!m_value.contains('8') && !m_value.contains('9'))
  63. return static_cast<double>(strtoul(value_string.characters() + 1, nullptr, 8));
  64. }
  65. }
  66. return strtod(value_string.characters(), nullptr);
  67. }
  68. static u32 hex2int(char x)
  69. {
  70. VERIFY(isxdigit(x));
  71. if (x >= '0' && x <= '9')
  72. return x - '0';
  73. return 10u + (tolower(x) - 'a');
  74. }
  75. String Token::string_value(StringValueStatus& status) const
  76. {
  77. VERIFY(type() == TokenType::StringLiteral || type() == TokenType::TemplateLiteralString);
  78. auto is_template = type() == TokenType::TemplateLiteralString;
  79. GenericLexer lexer(is_template ? m_value : m_value.substring_view(1, m_value.length() - 2));
  80. auto encoding_failure = [&status](StringValueStatus parse_status) -> String {
  81. status = parse_status;
  82. return {};
  83. };
  84. StringBuilder builder;
  85. while (!lexer.is_eof()) {
  86. // No escape, consume one char and continue
  87. if (!lexer.next_is('\\')) {
  88. builder.append(lexer.consume());
  89. continue;
  90. }
  91. lexer.ignore();
  92. VERIFY(!lexer.is_eof());
  93. // Line continuation
  94. if (lexer.next_is('\n') || lexer.next_is('\r')) {
  95. lexer.ignore();
  96. continue;
  97. }
  98. // Line continuation
  99. if (lexer.next_is(LINE_SEPARATOR) || lexer.next_is(PARAGRAPH_SEPARATOR)) {
  100. lexer.ignore(3);
  101. continue;
  102. }
  103. // Null-byte escape
  104. if (lexer.next_is('0') && !isdigit(lexer.peek(1))) {
  105. lexer.ignore();
  106. builder.append('\0');
  107. continue;
  108. }
  109. // Hex escape
  110. if (lexer.next_is('x')) {
  111. lexer.ignore();
  112. if (!isxdigit(lexer.peek()) || !isxdigit(lexer.peek(1)))
  113. return encoding_failure(StringValueStatus::MalformedHexEscape);
  114. auto code_point = hex2int(lexer.consume()) * 16 + hex2int(lexer.consume());
  115. VERIFY(code_point <= 255);
  116. builder.append_code_point(code_point);
  117. continue;
  118. }
  119. // Unicode escape
  120. if (lexer.next_is('u')) {
  121. lexer.ignore();
  122. u32 code_point = 0;
  123. if (lexer.next_is('{')) {
  124. lexer.ignore();
  125. while (true) {
  126. if (!lexer.next_is(isxdigit))
  127. return encoding_failure(StringValueStatus::MalformedUnicodeEscape);
  128. auto new_code_point = (code_point << 4u) | hex2int(lexer.consume());
  129. if (new_code_point < code_point)
  130. return encoding_failure(StringValueStatus::UnicodeEscapeOverflow);
  131. code_point = new_code_point;
  132. if (lexer.next_is('}'))
  133. break;
  134. }
  135. lexer.ignore();
  136. } else {
  137. for (int j = 0; j < 4; ++j) {
  138. if (!lexer.next_is(isxdigit))
  139. return encoding_failure(StringValueStatus::MalformedUnicodeEscape);
  140. code_point = (code_point << 4u) | hex2int(lexer.consume());
  141. }
  142. }
  143. builder.append_code_point(code_point);
  144. continue;
  145. }
  146. // In non-strict mode LegacyOctalEscapeSequence is allowed in strings:
  147. // https://tc39.es/ecma262/#sec-additional-syntax-string-literals
  148. String octal_str;
  149. auto is_octal_digit = [](char ch) { return ch >= '0' && ch <= '7'; };
  150. auto is_zero_to_three = [](char ch) { return ch >= '0' && ch <= '3'; };
  151. auto is_four_to_seven = [](char ch) { return ch >= '4' && ch <= '7'; };
  152. // OctalDigit [lookahead ∉ OctalDigit]
  153. if (is_octal_digit(lexer.peek()) && !is_octal_digit(lexer.peek(1)))
  154. octal_str = lexer.consume(1);
  155. // ZeroToThree OctalDigit [lookahead ∉ OctalDigit]
  156. else if (is_zero_to_three(lexer.peek()) && is_octal_digit(lexer.peek(1)) && !is_octal_digit(lexer.peek(2)))
  157. octal_str = lexer.consume(2);
  158. // FourToSeven OctalDigit
  159. else if (is_four_to_seven(lexer.peek()) && is_octal_digit(lexer.peek(1)))
  160. octal_str = lexer.consume(2);
  161. // ZeroToThree OctalDigit OctalDigit
  162. else if (is_zero_to_three(lexer.peek()) && is_octal_digit(lexer.peek(1)) && is_octal_digit(lexer.peek(2)))
  163. octal_str = lexer.consume(3);
  164. if (!octal_str.is_null()) {
  165. status = StringValueStatus::LegacyOctalEscapeSequence;
  166. auto code_point = strtoul(octal_str.characters(), nullptr, 8);
  167. VERIFY(code_point <= 255);
  168. builder.append_code_point(code_point);
  169. continue;
  170. }
  171. lexer.retreat();
  172. builder.append(lexer.consume_escaped_character('\\', "b\bf\fn\nr\rt\tv\v"));
  173. }
  174. return builder.to_string();
  175. }
  176. bool Token::bool_value() const
  177. {
  178. VERIFY(type() == TokenType::BoolLiteral);
  179. return m_value == "true";
  180. }
  181. bool Token::is_identifier_name() const
  182. {
  183. // IdentifierNames are Identifiers + ReservedWords
  184. // The standard defines this reversed: Identifiers are IdentifierNames except reserved words
  185. // https://www.ecma-international.org/ecma-262/5.1/#sec-7.6
  186. return m_type == TokenType::Identifier
  187. || m_type == TokenType::Await
  188. || m_type == TokenType::BoolLiteral
  189. || m_type == TokenType::Break
  190. || m_type == TokenType::Case
  191. || m_type == TokenType::Catch
  192. || m_type == TokenType::Class
  193. || m_type == TokenType::Const
  194. || m_type == TokenType::Continue
  195. || m_type == TokenType::Default
  196. || m_type == TokenType::Delete
  197. || m_type == TokenType::Do
  198. || m_type == TokenType::Else
  199. || m_type == TokenType::Enum
  200. || m_type == TokenType::Export
  201. || m_type == TokenType::Extends
  202. || m_type == TokenType::Finally
  203. || m_type == TokenType::For
  204. || m_type == TokenType::Function
  205. || m_type == TokenType::If
  206. || m_type == TokenType::Import
  207. || m_type == TokenType::In
  208. || m_type == TokenType::Instanceof
  209. || m_type == TokenType::Interface
  210. || m_type == TokenType::Let
  211. || m_type == TokenType::New
  212. || m_type == TokenType::NullLiteral
  213. || m_type == TokenType::Return
  214. || m_type == TokenType::Super
  215. || m_type == TokenType::Switch
  216. || m_type == TokenType::This
  217. || m_type == TokenType::Throw
  218. || m_type == TokenType::Try
  219. || m_type == TokenType::Typeof
  220. || m_type == TokenType::Var
  221. || m_type == TokenType::Void
  222. || m_type == TokenType::While
  223. || m_type == TokenType::Yield;
  224. }
  225. bool Token::trivia_contains_line_terminator() const
  226. {
  227. return m_trivia.contains('\n') || m_trivia.contains('\r') || m_trivia.contains(LINE_SEPARATOR) || m_trivia.contains(PARAGRAPH_SEPARATOR);
  228. }
  229. }