Preprocessor.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395
  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. GenericLexer program_lexer { m_program };
  18. for (;;) {
  19. if (program_lexer.is_eof())
  20. break;
  21. auto line = program_lexer.consume_until('\n');
  22. bool has_multiline = false;
  23. while (line.ends_with('\\') && !program_lexer.is_eof()) {
  24. auto continuation = program_lexer.consume_until('\n');
  25. line = StringView { line.characters_without_null_termination(), line.length() + continuation.length() + 1 };
  26. // Append an empty line to keep the line count correct.
  27. m_lines.append({});
  28. has_multiline = true;
  29. }
  30. if (has_multiline)
  31. m_lines.last() = line;
  32. else
  33. m_lines.append(line);
  34. }
  35. }
  36. Vector<Token> Preprocessor::process_and_lex()
  37. {
  38. for (; m_line_index < m_lines.size(); ++m_line_index) {
  39. auto& line = m_lines[m_line_index];
  40. bool include_in_processed_text = false;
  41. if (line.starts_with("#")) {
  42. auto keyword = handle_preprocessor_line(line);
  43. if (m_options.keep_include_statements && keyword == "include")
  44. include_in_processed_text = true;
  45. } else if (m_state == State::Normal) {
  46. include_in_processed_text = true;
  47. }
  48. if (include_in_processed_text) {
  49. process_line(line);
  50. }
  51. }
  52. return m_tokens;
  53. }
  54. static void consume_whitespace(GenericLexer& lexer)
  55. {
  56. auto ignore_line = [&] {
  57. for (;;) {
  58. if (lexer.consume_specific("\\\n"sv)) {
  59. lexer.ignore(2);
  60. } else {
  61. lexer.ignore_until('\n');
  62. break;
  63. }
  64. }
  65. };
  66. for (;;) {
  67. if (lexer.consume_specific("//"sv))
  68. ignore_line();
  69. else if (lexer.consume_specific("/*"sv))
  70. lexer.ignore_until("*/");
  71. else if (lexer.next_is("\\\n"sv))
  72. lexer.ignore(2);
  73. else if (lexer.is_eof() || !lexer.next_is(isspace))
  74. break;
  75. else
  76. lexer.ignore();
  77. }
  78. }
  79. Preprocessor::PreprocessorKeyword Preprocessor::handle_preprocessor_line(const StringView& line)
  80. {
  81. GenericLexer lexer(line);
  82. consume_whitespace(lexer);
  83. lexer.consume_specific('#');
  84. consume_whitespace(lexer);
  85. auto keyword = lexer.consume_until(' ');
  86. if (keyword.is_empty() || keyword.is_null() || keyword.is_whitespace())
  87. return {};
  88. handle_preprocessor_keyword(keyword, lexer);
  89. return keyword;
  90. }
  91. void Preprocessor::handle_preprocessor_keyword(const StringView& keyword, GenericLexer& line_lexer)
  92. {
  93. if (keyword == "include") {
  94. consume_whitespace(line_lexer);
  95. auto include_path = line_lexer.consume_all();
  96. m_included_paths.append(include_path);
  97. if (definitions_in_header_callback) {
  98. for (auto& def : definitions_in_header_callback(include_path))
  99. m_definitions.set(def.key, def.value);
  100. }
  101. return;
  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. void Preprocessor::process_line(StringView const& line)
  204. {
  205. Lexer line_lexer { line, m_line_index };
  206. line_lexer.set_ignore_whitespace(true);
  207. auto tokens = line_lexer.lex();
  208. for (size_t i = 0; i < tokens.size(); ++i) {
  209. auto& token = tokens[i];
  210. if (token.type() == Token::Type::Identifier) {
  211. if (auto defined_value = m_definitions.find(token.text()); defined_value != m_definitions.end()) {
  212. auto last_substituted_token_index = do_substitution(tokens, i, defined_value->value);
  213. i = last_substituted_token_index;
  214. continue;
  215. }
  216. }
  217. m_tokens.append(token);
  218. }
  219. }
  220. size_t Preprocessor::do_substitution(Vector<Token> const& tokens, size_t token_index, Definition const& defined_value)
  221. {
  222. if (defined_value.value.is_null())
  223. return token_index;
  224. Substitution sub;
  225. sub.defined_value = defined_value;
  226. auto macro_call = parse_macro_call(tokens, token_index);
  227. if (!macro_call.has_value())
  228. return token_index;
  229. Vector<Token> original_tokens;
  230. for (size_t i = token_index; i <= macro_call->end_token_index; ++i) {
  231. original_tokens.append(tokens[i]);
  232. }
  233. VERIFY(!original_tokens.is_empty());
  234. auto processed_value = evaluate_macro_call(*macro_call, defined_value);
  235. m_substitutions.append({ original_tokens, defined_value, processed_value });
  236. Lexer lexer(processed_value);
  237. for (auto& token : lexer.lex()) {
  238. if (token.type() == Token::Type::Whitespace)
  239. continue;
  240. token.set_start(original_tokens.first().start());
  241. token.set_end(original_tokens.first().end());
  242. m_tokens.append(token);
  243. }
  244. return macro_call->end_token_index;
  245. }
  246. Optional<Preprocessor::MacroCall> Preprocessor::parse_macro_call(Vector<Token> const& tokens, size_t token_index)
  247. {
  248. auto name = tokens[token_index];
  249. ++token_index;
  250. if (token_index >= tokens.size() || tokens[token_index].type() != Token::Type::LeftParen)
  251. return MacroCall { name, {}, token_index - 1 };
  252. ++token_index;
  253. Vector<MacroCall::Argument> arguments;
  254. MacroCall::Argument current_argument;
  255. size_t paren_depth = 1;
  256. for (; token_index < tokens.size(); ++token_index) {
  257. auto& token = tokens[token_index];
  258. if (token.type() == Token::Type::LeftParen)
  259. ++paren_depth;
  260. if (token.type() == Token::Type::RightParen)
  261. --paren_depth;
  262. if (paren_depth == 0) {
  263. arguments.append(move(current_argument));
  264. break;
  265. }
  266. if (paren_depth == 1 && token.type() == Token::Type::Comma) {
  267. arguments.append(move(current_argument));
  268. current_argument = {};
  269. } else {
  270. current_argument.tokens.append(token);
  271. }
  272. }
  273. if (token_index >= tokens.size())
  274. return {};
  275. return MacroCall { name, move(arguments), token_index };
  276. }
  277. Optional<Preprocessor::Definition> Preprocessor::create_definition(StringView line)
  278. {
  279. Lexer lexer { line };
  280. lexer.set_ignore_whitespace(true);
  281. auto tokens = lexer.lex();
  282. if (tokens.is_empty())
  283. return {};
  284. if (tokens.first().type() != Token::Type::Identifier)
  285. return {};
  286. Definition definition;
  287. definition.filename = m_filename;
  288. definition.line = m_line_index;
  289. definition.key = tokens.first().text();
  290. if (tokens.size() == 1)
  291. return definition;
  292. size_t token_index = 1;
  293. // Parse macro parameters (if any)
  294. if (tokens[token_index].type() == Token::Type::LeftParen) {
  295. ++token_index;
  296. while (token_index < tokens.size() && tokens[token_index].type() != Token::Type::RightParen) {
  297. auto param = tokens[token_index];
  298. if (param.type() != Token::Type::Identifier)
  299. return {};
  300. if (token_index + 1 >= tokens.size())
  301. return {};
  302. ++token_index;
  303. if (tokens[token_index].type() == Token::Type::Comma)
  304. ++token_index;
  305. else if (tokens[token_index].type() != Token::Type::RightParen)
  306. return {};
  307. definition.parameters.empend(param.text());
  308. }
  309. if (token_index >= tokens.size())
  310. return {};
  311. ++token_index;
  312. }
  313. if (token_index < tokens.size())
  314. definition.value = line.substring_view(tokens[token_index].start().column);
  315. return definition;
  316. }
  317. String Preprocessor::evaluate_macro_call(MacroCall const& macro_call, Definition const& definition)
  318. {
  319. if (macro_call.arguments.size() != definition.parameters.size()) {
  320. dbgln("mismatch in # of arguments for macro call: {}", macro_call.name.text());
  321. return {};
  322. }
  323. Lexer lexer { definition.value };
  324. auto tokens = lexer.lex();
  325. StringBuilder processed_value;
  326. for (auto& token : tokens) {
  327. if (token.type() != Token::Type::Identifier) {
  328. processed_value.append(token.text());
  329. continue;
  330. }
  331. auto param_index = definition.parameters.find_first_index(token.text());
  332. if (!param_index.has_value()) {
  333. processed_value.append(token.text());
  334. continue;
  335. }
  336. auto& argument = macro_call.arguments[*param_index];
  337. for (auto& arg_token : argument.tokens) {
  338. processed_value.append(arg_token.text());
  339. }
  340. }
  341. return processed_value.to_string();
  342. }
  343. };