main.cpp 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174
  1. /*
  2. * Copyright (c) 2023, Dan Klishch <danilklishch@gmail.com>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Format.h>
  7. #include <LibCore/ArgsParser.h>
  8. #include <LibMain/Main.h>
  9. #include "Compiler/Passes/CFGBuildingPass.h"
  10. #include "Compiler/Passes/CFGSimplificationPass.h"
  11. #include "Compiler/Passes/DeadCodeEliminationPass.h"
  12. #include "Compiler/Passes/IfBranchMergingPass.h"
  13. #include "Compiler/Passes/ReferenceResolvingPass.h"
  14. #include "Compiler/Passes/SSABuildingPass.h"
  15. #include "Function.h"
  16. #include "Parser/CppASTConverter.h"
  17. #include "Parser/SpecParser.h"
  18. using namespace JSSpecCompiler;
  19. struct CompilationStepWithDumpOptions {
  20. OwnPtr<CompilationStep> step;
  21. bool dump_ast = false;
  22. bool dump_cfg = false;
  23. };
  24. class CompilationPipeline {
  25. public:
  26. template<typename T>
  27. void add_compilation_pass()
  28. {
  29. auto func = +[](TranslationUnitRef translation_unit) {
  30. T { translation_unit }.run();
  31. };
  32. add_step(adopt_own_if_nonnull(new NonOwningCompilationStep(T::name, func)));
  33. }
  34. template<typename T>
  35. void for_each_step_in(StringView pass_list, T&& func)
  36. {
  37. HashTable<StringView> selected_steps;
  38. for (auto pass : pass_list.split_view(',')) {
  39. if (pass == "all") {
  40. for (auto const& step : m_pipeline)
  41. selected_steps.set(step.step->name());
  42. } else if (pass == "last") {
  43. selected_steps.set(m_pipeline.last().step->name());
  44. } else if (pass.starts_with('-')) {
  45. VERIFY(selected_steps.remove(pass.substring_view(1)));
  46. } else {
  47. selected_steps.set(pass);
  48. }
  49. }
  50. for (auto& step : m_pipeline)
  51. if (selected_steps.contains(step.step->name()))
  52. func(step);
  53. }
  54. void add_step(OwnPtr<CompilationStep>&& step)
  55. {
  56. m_pipeline.append({ move(step) });
  57. }
  58. auto const& pipeline() const { return m_pipeline; }
  59. private:
  60. Vector<CompilationStepWithDumpOptions> m_pipeline;
  61. };
  62. template<>
  63. struct AK::Formatter<Vector<FunctionArgument>> : AK::Formatter<StringView> {
  64. ErrorOr<void> format(FormatBuilder& builder, Vector<FunctionArgument> const& arguments)
  65. {
  66. for (size_t i = 0; i < arguments.size(); ++i) {
  67. TRY(builder.put_string(arguments[i].name));
  68. if (i + 1 != arguments.size())
  69. TRY(builder.put_literal(", "sv));
  70. }
  71. return {};
  72. }
  73. };
  74. ErrorOr<int> serenity_main(Main::Arguments arguments)
  75. {
  76. Core::ArgsParser args_parser;
  77. StringView filename;
  78. args_parser.add_positional_argument(filename, "File to compile", "file");
  79. constexpr StringView language_spec = "spec"sv;
  80. constexpr StringView language_cpp = "c++"sv;
  81. StringView language = language_spec;
  82. args_parser.add_option(Core::ArgsParser::Option {
  83. .argument_mode = Core::ArgsParser::OptionArgumentMode::Optional,
  84. .help_string = "Specify the language of the input file.",
  85. .short_name = 'x',
  86. .value_name = "{c++|spec}",
  87. .accept_value = [&](StringView value) {
  88. language = value;
  89. return language.is_one_of(language_spec, language_cpp);
  90. },
  91. });
  92. StringView passes_to_dump_ast;
  93. args_parser.add_option(passes_to_dump_ast, "Dump AST after specified passes.", "dump-ast", 0, "{all|last|<pass-name>|-<pass-name>[,...]}");
  94. StringView passes_to_dump_cfg;
  95. args_parser.add_option(passes_to_dump_cfg, "Dump CFG after specified passes.", "dump-cfg", 0, "{all|last|<pass-name>|-<pass-name>[,...]}");
  96. args_parser.parse(arguments);
  97. CompilationPipeline pipeline;
  98. if (language == language_cpp)
  99. pipeline.add_step(adopt_own_if_nonnull(new CppParsingStep()));
  100. else
  101. pipeline.add_step(adopt_own_if_nonnull(new SpecParsingStep()));
  102. pipeline.add_compilation_pass<IfBranchMergingPass>();
  103. pipeline.add_compilation_pass<ReferenceResolvingPass>();
  104. pipeline.add_compilation_pass<CFGBuildingPass>();
  105. pipeline.add_compilation_pass<CFGSimplificationPass>();
  106. pipeline.add_compilation_pass<SSABuildingPass>();
  107. pipeline.add_compilation_pass<DeadCodeEliminationPass>();
  108. pipeline.for_each_step_in(passes_to_dump_ast, [](CompilationStepWithDumpOptions& step) {
  109. step.dump_ast = true;
  110. });
  111. pipeline.for_each_step_in(passes_to_dump_cfg, [](CompilationStepWithDumpOptions& step) {
  112. step.dump_cfg = true;
  113. });
  114. TranslationUnit translation_unit(filename);
  115. // Functions referenced in DifferenceISODate
  116. // TODO: This is here just for testing. In a long run, we need some place, which is not
  117. // `serenity_main`, to store built-in functions.
  118. translation_unit.adopt_declaration(make_ref_counted<FunctionDeclaration>("CompareISODate"sv, Vector<FunctionArgument> {}));
  119. translation_unit.adopt_declaration(make_ref_counted<FunctionDeclaration>("CreateDateDurationRecord"sv, Vector<FunctionArgument> {}));
  120. translation_unit.adopt_declaration(make_ref_counted<FunctionDeclaration>("AddISODate"sv, Vector<FunctionArgument> {}));
  121. translation_unit.adopt_declaration(make_ref_counted<FunctionDeclaration>("ISODaysInMonth"sv, Vector<FunctionArgument> {}));
  122. translation_unit.adopt_declaration(make_ref_counted<FunctionDeclaration>("ISODateToEpochDays"sv, Vector<FunctionArgument> {}));
  123. translation_unit.adopt_declaration(make_ref_counted<FunctionDeclaration>("truncate"sv, Vector<FunctionArgument> {}));
  124. translation_unit.adopt_declaration(make_ref_counted<FunctionDeclaration>("remainder"sv, Vector<FunctionArgument> {}));
  125. for (auto const& step : pipeline.pipeline()) {
  126. step.step->run(&translation_unit);
  127. if (translation_unit.diag().has_fatal_errors()) {
  128. translation_unit.diag().print_diagnostics();
  129. return 1;
  130. }
  131. if (step.dump_ast) {
  132. outln(stderr, "===== AST after {} =====", step.step->name());
  133. for (auto const& function : translation_unit.functions_to_compile()) {
  134. outln(stderr, "{}({}):", function->m_name, function->m_arguments);
  135. outln(stderr, "{}", function->m_ast);
  136. }
  137. }
  138. if (step.dump_cfg && translation_unit.functions_to_compile().size() && translation_unit.functions_to_compile()[0]->m_cfg != nullptr) {
  139. outln(stderr, "===== CFG after {} =====", step.step->name());
  140. for (auto const& function : translation_unit.functions_to_compile()) {
  141. outln(stderr, "{}({}):", function->m_name, function->m_arguments);
  142. outln(stderr, "{}", *function->m_cfg);
  143. }
  144. }
  145. }
  146. translation_unit.diag().print_diagnostics();
  147. return 0;
  148. }