Removed print_ast, and added ast_to_s.

This commit is contained in:
Yuji Hirose 2015-11-27 15:32:17 -05:00
parent 444398d1bb
commit 3f5d54f811
3 changed files with 24 additions and 33 deletions

View File

@ -124,7 +124,8 @@ int main(int argc, const char** argv)
}
ast = peg::AstOptimizer(opt_optimize_ast_nodes).optimize(ast);
peg::print_ast(ast);
std::cout << peg::ast_to_s(ast);
} else {
if (!parser.parse_n(source.data(), source.size())) {
return -1;

View File

@ -265,29 +265,6 @@ bool parse_code(const string& text, peg::parser& peg, string& json, shared_ptr<p
return ret;
}
template <typename T>
void dump_ast(const shared_ptr<T>& ptr, string& json, int level = 0)
{
const auto& ast = *ptr;
for (auto i = 0; i < level; i++) {
json += " ";
}
string name;
if (ast.name == ast.original_name) {
name = ast.name;
} else {
name = ast.original_name + " (" + ast.name + ")";
}
if (ast.is_token) {
json += "- " + name + "(" + ast.token + ")\\n";
} else {
json += "+ " + name +"\\n";
}
for (auto node : ast.nodes) {
dump_ast(node, json, level + 1);
}
}
std::string replace_text(std::string &s, const std::string &toReplace, const std::string &replaceWith)
{
return(s.replace(s.find(toReplace), toReplace.length(), replaceWith));
@ -319,8 +296,8 @@ int run_server(int port, const vector<char>& syntax, const vector<char>& source)
const auto& codeText = req.params.at("code");
shared_ptr<peg::Ast> ast;
if (parse_code(codeText, peg, codeResult, ast)) {
dump_ast(ast, astResult);
dump_ast(peg::AstOptimizer(true).optimize(ast), astResultOptimized);
astResult = peg::ast_to_s(ast);
astResultOptimized = peg::ast_to_s(peg::AstOptimizer(true).optimize(ast));
}
}

View File

@ -2129,21 +2129,34 @@ struct AstBase : public Annotation
};
template <typename T>
void print_ast(const std::shared_ptr<T>& ptr, int level = 0) {
void ast_to_s(const std::shared_ptr<T>& ptr, std::string& s, int level = 0) {
const auto& ast = *ptr;
for (auto i = 0; i < level; i++) { std::cout << " "; }
for (auto i = 0; i < level; i++) {
s += " ";
}
std::string name;
if (ast.name == ast.original_name) {
name = ast.name;
} else {
}
else {
name = ast.original_name + " (" + ast.name + ")";
}
if (ast.is_token) {
std::cout << "- " << name << ": '" << ast.token << "'" << std::endl;
} else {
std::cout << "+ " << name << std::endl;
s += "- " + name + "(" + ast.token + ")\\n";
}
for (auto node : ast.nodes) { print_ast(node, level + 1); }
else {
s += "+ " + name + "\\n";
}
for (auto node : ast.nodes) {
ast_to_s(node, s, level + 1);
}
}
template <typename T>
std::string ast_to_s(const std::shared_ptr<T>& ptr) {
std::string s;
ast_to_s(ptr, s);
return s;
}
struct AstOptimizer