cpp-parser.cpp 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /*
  2. * Copyright (c) 2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibCore/ArgsParser.h>
  7. #include <LibCore/File.h>
  8. #include <LibCpp/Parser.h>
  9. int main(int argc, char** argv)
  10. {
  11. Core::ArgsParser args_parser;
  12. const char* path = nullptr;
  13. bool tokens_mode = false;
  14. bool preprocess_mode = false;
  15. args_parser.add_option(tokens_mode, "Print Tokens", "tokens", 'T');
  16. args_parser.add_option(preprocess_mode, "Print Preprocessed source", "preprocessed", 'P');
  17. args_parser.add_positional_argument(path, "Cpp File", "cpp-file", Core::ArgsParser::Required::No);
  18. args_parser.parse(argc, argv);
  19. if (!path)
  20. path = "Source/little/main.cpp";
  21. auto file = Core::File::construct(path);
  22. if (!file->open(Core::OpenMode::ReadOnly)) {
  23. perror("open");
  24. exit(1);
  25. }
  26. auto content = file->read_all();
  27. StringView content_view(content);
  28. ::Cpp::Preprocessor processor(path, content_view);
  29. auto preprocessed_content = processor.process();
  30. if (preprocess_mode) {
  31. outln(preprocessed_content);
  32. return 0;
  33. }
  34. ::Cpp::Parser parser(preprocessed_content, path);
  35. if (tokens_mode) {
  36. parser.print_tokens();
  37. return 0;
  38. }
  39. auto root = parser.parse();
  40. dbgln("Parser errors:");
  41. for (auto& error : parser.errors()) {
  42. dbgln("{}", error);
  43. }
  44. root->dump();
  45. }