|
1 | 1 | #include "ParserFsm.hpp" |
2 | 2 |
|
3 | | -namespace ovum::compiler::parser {} // namespace ovum::compiler::parser |
| 3 | +#include <memory> |
| 4 | +#include <utility> |
| 5 | + |
| 6 | +#include "context/ContextParser.hpp" |
| 7 | +#include "lib/parser/diagnostics/IDiagnosticSink.hpp" |
| 8 | +#include "lib/parser/states/base/IState.hpp" |
| 9 | +#include "lib/parser/states/base/StateError.hpp" |
| 10 | +#include "lib/parser/states/base/StateRegistry.hpp" |
| 11 | +#include "lib/parser/tokens/token_streams/ITokenStream.hpp" |
| 12 | +#include "recovery/SimpleRecovery.hpp" |
| 13 | + |
| 14 | +namespace ovum::compiler::parser { |
| 15 | + |
| 16 | +ParserFsm::ParserFsm(std::unique_ptr<IExpressionParser> expr, |
| 17 | + std::unique_ptr<ITypeParser> typep, |
| 18 | + std::unique_ptr<IAstFactory> factory) : |
| 19 | + expr_parser_(std::move(expr)), type_parser_(std::move(typep)), factory_(std::move(factory)) { |
| 20 | +} |
| 21 | + |
| 22 | +std::unique_ptr<Module> ParserFsm::Parse(ITokenStream& token_stream, IDiagnosticSink& diagnostics) { |
| 23 | + ContextParser context; |
| 24 | + context.SetDiagnostics(&diagnostics); |
| 25 | + context.SetExpr(expr_parser_.get()); |
| 26 | + context.SetTypeParser(type_parser_.get()); |
| 27 | + context.SetFactory(factory_.get()); |
| 28 | + |
| 29 | + SimpleRecovery recovery; |
| 30 | + |
| 31 | + context.PushState(StateRegistry::Module()); |
| 32 | + |
| 33 | + while (const IState* state = context.CurrentState()) { |
| 34 | + auto step = state->TryStep(context, token_stream); |
| 35 | + |
| 36 | + if (!step.has_value()) { |
| 37 | + const auto& message = step.error().Message(); |
| 38 | + diagnostics.Error("P0001", message.empty() ? "parse error" : message); |
| 39 | + recovery.SyncToStatementEnd(token_stream); |
| 40 | + context.PopState(); |
| 41 | + continue; |
| 42 | + } |
| 43 | + |
| 44 | + if (!*step) { |
| 45 | + context.PopState(); |
| 46 | + } |
| 47 | + } |
| 48 | + |
| 49 | + std::unique_ptr<AstNode> root = context.PopNode(); |
| 50 | + |
| 51 | + if (!root) { |
| 52 | + return std::make_unique<Module>(); |
| 53 | + } |
| 54 | + |
| 55 | + auto* as_module = dynamic_cast<Module*>(root.get()); |
| 56 | + |
| 57 | + if (as_module != nullptr) { |
| 58 | + root.release(); |
| 59 | + return std::unique_ptr<Module>(as_module); |
| 60 | + } |
| 61 | + |
| 62 | + return std::make_unique<Module>(); |
| 63 | +} |
| 64 | + |
| 65 | +} // namespace ovum::compiler::parser |
0 commit comments