WsParser_VS/libSyntax/ast_gen.cpp

64 lines
1.9 KiB
C++
Raw Normal View History

2024-03-17 07:58:28 +00:00
#include "ast_gen.h"
using namespace ast_gen;
2025-02-07 15:26:20 +00:00
using namespace ast_basic;
using namespace lib_token;
using namespace lib_syntax;
using namespace lib_words;
2024-03-17 07:58:28 +00:00
2025-02-08 05:40:36 +00:00
SyntaxParser::SyntaxParser(std::shared_ptr<const IBasicRule> rule)
2025-02-07 15:26:20 +00:00
: _rule_bind(rule) { }
2024-03-17 07:58:28 +00:00
2025-02-08 05:40:36 +00:00
QList<std::shared_ptr<const MatchCursor>> SyntaxParser::parse(std::shared_ptr<const IPrimitiveWord> words) {
auto cursor = std::make_shared<MatchCursor>(words->file());
2025-02-07 15:26:20 +00:00
cursor->setCurrent(nullptr, words);
2024-03-17 07:58:28 +00:00
2025-02-15 04:57:53 +00:00
auto list = this->_rule_bind->parse(cursor);
2025-02-14 17:48:14 +00:00
QHash<QString, std::shared_ptr<const MatchCursor>> result_map;
std::for_each(list.begin(), list.end(),
[&](std::shared_ptr<const MatchCursor> ins) {
result_map[ins->parseSyntax()] = ins;
});
list = result_map.values();
2025-02-07 15:26:20 +00:00
std::sort(list.begin(), list.end(),
[&](std::shared_ptr<const MatchCursor> a, std::shared_ptr<const MatchCursor> b) {
2025-02-15 04:57:53 +00:00
auto mark_a = a->token()->position() * 100 - a->totalErrorCount();
auto mark_b = b->token()->position() * 100 - b->totalErrorCount();
2025-02-14 17:48:14 +00:00
return mark_a > mark_b;
});
2024-03-17 07:58:28 +00:00
2025-02-07 15:26:20 +00:00
return list;
2024-03-17 07:58:28 +00:00
}
2025-02-07 15:26:20 +00:00
#include "tokens_impl.h"
std::shared_ptr<IExprInstance> ast_gen::SyntaxParser::getAst(
std::shared_ptr<const lib_syntax::MatchCursor> cursor, std::shared_ptr<IExprInstance> root) {
2025-02-08 01:06:39 +00:00
QList<std::shared_ptr<const IActionToken>> token_seqs;
2025-02-15 04:57:53 +00:00
std::shared_ptr<const IActionToken> action_token = cursor->token();
2025-02-08 01:06:39 +00:00
while (action_token) {
token_seqs.prepend(action_token);
2025-02-07 15:26:20 +00:00
action_token = action_token->prevToken();
}
2024-03-17 07:58:28 +00:00
2025-02-08 01:06:39 +00:00
auto expr_inst = root;
for (auto ins_t : token_seqs) {
expr_inst = std::const_pointer_cast<IActionToken>(ins_t)->makeSure(expr_inst);
}
return expr_inst;
2024-03-17 07:58:28 +00:00
}
2025-02-15 04:57:53 +00:00
void ast_gen::SyntaxParser::astPresent(std::shared_ptr<const ast_basic::IExprInstance> node, int depth) {
auto msg = QString(depth * 4, ' ');
if (node->definedRule())
qDebug() << msg + node->definedRule()->name();
else
qDebug() << msg + "Program";
for (auto it : node->children())
astPresent(it, depth + 1);
}