Lexer.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475
  1. /*
  2. * Copyright (c) 2020, Stephan Unverwerth <s.unverwerth@gmx.de>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include "Lexer.h"
  27. #include <AK/HashMap.h>
  28. #include <AK/StringBuilder.h>
  29. #include <ctype.h>
  30. #include <stdio.h>
  31. namespace JS {
  32. HashMap<String, TokenType> Lexer::s_keywords;
  33. HashMap<String, TokenType> Lexer::s_three_char_tokens;
  34. HashMap<String, TokenType> Lexer::s_two_char_tokens;
  35. HashMap<char, TokenType> Lexer::s_single_char_tokens;
  36. Lexer::Lexer(StringView source)
  37. : m_source(source)
  38. , m_current_token(TokenType::Eof, StringView(nullptr), StringView(nullptr), 0, 0)
  39. {
  40. if (s_keywords.is_empty()) {
  41. s_keywords.set("await", TokenType::Await);
  42. s_keywords.set("break", TokenType::Break);
  43. s_keywords.set("case", TokenType::Case);
  44. s_keywords.set("catch", TokenType::Catch);
  45. s_keywords.set("class", TokenType::Class);
  46. s_keywords.set("const", TokenType::Const);
  47. s_keywords.set("continue", TokenType::Continue);
  48. s_keywords.set("debugger", TokenType::Debugger);
  49. s_keywords.set("default", TokenType::Default);
  50. s_keywords.set("delete", TokenType::Delete);
  51. s_keywords.set("do", TokenType::Do);
  52. s_keywords.set("else", TokenType::Else);
  53. s_keywords.set("false", TokenType::BoolLiteral);
  54. s_keywords.set("finally", TokenType::Finally);
  55. s_keywords.set("for", TokenType::For);
  56. s_keywords.set("function", TokenType::Function);
  57. s_keywords.set("if", TokenType::If);
  58. s_keywords.set("in", TokenType::In);
  59. s_keywords.set("instanceof", TokenType::Instanceof);
  60. s_keywords.set("interface", TokenType::Interface);
  61. s_keywords.set("let", TokenType::Let);
  62. s_keywords.set("new", TokenType::New);
  63. s_keywords.set("null", TokenType::NullLiteral);
  64. s_keywords.set("return", TokenType::Return);
  65. s_keywords.set("switch", TokenType::Switch);
  66. s_keywords.set("this", TokenType::This);
  67. s_keywords.set("throw", TokenType::Throw);
  68. s_keywords.set("true", TokenType::BoolLiteral);
  69. s_keywords.set("try", TokenType::Try);
  70. s_keywords.set("typeof", TokenType::Typeof);
  71. s_keywords.set("var", TokenType::Var);
  72. s_keywords.set("void", TokenType::Void);
  73. s_keywords.set("while", TokenType::While);
  74. s_keywords.set("yield", TokenType::Yield);
  75. }
  76. if (s_three_char_tokens.is_empty()) {
  77. s_three_char_tokens.set("===", TokenType::EqualsEqualsEquals);
  78. s_three_char_tokens.set("!==", TokenType::ExclamationMarkEqualsEquals);
  79. s_three_char_tokens.set("**=", TokenType::AsteriskAsteriskEquals);
  80. s_three_char_tokens.set("<<=", TokenType::ShiftLeftEquals);
  81. s_three_char_tokens.set(">>=", TokenType::ShiftRightEquals);
  82. s_three_char_tokens.set(">>>", TokenType::UnsignedShiftRight);
  83. s_three_char_tokens.set("...", TokenType::TripleDot);
  84. }
  85. if (s_two_char_tokens.is_empty()) {
  86. s_two_char_tokens.set("=>", TokenType::Arrow);
  87. s_two_char_tokens.set("+=", TokenType::PlusEquals);
  88. s_two_char_tokens.set("-=", TokenType::MinusEquals);
  89. s_two_char_tokens.set("*=", TokenType::AsteriskEquals);
  90. s_two_char_tokens.set("/=", TokenType::SlashEquals);
  91. s_two_char_tokens.set("%=", TokenType::PercentEquals);
  92. s_two_char_tokens.set("&=", TokenType::AmpersandEquals);
  93. s_two_char_tokens.set("|=", TokenType::PipeEquals);
  94. s_two_char_tokens.set("^=", TokenType::CaretEquals);
  95. s_two_char_tokens.set("&&", TokenType::DoubleAmpersand);
  96. s_two_char_tokens.set("||", TokenType::DoublePipe);
  97. s_two_char_tokens.set("??", TokenType::DoubleQuestionMark);
  98. s_two_char_tokens.set("**", TokenType::DoubleAsterisk);
  99. s_two_char_tokens.set("==", TokenType::EqualsEquals);
  100. s_two_char_tokens.set("<=", TokenType::LessThanEquals);
  101. s_two_char_tokens.set(">=", TokenType::GreaterThanEquals);
  102. s_two_char_tokens.set("!=", TokenType::ExclamationMarkEquals);
  103. s_two_char_tokens.set("--", TokenType::MinusMinus);
  104. s_two_char_tokens.set("++", TokenType::PlusPlus);
  105. s_two_char_tokens.set("<<", TokenType::ShiftLeft);
  106. s_two_char_tokens.set(">>", TokenType::ShiftRight);
  107. s_two_char_tokens.set("?.", TokenType::QuestionMarkPeriod);
  108. }
  109. if (s_single_char_tokens.is_empty()) {
  110. s_single_char_tokens.set('&', TokenType::Ampersand);
  111. s_single_char_tokens.set('*', TokenType::Asterisk);
  112. s_single_char_tokens.set('[', TokenType::BracketOpen);
  113. s_single_char_tokens.set(']', TokenType::BracketClose);
  114. s_single_char_tokens.set('^', TokenType::Caret);
  115. s_single_char_tokens.set(':', TokenType::Colon);
  116. s_single_char_tokens.set(',', TokenType::Comma);
  117. s_single_char_tokens.set('{', TokenType::CurlyOpen);
  118. s_single_char_tokens.set('}', TokenType::CurlyClose);
  119. s_single_char_tokens.set('=', TokenType::Equals);
  120. s_single_char_tokens.set('!', TokenType::ExclamationMark);
  121. s_single_char_tokens.set('-', TokenType::Minus);
  122. s_single_char_tokens.set('(', TokenType::ParenOpen);
  123. s_single_char_tokens.set(')', TokenType::ParenClose);
  124. s_single_char_tokens.set('%', TokenType::Percent);
  125. s_single_char_tokens.set('.', TokenType::Period);
  126. s_single_char_tokens.set('|', TokenType::Pipe);
  127. s_single_char_tokens.set('+', TokenType::Plus);
  128. s_single_char_tokens.set('?', TokenType::QuestionMark);
  129. s_single_char_tokens.set(';', TokenType::Semicolon);
  130. s_single_char_tokens.set('/', TokenType::Slash);
  131. s_single_char_tokens.set('~', TokenType::Tilde);
  132. s_single_char_tokens.set('<', TokenType::LessThan);
  133. s_single_char_tokens.set('>', TokenType::GreaterThan);
  134. }
  135. consume();
  136. }
  137. void Lexer::consume()
  138. {
  139. if (m_position >= m_source.length()) {
  140. m_position = m_source.length() + 1;
  141. m_current_char = EOF;
  142. return;
  143. }
  144. if (m_current_char == '\n') {
  145. m_line_number++;
  146. m_line_column = 1;
  147. } else {
  148. m_line_column++;
  149. }
  150. m_current_char = m_source[m_position++];
  151. }
  152. void Lexer::consume_exponent()
  153. {
  154. consume();
  155. if (m_current_char == '-' || m_current_char == '+')
  156. consume();
  157. while (isdigit(m_current_char)) {
  158. consume();
  159. }
  160. }
  161. bool Lexer::match(char a, char b) const
  162. {
  163. if (m_position >= m_source.length())
  164. return false;
  165. return m_current_char == a
  166. && m_source[m_position] == b;
  167. }
  168. bool Lexer::match(char a, char b, char c) const
  169. {
  170. if (m_position + 1 >= m_source.length())
  171. return false;
  172. return m_current_char == a
  173. && m_source[m_position] == b
  174. && m_source[m_position + 1] == c;
  175. }
  176. bool Lexer::match(char a, char b, char c, char d) const
  177. {
  178. if (m_position + 2 >= m_source.length())
  179. return false;
  180. return m_current_char == a
  181. && m_source[m_position] == b
  182. && m_source[m_position + 1] == c
  183. && m_source[m_position + 2] == d;
  184. }
  185. bool Lexer::is_eof() const
  186. {
  187. return m_current_char == EOF;
  188. }
  189. bool Lexer::is_identifier_start() const
  190. {
  191. return isalpha(m_current_char) || m_current_char == '_' || m_current_char == '$';
  192. }
  193. bool Lexer::is_identifier_middle() const
  194. {
  195. return is_identifier_start() || isdigit(m_current_char);
  196. }
  197. bool Lexer::is_line_comment_start() const
  198. {
  199. return match('/', '/') || match('<', '!', '-', '-') || match('-', '-', '>');
  200. }
  201. bool Lexer::is_block_comment_start() const
  202. {
  203. return match('/', '*');
  204. }
  205. bool Lexer::is_block_comment_end() const
  206. {
  207. return match('*', '/');
  208. }
  209. bool Lexer::is_numeric_literal_start() const
  210. {
  211. return isdigit(m_current_char) || (m_current_char == '.' && m_position < m_source.length() && isdigit(m_source[m_position]));
  212. }
  213. void Lexer::syntax_error(const char* msg)
  214. {
  215. m_has_errors = true;
  216. if (m_log_errors)
  217. fprintf(stderr, "Syntax Error: %s (line: %zu, column: %zu)\n", msg, m_line_number, m_line_column);
  218. }
  219. Token Lexer::next()
  220. {
  221. size_t trivia_start = m_position;
  222. auto in_template = !m_template_states.is_empty();
  223. if (!in_template || m_template_states.last().in_expr) {
  224. // consume whitespace and comments
  225. while (true) {
  226. if (isspace(m_current_char)) {
  227. do {
  228. consume();
  229. } while (isspace(m_current_char));
  230. } else if (is_line_comment_start()) {
  231. consume();
  232. do {
  233. consume();
  234. } while (!is_eof() && m_current_char != '\n');
  235. } else if (is_block_comment_start()) {
  236. consume();
  237. do {
  238. consume();
  239. } while (!is_eof() && !is_block_comment_end());
  240. consume(); // consume *
  241. consume(); // consume /
  242. } else {
  243. break;
  244. }
  245. }
  246. }
  247. size_t value_start = m_position;
  248. auto token_type = TokenType::Invalid;
  249. if (m_current_char == '`') {
  250. consume();
  251. if (!in_template) {
  252. token_type = TokenType::TemplateLiteralStart;
  253. m_template_states.append({ false, 0 });
  254. } else {
  255. if (m_template_states.last().in_expr) {
  256. m_template_states.append({ false, 0 });
  257. token_type = TokenType::TemplateLiteralStart;
  258. } else {
  259. m_template_states.take_last();
  260. token_type = TokenType::TemplateLiteralEnd;
  261. }
  262. }
  263. } else if (in_template && m_template_states.last().in_expr && m_template_states.last().open_bracket_count == 0 && m_current_char == '}') {
  264. consume();
  265. token_type = TokenType::TemplateLiteralExprEnd;
  266. m_template_states.last().in_expr = false;
  267. } else if (in_template && !m_template_states.last().in_expr) {
  268. if (is_eof()) {
  269. token_type = TokenType::UnterminatedTemplateLiteral;
  270. m_template_states.take_last();
  271. } else if (match('$', '{')) {
  272. token_type = TokenType::TemplateLiteralExprStart;
  273. consume();
  274. consume();
  275. m_template_states.last().in_expr = true;
  276. } else {
  277. while (!match('$', '{') && m_current_char != '`' && !is_eof()) {
  278. if (match('\\', '$') || match('\\', '`'))
  279. consume();
  280. consume();
  281. }
  282. token_type = TokenType::TemplateLiteralString;
  283. }
  284. } else if (is_identifier_start()) {
  285. // identifier or keyword
  286. do {
  287. consume();
  288. } while (is_identifier_middle());
  289. StringView value = m_source.substring_view(value_start - 1, m_position - value_start);
  290. auto it = s_keywords.find(value);
  291. if (it == s_keywords.end()) {
  292. token_type = TokenType::Identifier;
  293. } else {
  294. token_type = it->value;
  295. }
  296. } else if (is_numeric_literal_start()) {
  297. if (m_current_char == '0') {
  298. consume();
  299. if (m_current_char == '.') {
  300. // decimal
  301. consume();
  302. while (isdigit(m_current_char)) {
  303. consume();
  304. }
  305. if (m_current_char == 'e' || m_current_char == 'E') {
  306. consume_exponent();
  307. }
  308. } else if (m_current_char == 'e' || m_current_char == 'E') {
  309. consume_exponent();
  310. } else if (m_current_char == 'o' || m_current_char == 'O') {
  311. // octal
  312. consume();
  313. while (m_current_char >= '0' && m_current_char <= '7') {
  314. consume();
  315. }
  316. } else if (m_current_char == 'b' || m_current_char == 'B') {
  317. // binary
  318. consume();
  319. while (m_current_char == '0' || m_current_char == '1') {
  320. consume();
  321. }
  322. } else if (m_current_char == 'x' || m_current_char == 'X') {
  323. // hexadecimal
  324. consume();
  325. while (isxdigit(m_current_char)) {
  326. consume();
  327. }
  328. } else if (isdigit(m_current_char)) {
  329. // octal without 'O' prefix. Forbidden in 'strict mode'
  330. // FIXME: We need to make sure this produces a syntax error when in strict mode
  331. do {
  332. consume();
  333. } while (isdigit(m_current_char));
  334. }
  335. } else {
  336. // 1...9 or period
  337. while (isdigit(m_current_char)) {
  338. consume();
  339. }
  340. if (m_current_char == '.') {
  341. consume();
  342. while (isdigit(m_current_char)) {
  343. consume();
  344. }
  345. }
  346. if (m_current_char == 'e' || m_current_char == 'E') {
  347. consume_exponent();
  348. }
  349. }
  350. token_type = TokenType::NumericLiteral;
  351. } else if (m_current_char == '"' || m_current_char == '\'') {
  352. char stop_char = m_current_char;
  353. consume();
  354. while (m_current_char != stop_char && m_current_char != '\n' && !is_eof()) {
  355. if (m_current_char == '\\') {
  356. consume();
  357. }
  358. consume();
  359. }
  360. if (m_current_char != stop_char) {
  361. syntax_error("unterminated string literal");
  362. token_type = TokenType::UnterminatedStringLiteral;
  363. } else {
  364. consume();
  365. token_type = TokenType::StringLiteral;
  366. }
  367. } else if (m_current_char == EOF) {
  368. token_type = TokenType::Eof;
  369. } else {
  370. // There is only one four-char operator: >>>=
  371. bool found_four_char_token = false;
  372. if (match('>', '>', '>', '=')) {
  373. found_four_char_token = true;
  374. consume();
  375. consume();
  376. consume();
  377. consume();
  378. token_type = TokenType::UnsignedShiftRightEquals;
  379. }
  380. bool found_three_char_token = false;
  381. if (!found_four_char_token && m_position + 1 < m_source.length()) {
  382. char second_char = m_source[m_position];
  383. char third_char = m_source[m_position + 1];
  384. char three_chars[] { (char)m_current_char, second_char, third_char, 0 };
  385. auto it = s_three_char_tokens.find(three_chars);
  386. if (it != s_three_char_tokens.end()) {
  387. found_three_char_token = true;
  388. consume();
  389. consume();
  390. consume();
  391. token_type = it->value;
  392. }
  393. }
  394. bool found_two_char_token = false;
  395. if (!found_four_char_token && !found_three_char_token && m_position < m_source.length()) {
  396. char second_char = m_source[m_position];
  397. char two_chars[] { (char)m_current_char, second_char, 0 };
  398. auto it = s_two_char_tokens.find(two_chars);
  399. if (it != s_two_char_tokens.end()) {
  400. found_two_char_token = true;
  401. consume();
  402. consume();
  403. token_type = it->value;
  404. }
  405. }
  406. bool found_one_char_token = false;
  407. if (!found_four_char_token && !found_three_char_token && !found_two_char_token) {
  408. auto it = s_single_char_tokens.find(m_current_char);
  409. if (it != s_single_char_tokens.end()) {
  410. found_one_char_token = true;
  411. consume();
  412. token_type = it->value;
  413. }
  414. }
  415. if (!found_four_char_token && !found_three_char_token && !found_two_char_token && !found_one_char_token) {
  416. consume();
  417. token_type = TokenType::Invalid;
  418. }
  419. }
  420. if (!m_template_states.is_empty() && m_template_states.last().in_expr) {
  421. if (token_type == TokenType::CurlyOpen) {
  422. m_template_states.last().open_bracket_count++;
  423. } else if (token_type == TokenType::CurlyClose) {
  424. m_template_states.last().open_bracket_count--;
  425. }
  426. }
  427. m_current_token = Token(
  428. token_type,
  429. m_source.substring_view(trivia_start - 1, value_start - trivia_start),
  430. m_source.substring_view(value_start - 1, m_position - value_start),
  431. m_line_number,
  432. m_line_column - m_position + value_start);
  433. return m_current_token;
  434. }
  435. }