cpp-preprocessor.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /*
  2. * Copyright (c) 2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/LexicalPath.h>
  7. #include <LibCore/ArgsParser.h>
  8. #include <LibCore/File.h>
  9. #include <LibCpp/Preprocessor.h>
  10. int main(int argc, char** argv)
  11. {
  12. Core::ArgsParser args_parser;
  13. const char* path = nullptr;
  14. bool print_definitions = false;
  15. args_parser.add_positional_argument(path, "File", "file", Core::ArgsParser::Required::Yes);
  16. args_parser.add_option(print_definitions, "Print preprocessor definitions", "definitions", 'D');
  17. args_parser.parse(argc, argv);
  18. auto file = Core::File::construct(path);
  19. if (!file->open(Core::OpenMode::ReadOnly)) {
  20. warnln("Failed to open {}: {}", path, file->error_string());
  21. exit(1);
  22. }
  23. auto content = file->read_all();
  24. String name = LexicalPath::basename(path);
  25. Cpp::Preprocessor cpp(name, StringView { content });
  26. auto tokens = cpp.process_and_lex();
  27. if (print_definitions) {
  28. outln("Definitions:");
  29. for (auto& definition : cpp.definitions()) {
  30. if (definition.value.parameters.is_empty())
  31. outln("{}: {}", definition.key, definition.value.value);
  32. else
  33. outln("{}({}): {}", definition.key, String::join(",", definition.value.parameters), definition.value.value);
  34. }
  35. outln("");
  36. }
  37. for (auto& token : tokens) {
  38. outln("{}", token.to_string());
  39. }
  40. }