Preprocessor.cpp 12 KB

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