cpp-preprocessor.cpp 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. #include <LibMain/Main.h>
  11. ErrorOr<int> serenity_main(Main::Arguments arguments)
  12. {
  13. Core::ArgsParser args_parser;
  14. char const* path = nullptr;
  15. bool print_definitions = false;
  16. args_parser.add_positional_argument(path, "File", "file", Core::ArgsParser::Required::Yes);
  17. args_parser.add_option(print_definitions, "Print preprocessor definitions", "definitions", 'D');
  18. args_parser.parse(arguments);
  19. auto file = Core::File::construct(path);
  20. if (!file->open(Core::OpenMode::ReadOnly)) {
  21. warnln("Failed to open {}: {}", path, file->error_string());
  22. exit(1);
  23. }
  24. auto content = file->read_all();
  25. String name = LexicalPath::basename(path);
  26. Cpp::Preprocessor cpp(name, StringView { content });
  27. auto tokens = cpp.process_and_lex();
  28. if (print_definitions) {
  29. outln("Definitions:");
  30. for (auto& definition : cpp.definitions()) {
  31. if (definition.value.parameters.is_empty())
  32. outln("{}: {}", definition.key, definition.value.value);
  33. else
  34. outln("{}({}): {}", definition.key, String::join(',', definition.value.parameters), definition.value.value);
  35. }
  36. outln("");
  37. }
  38. for (auto& token : tokens) {
  39. outln("{}", token.to_string());
  40. }
  41. return 0;
  42. }