Lexer.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474
  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::DoubleAmpersand);
  95. s_two_char_tokens.set("||", TokenType::DoublePipe);
  96. s_two_char_tokens.set("??", TokenType::DoubleQuestionMark);
  97. s_two_char_tokens.set("**", TokenType::DoubleAsterisk);
  98. s_two_char_tokens.set("==", TokenType::EqualsEquals);
  99. s_two_char_tokens.set("<=", TokenType::LessThanEquals);
  100. s_two_char_tokens.set(">=", TokenType::GreaterThanEquals);
  101. s_two_char_tokens.set("!=", TokenType::ExclamationMarkEquals);
  102. s_two_char_tokens.set("--", TokenType::MinusMinus);
  103. s_two_char_tokens.set("++", TokenType::PlusPlus);
  104. s_two_char_tokens.set("<<", TokenType::ShiftLeft);
  105. s_two_char_tokens.set(">>", TokenType::ShiftRight);
  106. s_two_char_tokens.set("?.", TokenType::QuestionMarkPeriod);
  107. }
  108. if (s_single_char_tokens.is_empty()) {
  109. s_single_char_tokens.set('&', TokenType::Ampersand);
  110. s_single_char_tokens.set('*', TokenType::Asterisk);
  111. s_single_char_tokens.set('[', TokenType::BracketOpen);
  112. s_single_char_tokens.set(']', TokenType::BracketClose);
  113. s_single_char_tokens.set('^', TokenType::Caret);
  114. s_single_char_tokens.set(':', TokenType::Colon);
  115. s_single_char_tokens.set(',', TokenType::Comma);
  116. s_single_char_tokens.set('{', TokenType::CurlyOpen);
  117. s_single_char_tokens.set('}', TokenType::CurlyClose);
  118. s_single_char_tokens.set('=', TokenType::Equals);
  119. s_single_char_tokens.set('!', TokenType::ExclamationMark);
  120. s_single_char_tokens.set('-', TokenType::Minus);
  121. s_single_char_tokens.set('(', TokenType::ParenOpen);
  122. s_single_char_tokens.set(')', TokenType::ParenClose);
  123. s_single_char_tokens.set('%', TokenType::Percent);
  124. s_single_char_tokens.set('.', TokenType::Period);
  125. s_single_char_tokens.set('|', TokenType::Pipe);
  126. s_single_char_tokens.set('+', TokenType::Plus);
  127. s_single_char_tokens.set('?', TokenType::QuestionMark);
  128. s_single_char_tokens.set(';', TokenType::Semicolon);
  129. s_single_char_tokens.set('/', TokenType::Slash);
  130. s_single_char_tokens.set('~', TokenType::Tilde);
  131. s_single_char_tokens.set('<', TokenType::LessThan);
  132. s_single_char_tokens.set('>', TokenType::GreaterThan);
  133. }
  134. consume();
  135. }
  136. void Lexer::consume()
  137. {
  138. if (m_position >= m_source.length()) {
  139. m_position = m_source.length() + 1;
  140. m_current_char = EOF;
  141. return;
  142. }
  143. if (m_current_char == '\n') {
  144. m_line_number++;
  145. m_line_column = 1;
  146. } else {
  147. m_line_column++;
  148. }
  149. m_current_char = m_source[m_position++];
  150. }
  151. void Lexer::consume_exponent()
  152. {
  153. consume();
  154. if (m_current_char == '-' || m_current_char == '+')
  155. consume();
  156. while (isdigit(m_current_char)) {
  157. consume();
  158. }
  159. }
  160. bool Lexer::match(char a, char b) const
  161. {
  162. if (m_position >= m_source.length())
  163. return false;
  164. return m_current_char == a
  165. && m_source[m_position] == b;
  166. }
  167. bool Lexer::match(char a, char b, char c) const
  168. {
  169. if (m_position + 1 >= m_source.length())
  170. return false;
  171. return m_current_char == a
  172. && m_source[m_position] == b
  173. && m_source[m_position + 1] == c;
  174. }
  175. bool Lexer::match(char a, char b, char c, char d) const
  176. {
  177. if (m_position + 2 >= m_source.length())
  178. return false;
  179. return m_current_char == a
  180. && m_source[m_position] == b
  181. && m_source[m_position + 1] == c
  182. && m_source[m_position + 2] == d;
  183. }
  184. bool Lexer::is_eof() const
  185. {
  186. return m_current_char == EOF;
  187. }
  188. bool Lexer::is_identifier_start() const
  189. {
  190. return isalpha(m_current_char) || m_current_char == '_' || m_current_char == '$';
  191. }
  192. bool Lexer::is_identifier_middle() const
  193. {
  194. return is_identifier_start() || isdigit(m_current_char);
  195. }
  196. bool Lexer::is_line_comment_start() const
  197. {
  198. return match('/', '/') || match('<', '!', '-', '-') || match('-', '-', '>');
  199. }
  200. bool Lexer::is_block_comment_start() const
  201. {
  202. return match('/', '*');
  203. }
  204. bool Lexer::is_block_comment_end() const
  205. {
  206. return match('*', '/');
  207. }
  208. bool Lexer::is_numeric_literal_start() const
  209. {
  210. return isdigit(m_current_char) || (m_current_char == '.' && m_position < m_source.length() && isdigit(m_source[m_position]));
  211. }
  212. void Lexer::syntax_error(const char* msg)
  213. {
  214. m_has_errors = true;
  215. if (m_log_errors)
  216. fprintf(stderr, "Syntax Error: %s (line: %zu, column: %zu)\n", msg, m_line_number, m_line_column);
  217. }
  218. Token Lexer::next()
  219. {
  220. size_t trivia_start = m_position;
  221. auto in_template = !m_template_states.is_empty();
  222. if (!in_template || m_template_states.last().in_expr) {
  223. // consume whitespace and comments
  224. while (true) {
  225. if (isspace(m_current_char)) {
  226. do {
  227. consume();
  228. } while (isspace(m_current_char));
  229. } else if (is_line_comment_start()) {
  230. consume();
  231. do {
  232. consume();
  233. } while (!is_eof() && m_current_char != '\n');
  234. } else if (is_block_comment_start()) {
  235. consume();
  236. do {
  237. consume();
  238. } while (!is_eof() && !is_block_comment_end());
  239. consume(); // consume *
  240. consume(); // consume /
  241. } else {
  242. break;
  243. }
  244. }
  245. }
  246. size_t value_start = m_position;
  247. auto token_type = TokenType::Invalid;
  248. if (m_current_char == '`') {
  249. consume();
  250. if (!in_template) {
  251. token_type = TokenType::TemplateLiteralStart;
  252. m_template_states.append({ false, 0 });
  253. } else {
  254. if (m_template_states.last().in_expr) {
  255. m_template_states.append({ false, 0 });
  256. token_type = TokenType::TemplateLiteralStart;
  257. } else {
  258. m_template_states.take_last();
  259. token_type = TokenType::TemplateLiteralEnd;
  260. }
  261. }
  262. } else if (in_template && m_template_states.last().in_expr && m_template_states.last().open_bracket_count == 0 && m_current_char == '}') {
  263. consume();
  264. token_type = TokenType::TemplateLiteralExprEnd;
  265. m_template_states.last().in_expr = false;
  266. } else if (in_template && !m_template_states.last().in_expr) {
  267. if (is_eof()) {
  268. token_type = TokenType::UnterminatedTemplateLiteral;
  269. m_template_states.take_last();
  270. } else if (match('$', '{')) {
  271. token_type = TokenType::TemplateLiteralExprStart;
  272. consume();
  273. consume();
  274. m_template_states.last().in_expr = true;
  275. } else {
  276. while (!match('$', '{') && m_current_char != '`' && !is_eof()) {
  277. if (match('\\', '$') || match('\\', '`'))
  278. consume();
  279. consume();
  280. }
  281. token_type = TokenType::TemplateLiteralString;
  282. }
  283. } else if (is_identifier_start()) {
  284. // identifier or keyword
  285. do {
  286. consume();
  287. } while (is_identifier_middle());
  288. StringView value = m_source.substring_view(value_start - 1, m_position - value_start);
  289. auto it = s_keywords.find(value);
  290. if (it == s_keywords.end()) {
  291. token_type = TokenType::Identifier;
  292. } else {
  293. token_type = it->value;
  294. }
  295. } else if (is_numeric_literal_start()) {
  296. if (m_current_char == '0') {
  297. consume();
  298. if (m_current_char == '.') {
  299. // decimal
  300. consume();
  301. while (isdigit(m_current_char)) {
  302. consume();
  303. }
  304. if (m_current_char == 'e' || m_current_char == 'E') {
  305. consume_exponent();
  306. }
  307. } else if (m_current_char == 'e' || m_current_char == 'E') {
  308. consume_exponent();
  309. } else if (m_current_char == 'o' || m_current_char == 'O') {
  310. // octal
  311. consume();
  312. while (m_current_char >= '0' && m_current_char <= '7') {
  313. consume();
  314. }
  315. } else if (m_current_char == 'b' || m_current_char == 'B') {
  316. // binary
  317. consume();
  318. while (m_current_char == '0' || m_current_char == '1') {
  319. consume();
  320. }
  321. } else if (m_current_char == 'x' || m_current_char == 'X') {
  322. // hexadecimal
  323. consume();
  324. while (isxdigit(m_current_char)) {
  325. consume();
  326. }
  327. } else if (isdigit(m_current_char)) {
  328. // octal without 'O' prefix. Forbidden in 'strict mode'
  329. // FIXME: We need to make sure this produces a syntax error when in strict mode
  330. do {
  331. consume();
  332. } while (isdigit(m_current_char));
  333. }
  334. } else {
  335. // 1...9 or period
  336. while (isdigit(m_current_char)) {
  337. consume();
  338. }
  339. if (m_current_char == '.') {
  340. consume();
  341. while (isdigit(m_current_char)) {
  342. consume();
  343. }
  344. }
  345. if (m_current_char == 'e' || m_current_char == 'E') {
  346. consume_exponent();
  347. }
  348. }
  349. token_type = TokenType::NumericLiteral;
  350. } else if (m_current_char == '"' || m_current_char == '\'') {
  351. char stop_char = m_current_char;
  352. consume();
  353. while (m_current_char != stop_char && m_current_char != '\n' && !is_eof()) {
  354. if (m_current_char == '\\') {
  355. consume();
  356. }
  357. consume();
  358. }
  359. if (m_current_char != stop_char) {
  360. syntax_error("unterminated string literal");
  361. token_type = TokenType::UnterminatedStringLiteral;
  362. } else {
  363. consume();
  364. token_type = TokenType::StringLiteral;
  365. }
  366. } else if (m_current_char == EOF) {
  367. token_type = TokenType::Eof;
  368. } else {
  369. // There is only one four-char operator: >>>=
  370. bool found_four_char_token = false;
  371. if (match('>', '>', '>', '=')) {
  372. found_four_char_token = true;
  373. consume();
  374. consume();
  375. consume();
  376. consume();
  377. token_type = TokenType::UnsignedShiftRightEquals;
  378. }
  379. bool found_three_char_token = false;
  380. if (!found_four_char_token && m_position + 1 < m_source.length()) {
  381. char second_char = m_source[m_position];
  382. char third_char = m_source[m_position + 1];
  383. char three_chars[] { (char)m_current_char, second_char, third_char, 0 };
  384. auto it = s_three_char_tokens.find(three_chars);
  385. if (it != s_three_char_tokens.end()) {
  386. found_three_char_token = true;
  387. consume();
  388. consume();
  389. consume();
  390. token_type = it->value;
  391. }
  392. }
  393. bool found_two_char_token = false;
  394. if (!found_four_char_token && !found_three_char_token && m_position < m_source.length()) {
  395. char second_char = m_source[m_position];
  396. char two_chars[] { (char)m_current_char, second_char, 0 };
  397. auto it = s_two_char_tokens.find(two_chars);
  398. if (it != s_two_char_tokens.end()) {
  399. found_two_char_token = true;
  400. consume();
  401. consume();
  402. token_type = it->value;
  403. }
  404. }
  405. bool found_one_char_token = false;
  406. if (!found_four_char_token && !found_three_char_token && !found_two_char_token) {
  407. auto it = s_single_char_tokens.find(m_current_char);
  408. if (it != s_single_char_tokens.end()) {
  409. found_one_char_token = true;
  410. consume();
  411. token_type = it->value;
  412. }
  413. }
  414. if (!found_four_char_token && !found_three_char_token && !found_two_char_token && !found_one_char_token) {
  415. consume();
  416. token_type = TokenType::Invalid;
  417. }
  418. }
  419. if (!m_template_states.is_empty() && m_template_states.last().in_expr) {
  420. if (token_type == TokenType::CurlyOpen) {
  421. m_template_states.last().open_bracket_count++;
  422. } else if (token_type == TokenType::CurlyClose) {
  423. m_template_states.last().open_bracket_count--;
  424. }
  425. }
  426. m_current_token = Token(
  427. token_type,
  428. m_source.substring_view(trivia_start - 1, value_start - trivia_start),
  429. m_source.substring_view(value_start - 1, m_position - value_start),
  430. m_line_number,
  431. m_line_column - m_position + value_start);
  432. return m_current_token;
  433. }
  434. }