CppLexer.cpp 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  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 "CppLexer.h"
  27. #include <AK/HashTable.h>
  28. #include <AK/String.h>
  29. #include <ctype.h>
  30. namespace GUI {
  31. CppLexer::CppLexer(const StringView& input)
  32. : m_input(input)
  33. {
  34. }
  35. char CppLexer::peek(size_t offset) const
  36. {
  37. if ((m_index + offset) >= m_input.length())
  38. return 0;
  39. return m_input[m_index + offset];
  40. }
  41. char CppLexer::consume()
  42. {
  43. ASSERT(m_index < m_input.length());
  44. char ch = m_input[m_index++];
  45. m_previous_position = m_position;
  46. if (ch == '\n') {
  47. m_position.line++;
  48. m_position.column = 0;
  49. } else {
  50. m_position.column++;
  51. }
  52. return ch;
  53. }
  54. static bool is_valid_first_character_of_identifier(char ch)
  55. {
  56. return isalpha(ch) || ch == '_' || ch == '$';
  57. }
  58. static bool is_valid_nonfirst_character_of_identifier(char ch)
  59. {
  60. return is_valid_first_character_of_identifier(ch) || isdigit(ch);
  61. }
  62. static bool is_keyword(const StringView& string)
  63. {
  64. static HashTable<String> keywords;
  65. if (keywords.is_empty()) {
  66. keywords.set("alignas");
  67. keywords.set("alignof");
  68. keywords.set("and");
  69. keywords.set("and_eq");
  70. keywords.set("asm");
  71. keywords.set("bitand");
  72. keywords.set("bitor");
  73. keywords.set("bool");
  74. keywords.set("break");
  75. keywords.set("case");
  76. keywords.set("catch");
  77. keywords.set("class");
  78. keywords.set("compl");
  79. keywords.set("const");
  80. keywords.set("const_cast");
  81. keywords.set("constexpr");
  82. keywords.set("continue");
  83. keywords.set("decltype");
  84. keywords.set("default");
  85. keywords.set("delete");
  86. keywords.set("do");
  87. keywords.set("dynamic_cast");
  88. keywords.set("else");
  89. keywords.set("enum");
  90. keywords.set("explicit");
  91. keywords.set("export");
  92. keywords.set("extern");
  93. keywords.set("false");
  94. keywords.set("final");
  95. keywords.set("for");
  96. keywords.set("friend");
  97. keywords.set("goto");
  98. keywords.set("if");
  99. keywords.set("inline");
  100. keywords.set("mutable");
  101. keywords.set("namespace");
  102. keywords.set("new");
  103. keywords.set("noexcept");
  104. keywords.set("not");
  105. keywords.set("not_eq");
  106. keywords.set("nullptr");
  107. keywords.set("operator");
  108. keywords.set("or");
  109. keywords.set("or_eq");
  110. keywords.set("override");
  111. keywords.set("private");
  112. keywords.set("protected");
  113. keywords.set("public");
  114. keywords.set("register");
  115. keywords.set("reinterpret_cast");
  116. keywords.set("return");
  117. keywords.set("signed");
  118. keywords.set("sizeof");
  119. keywords.set("static");
  120. keywords.set("static_assert");
  121. keywords.set("static_cast");
  122. keywords.set("struct");
  123. keywords.set("switch");
  124. keywords.set("template");
  125. keywords.set("this");
  126. keywords.set("thread_local");
  127. keywords.set("throw");
  128. keywords.set("true");
  129. keywords.set("try");
  130. keywords.set("typedef");
  131. keywords.set("typeid");
  132. keywords.set("typename");
  133. keywords.set("union");
  134. keywords.set("using");
  135. keywords.set("virtual");
  136. keywords.set("volatile");
  137. keywords.set("while");
  138. keywords.set("xor");
  139. keywords.set("xor_eq");
  140. }
  141. return keywords.contains(string);
  142. }
  143. static bool is_known_type(const StringView& string)
  144. {
  145. static HashTable<String> types;
  146. if (types.is_empty()) {
  147. types.set("ByteBuffer");
  148. types.set("CircularDeque");
  149. types.set("CircularQueue");
  150. types.set("Deque");
  151. types.set("DoublyLinkedList");
  152. types.set("FileSystemPath");
  153. types.set("FixedArray");
  154. types.set("Function");
  155. types.set("HashMap");
  156. types.set("HashTable");
  157. types.set("IPv4Address");
  158. types.set("InlineLinkedList");
  159. types.set("IntrusiveList");
  160. types.set("JsonArray");
  161. types.set("JsonObject");
  162. types.set("JsonValue");
  163. types.set("MappedFile");
  164. types.set("NetworkOrdered");
  165. types.set("NonnullOwnPtr");
  166. types.set("NonnullOwnPtrVector");
  167. types.set("NonnullRefPtr");
  168. types.set("NonnullRefPtrVector");
  169. types.set("Optional");
  170. types.set("OwnPtr");
  171. types.set("RefPtr");
  172. types.set("Result");
  173. types.set("ScopeGuard");
  174. types.set("SinglyLinkedList");
  175. types.set("String");
  176. types.set("StringBuilder");
  177. types.set("StringImpl");
  178. types.set("StringView");
  179. types.set("Utf8View");
  180. types.set("Vector");
  181. types.set("WeakPtr");
  182. types.set("auto");
  183. types.set("char");
  184. types.set("char16_t");
  185. types.set("char32_t");
  186. types.set("char8_t");
  187. types.set("double");
  188. types.set("float");
  189. types.set("i16");
  190. types.set("i32");
  191. types.set("i64");
  192. types.set("i8");
  193. types.set("int");
  194. types.set("int");
  195. types.set("long");
  196. types.set("short");
  197. types.set("signed");
  198. types.set("u16");
  199. types.set("u32");
  200. types.set("u64");
  201. types.set("u8");
  202. types.set("unsigned");
  203. types.set("void");
  204. types.set("wchar_t");
  205. }
  206. return types.contains(string);
  207. }
  208. Vector<CppToken> CppLexer::lex()
  209. {
  210. Vector<CppToken> tokens;
  211. size_t token_start_index = 0;
  212. CppPosition token_start_position;
  213. auto emit_token = [&](auto type) {
  214. CppToken token;
  215. token.m_type = type;
  216. token.m_start = m_position;
  217. token.m_end = m_position;
  218. tokens.append(token);
  219. consume();
  220. };
  221. auto begin_token = [&] {
  222. token_start_index = m_index;
  223. token_start_position = m_position;
  224. };
  225. auto commit_token = [&](auto type) {
  226. CppToken token;
  227. token.m_type = type;
  228. token.m_start = token_start_position;
  229. token.m_end = m_previous_position;
  230. tokens.append(token);
  231. };
  232. auto emit_token_equals = [&](auto type, auto equals_type) {
  233. if (peek(1) == '=') {
  234. begin_token();
  235. consume();
  236. consume();
  237. commit_token(equals_type);
  238. return;
  239. }
  240. emit_token(type);
  241. };
  242. auto match_escape_sequence = [&]() -> size_t {
  243. switch (peek(1)) {
  244. case '\'':
  245. case '"':
  246. case '?':
  247. case '\\':
  248. case 'a':
  249. case 'b':
  250. case 'f':
  251. case 'n':
  252. case 'r':
  253. case 't':
  254. case 'v':
  255. return 2;
  256. case '0':
  257. case '1':
  258. case '2':
  259. case '3':
  260. case '4':
  261. case '5':
  262. case '6':
  263. case '7': {
  264. size_t octal_digits = 1;
  265. for (size_t i = 0; i < 2; ++i) {
  266. char next = peek(2 + i);
  267. if (next < '0' || next > '7')
  268. break;
  269. ++octal_digits;
  270. }
  271. return 1 + octal_digits;
  272. }
  273. case 'x': {
  274. size_t hex_digits = 0;
  275. for (size_t i = 0; i < 2; ++i) {
  276. if (!isxdigit(peek(2 + i)))
  277. break;
  278. ++hex_digits;
  279. }
  280. return 2 + hex_digits;
  281. }
  282. case 'u': {
  283. bool is_unicode = true;
  284. for (size_t i = 0; i < 4; ++i) {
  285. if (!isxdigit(peek(2 + i))) {
  286. is_unicode = false;
  287. break;
  288. }
  289. }
  290. return is_unicode ? 6 : 0;
  291. }
  292. default:
  293. return 0;
  294. }
  295. };
  296. while (m_index < m_input.length()) {
  297. auto ch = peek();
  298. if (isspace(ch)) {
  299. begin_token();
  300. while (isspace(peek()))
  301. consume();
  302. commit_token(CppToken::Type::Whitespace);
  303. continue;
  304. }
  305. if (ch == '(') {
  306. emit_token(CppToken::Type::LeftParen);
  307. continue;
  308. }
  309. if (ch == ')') {
  310. emit_token(CppToken::Type::RightParen);
  311. continue;
  312. }
  313. if (ch == '{') {
  314. emit_token(CppToken::Type::LeftCurly);
  315. continue;
  316. }
  317. if (ch == '}') {
  318. emit_token(CppToken::Type::RightCurly);
  319. continue;
  320. }
  321. if (ch == '[') {
  322. emit_token(CppToken::Type::LeftBracket);
  323. continue;
  324. }
  325. if (ch == ']') {
  326. emit_token(CppToken::Type::RightBracket);
  327. continue;
  328. }
  329. if (ch == '<') {
  330. begin_token();
  331. consume();
  332. if (peek() == '<') {
  333. consume();
  334. if (peek() == '=') {
  335. consume();
  336. commit_token(CppToken::Type::LessLessEquals);
  337. continue;
  338. }
  339. commit_token(CppToken::Type::LessLess);
  340. continue;
  341. }
  342. if (peek() == '=') {
  343. consume();
  344. commit_token(CppToken::Type::LessEquals);
  345. continue;
  346. }
  347. if (peek() == '>') {
  348. consume();
  349. commit_token(CppToken::Type::LessGreater);
  350. continue;
  351. }
  352. commit_token(CppToken::Type::Less);
  353. continue;
  354. }
  355. if (ch == ',') {
  356. emit_token(CppToken::Type::Comma);
  357. continue;
  358. }
  359. if (ch == '+') {
  360. emit_token_equals(CppToken::Type::Plus, CppToken::Type::PlusEquals);
  361. continue;
  362. }
  363. if (ch == '-') {
  364. emit_token_equals(CppToken::Type::Minus, CppToken::Type::MinusEquals);
  365. continue;
  366. }
  367. if (ch == '*') {
  368. emit_token_equals(CppToken::Type::Asterisk, CppToken::Type::AsteriskEquals);
  369. continue;
  370. }
  371. if (ch == '%') {
  372. emit_token_equals(CppToken::Type::Percent, CppToken::Type::PercentEquals);
  373. continue;
  374. }
  375. if (ch == '=') {
  376. emit_token_equals(CppToken::Type::Equals, CppToken::Type::EqualsEquals);
  377. continue;
  378. }
  379. if (ch == ';') {
  380. emit_token(CppToken::Type::Semicolon);
  381. continue;
  382. }
  383. if (ch == '#') {
  384. begin_token();
  385. consume();
  386. if (is_valid_first_character_of_identifier(peek()))
  387. while (peek() && is_valid_nonfirst_character_of_identifier(peek()))
  388. consume();
  389. auto directive = StringView(m_input.characters_without_null_termination() + token_start_index, m_index - token_start_index);
  390. if (directive == "#include") {
  391. commit_token(CppToken::Type::IncludeStatement);
  392. begin_token();
  393. while (isspace(peek()))
  394. consume();
  395. commit_token(CppToken::Type::Whitespace);
  396. begin_token();
  397. if (peek() == '<' || peek() == '"') {
  398. char closing = consume() == '<' ? '>' : '"';
  399. while (peek() && peek() != closing && peek() != '\n')
  400. consume();
  401. if (peek() && consume() == '\n') {
  402. commit_token(CppToken::Type::IncludePath);
  403. continue;
  404. }
  405. commit_token(CppToken::Type::IncludePath);
  406. begin_token();
  407. }
  408. }
  409. while (peek() && peek() != '\n')
  410. consume();
  411. commit_token(CppToken::Type::PreprocessorStatement);
  412. continue;
  413. }
  414. if (ch == '/' && peek(1) == '/') {
  415. begin_token();
  416. while (peek() && peek() != '\n')
  417. consume();
  418. commit_token(CppToken::Type::Comment);
  419. continue;
  420. }
  421. if (ch == '/' && peek(1) == '*') {
  422. begin_token();
  423. consume();
  424. consume();
  425. bool comment_block_ends = false;
  426. while (peek()) {
  427. if (peek() == '*' && peek(1) == '/') {
  428. comment_block_ends = true;
  429. break;
  430. }
  431. consume();
  432. }
  433. if (comment_block_ends) {
  434. consume();
  435. consume();
  436. }
  437. commit_token(CppToken::Type::Comment);
  438. continue;
  439. }
  440. if (ch == '/') {
  441. emit_token_equals(CppToken::Type::Slash, CppToken::Type::SlashEquals);
  442. continue;
  443. }
  444. if (ch == '"') {
  445. begin_token();
  446. consume();
  447. while (peek()) {
  448. if (peek() == '\\') {
  449. size_t escape = match_escape_sequence();
  450. if (escape > 0) {
  451. commit_token(CppToken::Type::DoubleQuotedString);
  452. begin_token();
  453. for (size_t i = 0; i < escape; ++i)
  454. consume();
  455. commit_token(CppToken::Type::EscapeSequence);
  456. begin_token();
  457. continue;
  458. }
  459. }
  460. if (consume() == '"')
  461. break;
  462. }
  463. commit_token(CppToken::Type::DoubleQuotedString);
  464. continue;
  465. }
  466. if (ch == '\'') {
  467. begin_token();
  468. consume();
  469. while (peek()) {
  470. if (peek() == '\\') {
  471. size_t escape = match_escape_sequence();
  472. if (escape > 0) {
  473. commit_token(CppToken::Type::SingleQuotedString);
  474. begin_token();
  475. for (size_t i = 0; i < escape; ++i)
  476. consume();
  477. commit_token(CppToken::Type::EscapeSequence);
  478. begin_token();
  479. continue;
  480. }
  481. }
  482. if (consume() == '\'')
  483. break;
  484. }
  485. commit_token(CppToken::Type::SingleQuotedString);
  486. continue;
  487. }
  488. if (isdigit(ch) || (ch == '.' && isdigit(peek(1)))) {
  489. begin_token();
  490. consume();
  491. auto type = ch == '.' ? CppToken::Type::Float : CppToken::Type::Integer;
  492. bool is_hex = false;
  493. bool is_binary = false;
  494. auto match_exponent = [&]() -> size_t {
  495. char ch = peek();
  496. if (ch != 'e' && ch != 'E' && ch != 'p' && ch != 'P')
  497. return 0;
  498. type = CppToken::Type::Float;
  499. size_t length = 1;
  500. ch = peek(length);
  501. if (ch == '+' || ch == '-') {
  502. ++length;
  503. }
  504. for (ch = peek(length); isdigit(ch); ch = peek(length)) {
  505. ++length;
  506. }
  507. return length;
  508. };
  509. auto match_type_literal = [&]() -> size_t {
  510. size_t length = 0;
  511. for (;;) {
  512. char ch = peek(length);
  513. if ((ch == 'u' || ch == 'U') && type == CppToken::Type::Integer) {
  514. ++length;
  515. } else if ((ch == 'f' || ch == 'F') && !is_binary) {
  516. type = CppToken::Type::Float;
  517. ++length;
  518. } else if (ch == 'l' || ch == 'L') {
  519. ++length;
  520. } else
  521. return length;
  522. }
  523. };
  524. if (peek() == 'b' || peek() == 'B') {
  525. consume();
  526. is_binary = true;
  527. for (char ch = peek(); ch == '0' || ch == '1' || (ch == '\'' && peek(1) != '\''); ch = peek()) {
  528. consume();
  529. }
  530. } else {
  531. if (peek() == 'x' || peek() == 'X') {
  532. consume();
  533. is_hex = true;
  534. }
  535. for (char ch = peek(); (is_hex ? isxdigit(ch) : isdigit(ch)) || (ch == '\'' && peek(1) != '\'') || ch == '.'; ch = peek()) {
  536. if (ch == '.') {
  537. if (type == CppToken::Type::Integer) {
  538. type = CppToken::Type::Float;
  539. } else
  540. break;
  541. };
  542. consume();
  543. }
  544. }
  545. if (!is_binary) {
  546. size_t length = match_exponent();
  547. for (size_t i = 0; i < length; ++i)
  548. consume();
  549. }
  550. size_t length = match_type_literal();
  551. for (size_t i = 0; i < length; ++i)
  552. consume();
  553. commit_token(type);
  554. continue;
  555. }
  556. if (is_valid_first_character_of_identifier(ch)) {
  557. begin_token();
  558. while (peek() && is_valid_nonfirst_character_of_identifier(peek()))
  559. consume();
  560. auto token_view = StringView(m_input.characters_without_null_termination() + token_start_index, m_index - token_start_index);
  561. if (is_keyword(token_view))
  562. commit_token(CppToken::Type::Keyword);
  563. else if (is_known_type(token_view))
  564. commit_token(CppToken::Type::KnownType);
  565. else
  566. commit_token(CppToken::Type::Identifier);
  567. continue;
  568. }
  569. dbg() << "Unimplemented token character: " << ch;
  570. emit_token(CppToken::Type::Unknown);
  571. }
  572. return tokens;
  573. }
  574. }