Token.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. /*
  2. * Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@gmx.de>
  3. * Copyright (c) 2020, Linus Groh <mail@linusgroh.de>
  4. * All rights reserved.
  5. *
  6. * Redistribution and use in source and binary forms, with or without
  7. * modification, are permitted provided that the following conditions are met:
  8. *
  9. * 1. Redistributions of source code must retain the above copyright notice, this
  10. * list of conditions and the following disclaimer.
  11. *
  12. * 2. Redistributions in binary form must reproduce the above copyright notice,
  13. * this list of conditions and the following disclaimer in the documentation
  14. * and/or other materials provided with the distribution.
  15. *
  16. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  17. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  18. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  20. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  21. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  22. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  23. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  24. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  25. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. #include "Token.h"
  28. #include <AK/Assertions.h>
  29. #include <AK/GenericLexer.h>
  30. #include <AK/StringBuilder.h>
  31. #include <ctype.h>
  32. namespace JS {
  33. const char* Token::name(TokenType type)
  34. {
  35. switch (type) {
  36. #define __ENUMERATE_JS_TOKEN(type, category) \
  37. case TokenType::type: \
  38. return #type;
  39. ENUMERATE_JS_TOKENS
  40. #undef __ENUMERATE_JS_TOKEN
  41. default:
  42. ASSERT_NOT_REACHED();
  43. return "<Unknown>";
  44. }
  45. }
  46. const char* Token::name() const
  47. {
  48. return name(m_type);
  49. }
  50. TokenCategory Token::category(TokenType type)
  51. {
  52. switch (type) {
  53. #define __ENUMERATE_JS_TOKEN(type, category) \
  54. case TokenType::type: \
  55. return TokenCategory::category;
  56. ENUMERATE_JS_TOKENS
  57. #undef __ENUMERATE_JS_TOKEN
  58. default:
  59. ASSERT_NOT_REACHED();
  60. }
  61. }
  62. TokenCategory Token::category() const
  63. {
  64. return category(m_type);
  65. }
  66. double Token::double_value() const
  67. {
  68. ASSERT(type() == TokenType::NumericLiteral);
  69. String value_string(m_value);
  70. if (value_string[0] == '0' && value_string.length() >= 2) {
  71. if (value_string[1] == 'x' || value_string[1] == 'X') {
  72. // hexadecimal
  73. return static_cast<double>(strtoul(value_string.characters() + 2, nullptr, 16));
  74. } else if (value_string[1] == 'o' || value_string[1] == 'O') {
  75. // octal
  76. return static_cast<double>(strtoul(value_string.characters() + 2, nullptr, 8));
  77. } else if (value_string[1] == 'b' || value_string[1] == 'B') {
  78. // binary
  79. return static_cast<double>(strtoul(value_string.characters() + 2, nullptr, 2));
  80. } else if (isdigit(value_string[1])) {
  81. // also octal, but syntax error in strict mode
  82. if (!m_value.contains('8') && !m_value.contains('9'))
  83. return static_cast<double>(strtoul(value_string.characters() + 1, nullptr, 8));
  84. }
  85. }
  86. return strtod(value_string.characters(), nullptr);
  87. }
  88. static u32 hex2int(char x)
  89. {
  90. ASSERT(isxdigit(x));
  91. if (x >= '0' && x <= '9')
  92. return x - '0';
  93. return 10u + (tolower(x) - 'a');
  94. }
  95. String Token::string_value(StringValueStatus& status) const
  96. {
  97. ASSERT(type() == TokenType::StringLiteral || type() == TokenType::TemplateLiteralString);
  98. auto is_template = type() == TokenType::TemplateLiteralString;
  99. GenericLexer lexer(is_template ? m_value : m_value.substring_view(1, m_value.length() - 2));
  100. auto encoding_failure = [&status](StringValueStatus parse_status) -> String {
  101. status = parse_status;
  102. return {};
  103. };
  104. StringBuilder builder;
  105. while (!lexer.is_eof()) {
  106. // No escape, consume one char and continue
  107. if (!lexer.next_is('\\')) {
  108. builder.append(lexer.consume());
  109. continue;
  110. }
  111. lexer.ignore();
  112. ASSERT(!lexer.is_eof());
  113. // Line continuation
  114. if (lexer.next_is('\n') || lexer.next_is('\r')) {
  115. lexer.ignore();
  116. continue;
  117. }
  118. // Line continuation
  119. if (lexer.next_is(LINE_SEPARATOR) || lexer.next_is(PARAGRAPH_SEPARATOR)) {
  120. lexer.ignore(3);
  121. continue;
  122. }
  123. // Null-byte escape
  124. if (lexer.next_is('0') && !isdigit(lexer.peek(1))) {
  125. lexer.ignore();
  126. builder.append('\0');
  127. continue;
  128. }
  129. // Hex escape
  130. if (lexer.next_is('x')) {
  131. lexer.ignore();
  132. if (!isxdigit(lexer.peek()) || !isxdigit(lexer.peek(1)))
  133. return encoding_failure(StringValueStatus::MalformedHexEscape);
  134. auto code_point = hex2int(lexer.consume()) * 16 + hex2int(lexer.consume());
  135. ASSERT(code_point <= 255);
  136. builder.append_code_point(code_point);
  137. continue;
  138. }
  139. // Unicode escape
  140. if (lexer.next_is('u')) {
  141. lexer.ignore();
  142. u32 code_point = 0;
  143. if (lexer.next_is('{')) {
  144. lexer.ignore();
  145. while (true) {
  146. if (!lexer.next_is(isxdigit))
  147. return encoding_failure(StringValueStatus::MalformedUnicodeEscape);
  148. auto new_code_point = (code_point << 4u) | hex2int(lexer.consume());
  149. if (new_code_point < code_point)
  150. return encoding_failure(StringValueStatus::UnicodeEscapeOverflow);
  151. code_point = new_code_point;
  152. if (lexer.next_is('}'))
  153. break;
  154. }
  155. lexer.ignore();
  156. } else {
  157. for (int j = 0; j < 4; ++j) {
  158. if (!lexer.next_is(isxdigit))
  159. return encoding_failure(StringValueStatus::MalformedUnicodeEscape);
  160. code_point = (code_point << 4u) | hex2int(lexer.consume());
  161. }
  162. }
  163. builder.append_code_point(code_point);
  164. continue;
  165. }
  166. // In non-strict mode LegacyOctalEscapeSequence is allowed in strings:
  167. // https://tc39.es/ecma262/#sec-additional-syntax-string-literals
  168. String octal_str;
  169. auto is_octal_digit = [](char ch) { return ch >= '0' && ch <= '7'; };
  170. auto is_zero_to_three = [](char ch) { return ch >= '0' && ch <= '3'; };
  171. auto is_four_to_seven = [](char ch) { return ch >= '4' && ch <= '7'; };
  172. // OctalDigit [lookahead ∉ OctalDigit]
  173. if (is_octal_digit(lexer.peek()) && !is_octal_digit(lexer.peek(1)))
  174. octal_str = lexer.consume(1);
  175. // ZeroToThree OctalDigit [lookahead ∉ OctalDigit]
  176. else if (is_zero_to_three(lexer.peek()) && is_octal_digit(lexer.peek(1)) && !is_octal_digit(lexer.peek(2)))
  177. octal_str = lexer.consume(2);
  178. // FourToSeven OctalDigit
  179. else if (is_four_to_seven(lexer.peek()) && is_octal_digit(lexer.peek(1)))
  180. octal_str = lexer.consume(2);
  181. // ZeroToThree OctalDigit OctalDigit
  182. else if (is_zero_to_three(lexer.peek()) && is_octal_digit(lexer.peek(1)) && is_octal_digit(lexer.peek(2)))
  183. octal_str = lexer.consume(3);
  184. if (!octal_str.is_null()) {
  185. status = StringValueStatus::LegacyOctalEscapeSequence;
  186. auto code_point = strtoul(octal_str.characters(), nullptr, 8);
  187. ASSERT(code_point <= 255);
  188. builder.append_code_point(code_point);
  189. continue;
  190. }
  191. lexer.retreat();
  192. builder.append(lexer.consume_escaped_character('\\', "b\bf\fn\nr\rt\tv\v"));
  193. }
  194. return builder.to_string();
  195. }
  196. bool Token::bool_value() const
  197. {
  198. ASSERT(type() == TokenType::BoolLiteral);
  199. return m_value == "true";
  200. }
  201. bool Token::is_identifier_name() const
  202. {
  203. // IdentifierNames are Identifiers + ReservedWords
  204. // The standard defines this reversed: Identifiers are IdentifierNames except reserved words
  205. // https://www.ecma-international.org/ecma-262/5.1/#sec-7.6
  206. return m_type == TokenType::Identifier
  207. || m_type == TokenType::Await
  208. || m_type == TokenType::BoolLiteral
  209. || m_type == TokenType::Break
  210. || m_type == TokenType::Case
  211. || m_type == TokenType::Catch
  212. || m_type == TokenType::Class
  213. || m_type == TokenType::Const
  214. || m_type == TokenType::Continue
  215. || m_type == TokenType::Default
  216. || m_type == TokenType::Delete
  217. || m_type == TokenType::Do
  218. || m_type == TokenType::Else
  219. || m_type == TokenType::Enum
  220. || m_type == TokenType::Export
  221. || m_type == TokenType::Extends
  222. || m_type == TokenType::Finally
  223. || m_type == TokenType::For
  224. || m_type == TokenType::Function
  225. || m_type == TokenType::If
  226. || m_type == TokenType::Import
  227. || m_type == TokenType::In
  228. || m_type == TokenType::Instanceof
  229. || m_type == TokenType::Interface
  230. || m_type == TokenType::Let
  231. || m_type == TokenType::New
  232. || m_type == TokenType::NullLiteral
  233. || m_type == TokenType::Return
  234. || m_type == TokenType::Super
  235. || m_type == TokenType::Switch
  236. || m_type == TokenType::This
  237. || m_type == TokenType::Throw
  238. || m_type == TokenType::Try
  239. || m_type == TokenType::Typeof
  240. || m_type == TokenType::Var
  241. || m_type == TokenType::Void
  242. || m_type == TokenType::While
  243. || m_type == TokenType::Yield;
  244. }
  245. bool Token::trivia_contains_line_terminator() const
  246. {
  247. return m_trivia.contains('\n') || m_trivia.contains('\r') || m_trivia.contains(LINE_SEPARATOR) || m_trivia.contains(PARAGRAPH_SEPARATOR);
  248. }
  249. }