cpp-preprocessor.cpp 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. /*
  2. * Copyright (c) 2021-2022, 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/Stream.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. StringView path;
  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 = TRY(Core::Stream::File::open(path, Core::Stream::OpenMode::Read));
  20. auto content = TRY(file->read_all());
  21. String name = LexicalPath::basename(path);
  22. Cpp::Preprocessor cpp(name, StringView { content });
  23. auto tokens = cpp.process_and_lex();
  24. if (print_definitions) {
  25. outln("Definitions:");
  26. for (auto const& definition : cpp.definitions()) {
  27. if (definition.value.parameters.is_empty())
  28. outln("{}: {}", definition.key, definition.value.value);
  29. else
  30. outln("{}({}): {}", definition.key, String::join(',', definition.value.parameters), definition.value.value);
  31. }
  32. outln("");
  33. }
  34. for (auto& token : tokens) {
  35. outln("{}", token.to_string());
  36. }
  37. return 0;
  38. }