CppLexer.cpp 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556
  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 match_escape_sequence = [&]() -> size_t {
  233. switch (peek(1)) {
  234. case '\'':
  235. case '"':
  236. case '?':
  237. case '\\':
  238. case 'a':
  239. case 'b':
  240. case 'f':
  241. case 'n':
  242. case 'r':
  243. case 't':
  244. case 'v':
  245. return 2;
  246. case '0':
  247. case '1':
  248. case '2':
  249. case '3':
  250. case '4':
  251. case '5':
  252. case '6':
  253. case '7': {
  254. size_t octal_digits = 1;
  255. for (size_t i = 0; i < 2; ++i) {
  256. char next = peek(2 + i);
  257. if (next < '0' || next > '7')
  258. break;
  259. ++octal_digits;
  260. }
  261. return 1 + octal_digits;
  262. }
  263. case 'x': {
  264. size_t hex_digits = 0;
  265. for (size_t i = 0; i < 2; ++i) {
  266. if (!isxdigit(peek(2 + i)))
  267. break;
  268. ++hex_digits;
  269. }
  270. return 2 + hex_digits;
  271. }
  272. case 'u': {
  273. bool is_unicode = true;
  274. for (size_t i = 0; i < 4; ++i) {
  275. if (!isxdigit(peek(2 + i))) {
  276. is_unicode = false;
  277. break;
  278. }
  279. }
  280. return is_unicode ? 6 : 0;
  281. }
  282. default:
  283. return 0;
  284. }
  285. };
  286. while (m_index < m_input.length()) {
  287. auto ch = peek();
  288. if (isspace(ch)) {
  289. begin_token();
  290. while (isspace(peek()))
  291. consume();
  292. commit_token(CppToken::Type::Whitespace);
  293. continue;
  294. }
  295. if (ch == '(') {
  296. emit_token(CppToken::Type::LeftParen);
  297. continue;
  298. }
  299. if (ch == ')') {
  300. emit_token(CppToken::Type::RightParen);
  301. continue;
  302. }
  303. if (ch == '{') {
  304. emit_token(CppToken::Type::LeftCurly);
  305. continue;
  306. }
  307. if (ch == '}') {
  308. emit_token(CppToken::Type::RightCurly);
  309. continue;
  310. }
  311. if (ch == '[') {
  312. emit_token(CppToken::Type::LeftBracket);
  313. continue;
  314. }
  315. if (ch == ']') {
  316. emit_token(CppToken::Type::RightBracket);
  317. continue;
  318. }
  319. if (ch == ',') {
  320. emit_token(CppToken::Type::Comma);
  321. continue;
  322. }
  323. if (ch == '*') {
  324. emit_token(CppToken::Type::Asterisk);
  325. continue;
  326. }
  327. if (ch == ';') {
  328. emit_token(CppToken::Type::Semicolon);
  329. continue;
  330. }
  331. if (ch == '#') {
  332. begin_token();
  333. consume();
  334. if (is_valid_first_character_of_identifier(peek()))
  335. while (peek() && is_valid_nonfirst_character_of_identifier(peek()))
  336. consume();
  337. auto directive = StringView(m_input.characters_without_null_termination() + token_start_index, m_index - token_start_index);
  338. if (directive == "#include") {
  339. commit_token(CppToken::Type::IncludeStatement);
  340. begin_token();
  341. while (isspace(peek()))
  342. consume();
  343. commit_token(CppToken::Type::Whitespace);
  344. begin_token();
  345. if (peek() == '<' || peek() == '"') {
  346. char closing = consume() == '<' ? '>' : '"';
  347. while (peek() && peek() != closing && peek() != '\n')
  348. consume();
  349. if (peek() && consume() == '\n') {
  350. commit_token(CppToken::Type::IncludePath);
  351. continue;
  352. }
  353. commit_token(CppToken::Type::IncludePath);
  354. begin_token();
  355. }
  356. }
  357. while (peek() && peek() != '\n')
  358. consume();
  359. commit_token(CppToken::Type::PreprocessorStatement);
  360. continue;
  361. }
  362. if (ch == '/' && peek(1) == '/') {
  363. begin_token();
  364. while (peek() && peek() != '\n')
  365. consume();
  366. commit_token(CppToken::Type::Comment);
  367. continue;
  368. }
  369. if (ch == '/' && peek(1) == '*') {
  370. begin_token();
  371. consume();
  372. consume();
  373. bool comment_block_ends = false;
  374. while (peek()) {
  375. if (peek() == '*' && peek(1) == '/') {
  376. comment_block_ends = true;
  377. break;
  378. }
  379. consume();
  380. }
  381. if (comment_block_ends) {
  382. consume();
  383. consume();
  384. }
  385. commit_token(CppToken::Type::Comment);
  386. continue;
  387. }
  388. if (ch == '"') {
  389. begin_token();
  390. consume();
  391. while (peek()) {
  392. if (peek() == '\\') {
  393. size_t escape = match_escape_sequence();
  394. if (escape > 0) {
  395. commit_token(CppToken::Type::DoubleQuotedString);
  396. begin_token();
  397. for (size_t i = 0; i < escape; ++i)
  398. consume();
  399. commit_token(CppToken::Type::EscapeSequence);
  400. begin_token();
  401. continue;
  402. }
  403. }
  404. if (consume() == '"')
  405. break;
  406. }
  407. commit_token(CppToken::Type::DoubleQuotedString);
  408. continue;
  409. }
  410. if (ch == '\'') {
  411. begin_token();
  412. consume();
  413. while (peek()) {
  414. if (peek() == '\\') {
  415. size_t escape = match_escape_sequence();
  416. if (escape > 0) {
  417. commit_token(CppToken::Type::SingleQuotedString);
  418. begin_token();
  419. for (size_t i = 0; i < escape; ++i)
  420. consume();
  421. commit_token(CppToken::Type::EscapeSequence);
  422. begin_token();
  423. continue;
  424. }
  425. }
  426. if (consume() == '\'')
  427. break;
  428. }
  429. commit_token(CppToken::Type::SingleQuotedString);
  430. continue;
  431. }
  432. if (isdigit(ch) || (ch == '.' && isdigit(peek(1)))) {
  433. begin_token();
  434. consume();
  435. auto type = ch == '.' ? CppToken::Type::Float : CppToken::Type::Integer;
  436. bool is_hex = false;
  437. bool is_binary = false;
  438. auto match_exponent = [&]() -> size_t {
  439. char ch = peek();
  440. if (ch != 'e' && ch != 'E' && ch != 'p' && ch != 'P')
  441. return 0;
  442. type = CppToken::Type::Float;
  443. size_t length = 1;
  444. ch = peek(length);
  445. if (ch == '+' || ch == '-') {
  446. ++length;
  447. }
  448. for (ch = peek(length); isdigit(ch); ch = peek(length)) {
  449. ++length;
  450. }
  451. return length;
  452. };
  453. auto match_type_literal = [&]() -> size_t {
  454. size_t length = 0;
  455. for (;;) {
  456. char ch = peek(length);
  457. if ((ch == 'u' || ch == 'U') && type == CppToken::Type::Integer) {
  458. ++length;
  459. } else if ((ch == 'f' || ch == 'F') && !is_binary) {
  460. type = CppToken::Type::Float;
  461. ++length;
  462. } else if (ch == 'l' || ch == 'L') {
  463. ++length;
  464. } else
  465. return length;
  466. }
  467. };
  468. if (peek() == 'b' || peek() == 'B') {
  469. consume();
  470. is_binary = true;
  471. for (char ch = peek(); ch == '0' || ch == '1' || (ch == '\'' && peek(1) != '\''); ch = peek()) {
  472. consume();
  473. }
  474. } else {
  475. if (peek() == 'x' || peek() == 'X') {
  476. consume();
  477. is_hex = true;
  478. }
  479. for (char ch = peek(); (is_hex ? isxdigit(ch) : isdigit(ch)) || (ch == '\'' && peek(1) != '\'') || ch == '.'; ch = peek()) {
  480. if (ch == '.') {
  481. if (type == CppToken::Type::Integer) {
  482. type = CppToken::Type::Float;
  483. } else
  484. break;
  485. };
  486. consume();
  487. }
  488. }
  489. if (!is_binary) {
  490. size_t length = match_exponent();
  491. for (size_t i = 0; i < length; ++i)
  492. consume();
  493. }
  494. size_t length = match_type_literal();
  495. for (size_t i = 0; i < length; ++i)
  496. consume();
  497. commit_token(type);
  498. continue;
  499. }
  500. if (is_valid_first_character_of_identifier(ch)) {
  501. begin_token();
  502. while (peek() && is_valid_nonfirst_character_of_identifier(peek()))
  503. consume();
  504. auto token_view = StringView(m_input.characters_without_null_termination() + token_start_index, m_index - token_start_index);
  505. if (is_keyword(token_view))
  506. commit_token(CppToken::Type::Keyword);
  507. else if (is_known_type(token_view))
  508. commit_token(CppToken::Type::KnownType);
  509. else
  510. commit_token(CppToken::Type::Identifier);
  511. continue;
  512. }
  513. dbg() << "Unimplemented token character: " << ch;
  514. emit_token(CppToken::Type::Unknown);
  515. }
  516. return tokens;
  517. }
  518. }