Token.cpp 9.2 KB

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