Preprocessor.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  1. /*
  2. * Copyright (c) 2021, Itamar S. <itamar8910@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include "Preprocessor.h"
  7. #include <AK/Assertions.h>
  8. #include <AK/GenericLexer.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibCpp/Lexer.h>
  11. #include <ctype.h>
  12. namespace Cpp {
  13. Preprocessor::Preprocessor(const String& filename, StringView program)
  14. : m_filename(filename)
  15. , m_program(program)
  16. {
  17. }
  18. Vector<Token> Preprocessor::process_and_lex()
  19. {
  20. Lexer lexer { m_program };
  21. lexer.set_ignore_whitespace(true);
  22. auto tokens = lexer.lex();
  23. m_unprocessed_tokens = tokens;
  24. for (size_t token_index = 0; token_index < tokens.size(); ++token_index) {
  25. auto& token = tokens[token_index];
  26. m_current_line = token.start().line;
  27. if (token.type() == Token::Type::PreprocessorStatement) {
  28. handle_preprocessor_statement(token.text());
  29. m_processed_tokens.append(tokens[token_index]);
  30. continue;
  31. }
  32. if (m_state != State::Normal)
  33. continue;
  34. if (token.type() == Token::Type::IncludeStatement) {
  35. if (token_index >= tokens.size() - 1 || tokens[token_index + 1].type() != Token::Type::IncludePath)
  36. continue;
  37. handle_include_statement(tokens[token_index + 1].text());
  38. if (m_options.keep_include_statements) {
  39. m_processed_tokens.append(tokens[token_index]);
  40. m_processed_tokens.append(tokens[token_index + 1]);
  41. }
  42. ++token_index; // Also skip IncludePath token
  43. continue;
  44. }
  45. if (token.type() == Token::Type::Identifier) {
  46. if (auto defined_value = m_definitions.find(token.text()); defined_value != m_definitions.end()) {
  47. auto last_substituted_token_index = do_substitution(tokens, token_index, defined_value->value);
  48. token_index = last_substituted_token_index;
  49. continue;
  50. }
  51. }
  52. m_processed_tokens.append(token);
  53. }
  54. return m_processed_tokens;
  55. }
  56. static void consume_whitespace(GenericLexer& lexer)
  57. {
  58. auto ignore_line = [&] {
  59. for (;;) {
  60. if (lexer.consume_specific("\\\n"sv)) {
  61. lexer.ignore(2);
  62. } else {
  63. lexer.ignore_until('\n');
  64. break;
  65. }
  66. }
  67. };
  68. for (;;) {
  69. if (lexer.consume_specific("//"sv))
  70. ignore_line();
  71. else if (lexer.consume_specific("/*"sv))
  72. lexer.ignore_until("*/");
  73. else if (lexer.next_is("\\\n"sv))
  74. lexer.ignore(2);
  75. else if (lexer.is_eof() || !lexer.next_is(isspace))
  76. break;
  77. else
  78. lexer.ignore();
  79. }
  80. }
  81. void Preprocessor::handle_preprocessor_statement(StringView line)
  82. {
  83. GenericLexer lexer(line);
  84. consume_whitespace(lexer);
  85. lexer.consume_specific('#');
  86. consume_whitespace(lexer);
  87. auto keyword = lexer.consume_until(' ');
  88. lexer.ignore();
  89. if (keyword.is_empty() || keyword.is_null() || keyword.is_whitespace())
  90. return;
  91. handle_preprocessor_keyword(keyword, lexer);
  92. }
  93. void Preprocessor::handle_include_statement(StringView include_path)
  94. {
  95. m_included_paths.append(include_path);
  96. if (definitions_in_header_callback) {
  97. for (auto& def : definitions_in_header_callback(include_path))
  98. m_definitions.set(def.key, def.value);
  99. }
  100. }
  101. void Preprocessor::handle_preprocessor_keyword(StringView keyword, GenericLexer& line_lexer)
  102. {
  103. if (keyword == "include") {
  104. // Should have called 'handle_include_statement'.
  105. VERIFY_NOT_REACHED();
  106. }
  107. if (keyword == "else") {
  108. if (m_options.ignore_invalid_statements && m_current_depth == 0)
  109. return;
  110. VERIFY(m_current_depth > 0);
  111. if (m_depths_of_not_taken_branches.contains_slow(m_current_depth - 1)) {
  112. m_depths_of_not_taken_branches.remove_all_matching([this](auto x) { return x == m_current_depth - 1; });
  113. m_state = State::Normal;
  114. }
  115. if (m_depths_of_taken_branches.contains_slow(m_current_depth - 1)) {
  116. m_state = State::SkipElseBranch;
  117. }
  118. return;
  119. }
  120. if (keyword == "endif") {
  121. if (m_options.ignore_invalid_statements && m_current_depth == 0)
  122. return;
  123. VERIFY(m_current_depth > 0);
  124. --m_current_depth;
  125. if (m_depths_of_not_taken_branches.contains_slow(m_current_depth)) {
  126. m_depths_of_not_taken_branches.remove_all_matching([this](auto x) { return x == m_current_depth; });
  127. }
  128. if (m_depths_of_taken_branches.contains_slow(m_current_depth)) {
  129. m_depths_of_taken_branches.remove_all_matching([this](auto x) { return x == m_current_depth; });
  130. }
  131. m_state = State::Normal;
  132. return;
  133. }
  134. if (keyword == "define") {
  135. if (m_state == State::Normal) {
  136. auto definition = create_definition(line_lexer.consume_all());
  137. if (definition.has_value())
  138. m_definitions.set(definition->key, *definition);
  139. }
  140. return;
  141. }
  142. if (keyword == "undef") {
  143. if (m_state == State::Normal) {
  144. auto key = line_lexer.consume_until(' ');
  145. line_lexer.consume_all();
  146. m_definitions.remove(key);
  147. }
  148. return;
  149. }
  150. if (keyword == "ifdef") {
  151. ++m_current_depth;
  152. if (m_state == State::Normal) {
  153. auto key = line_lexer.consume_until(' ');
  154. line_lexer.ignore();
  155. if (m_definitions.contains(key)) {
  156. m_depths_of_taken_branches.append(m_current_depth - 1);
  157. return;
  158. } else {
  159. m_depths_of_not_taken_branches.append(m_current_depth - 1);
  160. m_state = State::SkipIfBranch;
  161. return;
  162. }
  163. }
  164. return;
  165. }
  166. if (keyword == "ifndef") {
  167. ++m_current_depth;
  168. if (m_state == State::Normal) {
  169. auto key = line_lexer.consume_until(' ');
  170. line_lexer.ignore();
  171. if (!m_definitions.contains(key)) {
  172. m_depths_of_taken_branches.append(m_current_depth - 1);
  173. return;
  174. } else {
  175. m_depths_of_not_taken_branches.append(m_current_depth - 1);
  176. m_state = State::SkipIfBranch;
  177. return;
  178. }
  179. }
  180. return;
  181. }
  182. if (keyword == "if") {
  183. ++m_current_depth;
  184. if (m_state == State::Normal) {
  185. // FIXME: Implement #if logic
  186. // We currently always take #if branches.
  187. m_depths_of_taken_branches.append(m_current_depth - 1);
  188. }
  189. return;
  190. }
  191. if (keyword == "elif") {
  192. if (m_options.ignore_invalid_statements && m_current_depth == 0)
  193. return;
  194. VERIFY(m_current_depth > 0);
  195. // FIXME: Evaluate the elif expression
  196. // We currently always treat the expression in #elif as true.
  197. if (m_depths_of_not_taken_branches.contains_slow(m_current_depth - 1) /* && should_take*/) {
  198. m_depths_of_not_taken_branches.remove_all_matching([this](auto x) { return x == m_current_depth - 1; });
  199. m_state = State::Normal;
  200. }
  201. if (m_depths_of_taken_branches.contains_slow(m_current_depth - 1)) {
  202. m_state = State::SkipElseBranch;
  203. }
  204. return;
  205. }
  206. if (keyword == "pragma") {
  207. line_lexer.consume_all();
  208. return;
  209. }
  210. if (!m_options.ignore_unsupported_keywords) {
  211. dbgln("Unsupported preprocessor keyword: {}", keyword);
  212. VERIFY_NOT_REACHED();
  213. }
  214. }
  215. size_t Preprocessor::do_substitution(Vector<Token> const& tokens, size_t token_index, Definition const& defined_value)
  216. {
  217. if (defined_value.value.is_null())
  218. return token_index;
  219. Substitution sub;
  220. sub.defined_value = defined_value;
  221. auto macro_call = parse_macro_call(tokens, token_index);
  222. if (!macro_call.has_value())
  223. return token_index;
  224. Vector<Token> original_tokens;
  225. for (size_t i = token_index; i <= macro_call->end_token_index; ++i) {
  226. original_tokens.append(tokens[i]);
  227. }
  228. VERIFY(!original_tokens.is_empty());
  229. auto processed_value = evaluate_macro_call(*macro_call, defined_value);
  230. m_substitutions.append({ original_tokens, defined_value, processed_value });
  231. Lexer lexer(processed_value);
  232. lexer.lex_iterable([&](auto token) {
  233. if (token.type() == Token::Type::Whitespace)
  234. return;
  235. token.set_start(original_tokens.first().start());
  236. token.set_end(original_tokens.first().end());
  237. m_processed_tokens.append(token);
  238. });
  239. return macro_call->end_token_index;
  240. }
  241. Optional<Preprocessor::MacroCall> Preprocessor::parse_macro_call(Vector<Token> const& tokens, size_t token_index)
  242. {
  243. auto name = tokens[token_index];
  244. ++token_index;
  245. if (token_index >= tokens.size() || tokens[token_index].type() != Token::Type::LeftParen)
  246. return MacroCall { name, {}, token_index - 1 };
  247. ++token_index;
  248. Vector<MacroCall::Argument> arguments;
  249. MacroCall::Argument current_argument;
  250. size_t paren_depth = 1;
  251. for (; token_index < tokens.size(); ++token_index) {
  252. auto& token = tokens[token_index];
  253. if (token.type() == Token::Type::LeftParen)
  254. ++paren_depth;
  255. if (token.type() == Token::Type::RightParen)
  256. --paren_depth;
  257. if (paren_depth == 0) {
  258. arguments.append(move(current_argument));
  259. break;
  260. }
  261. if (paren_depth == 1 && token.type() == Token::Type::Comma) {
  262. arguments.append(move(current_argument));
  263. current_argument = {};
  264. } else {
  265. current_argument.tokens.append(token);
  266. }
  267. }
  268. if (token_index >= tokens.size())
  269. return {};
  270. return MacroCall { name, move(arguments), token_index };
  271. }
  272. Optional<Preprocessor::Definition> Preprocessor::create_definition(StringView line)
  273. {
  274. Lexer lexer { line };
  275. lexer.set_ignore_whitespace(true);
  276. auto tokens = lexer.lex();
  277. if (tokens.is_empty())
  278. return {};
  279. if (tokens.first().type() != Token::Type::Identifier)
  280. return {};
  281. Definition definition;
  282. definition.filename = m_filename;
  283. definition.line = m_current_line;
  284. definition.key = tokens.first().text();
  285. if (tokens.size() == 1)
  286. return definition;
  287. size_t token_index = 1;
  288. // Parse macro parameters (if any)
  289. if (tokens[token_index].type() == Token::Type::LeftParen) {
  290. ++token_index;
  291. while (token_index < tokens.size() && tokens[token_index].type() != Token::Type::RightParen) {
  292. auto param = tokens[token_index];
  293. if (param.type() != Token::Type::Identifier)
  294. return {};
  295. if (token_index + 1 >= tokens.size())
  296. return {};
  297. ++token_index;
  298. if (tokens[token_index].type() == Token::Type::Comma)
  299. ++token_index;
  300. else if (tokens[token_index].type() != Token::Type::RightParen)
  301. return {};
  302. definition.parameters.empend(param.text());
  303. }
  304. if (token_index >= tokens.size())
  305. return {};
  306. ++token_index;
  307. }
  308. if (token_index < tokens.size())
  309. definition.value = remove_escaped_newlines(line.substring_view(tokens[token_index].start().column));
  310. return definition;
  311. }
  312. String Preprocessor::remove_escaped_newlines(StringView value)
  313. {
  314. static constexpr auto escaped_newline = "\\\n"sv;
  315. AK::StringBuilder processed_value;
  316. GenericLexer lexer { value };
  317. while (!lexer.is_eof()) {
  318. processed_value.append(lexer.consume_until(escaped_newline));
  319. lexer.ignore(escaped_newline.length());
  320. }
  321. return processed_value.to_string();
  322. }
  323. String Preprocessor::evaluate_macro_call(MacroCall const& macro_call, Definition const& definition)
  324. {
  325. if (macro_call.arguments.size() != definition.parameters.size()) {
  326. dbgln("mismatch in # of arguments for macro call: {}", macro_call.name.text());
  327. return {};
  328. }
  329. Lexer lexer { definition.value };
  330. StringBuilder processed_value;
  331. lexer.lex_iterable([&](auto token) {
  332. if (token.type() != Token::Type::Identifier) {
  333. processed_value.append(token.text());
  334. return;
  335. }
  336. auto param_index = definition.parameters.find_first_index(token.text());
  337. if (!param_index.has_value()) {
  338. processed_value.append(token.text());
  339. return;
  340. }
  341. auto& argument = macro_call.arguments[*param_index];
  342. for (auto& arg_token : argument.tokens) {
  343. processed_value.append(arg_token.text());
  344. }
  345. });
  346. return processed_value.to_string();
  347. }
  348. };