Token.cpp 9.6 KB

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