Preprocessor.cpp 12 KB

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