WsParser_VS/libSyntax/ast_gen.cpp

71 lines
2.2 KiB
C++

#include "ast_gen.h"
using namespace ast_gen;
using namespace ast_basic;
using namespace lib_token;
using namespace lib_syntax;
using namespace lib_words;
SyntaxParser::SyntaxParser(std::shared_ptr<const IBasicRule> rule)
: _rule_bind(rule) { }
QList<std::shared_ptr<const MatchCursor>> SyntaxParser::parse(std::shared_ptr<const IPrimitiveWord> words) {
auto cursor = std::make_shared<MatchCursor>(words->file());
cursor->setCurrent(nullptr, words);
auto list = this->_rule_bind->parse(cursor);
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();
std::sort(list.begin(), list.end(),
[&](std::shared_ptr<const MatchCursor> a, std::shared_ptr<const MatchCursor> b) {
auto mark_a = a->token()->position() * 100 - a->totalErrorCount();
auto mark_b = b->token()->position() * 100 - b->totalErrorCount();
return mark_a > mark_b;
});
return list;
}
#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) {
QList<std::shared_ptr<const IActionToken>> token_seqs;
std::shared_ptr<const IActionToken> action_token = cursor->token();
while (action_token) {
token_seqs.prepend(action_token);
action_token = action_token->prevToken();
}
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;
}
void ast_gen::SyntaxParser::astPresent(std::shared_ptr<const ast_basic::IExprInstance> node, int depth) {
auto msg = QString(depth * 4, ' ');
if (node->definedRule()) {
auto token_seqs = node->tokens();
QList<QString> _contents;
std::transform(token_seqs.begin(), token_seqs.end(),
std::back_inserter(_contents),
[](std::shared_ptr<const lib_token::IToken> t) { return t->content(); });
qDebug().noquote() << msg + node->definedRule()->name() << _contents;
}
else
qDebug().noquote() << msg + "Program";
for (auto it : node->children())
astPresent(it, depth + 1);
}