-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAstPrinter.h
90 lines (73 loc) · 2.28 KB
/
AstPrinter.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#pragma once
#include "Expr/ExprVisitor.h"
#include "Expr/Expr.h"
#include <vector>
#include <string>
class AstPrinter : ExprVisitor <std::any>
{
private:
std::string Parenthesize(std::string name, std::vector<ExprPtr> exprs)
{
std::string builder = "";
builder += "(" + name;
for (auto e : exprs)
{
builder += " ";
auto visitor = reinterpret_cast<ExprVisitor<std::any>*>(this);
std::any accept = e->Accept(*visitor);
if (accept.type() == typeid(builder))
builder += std::any_cast<std::string>(accept);
else
builder += std::to_string(std::any_cast<double>(accept));
}
builder += ")";
return builder;
}
public:
std::any VisitBinaryExpr(const Binary& expr) override
{
std::vector<ExprPtr> ptrs;
ptrs.push_back(expr.GetLeftExpr());
ptrs.push_back(expr.GetRightExpr());
return Parenthesize(expr.GetOp().LiteralToString(), ptrs);
}
std::any VisitGroupingExpr(const Grouping& expr) override
{
std::vector<ExprPtr> ptrs;
ptrs.push_back(expr.GetExpr());
return Parenthesize("group", ptrs);
}
std::any VisitLiteralExpr(const Literal& expr) override
{
std::any literal = expr.GetLiteral();
if (!literal.has_value())
{
return "nil";
}
std::string str;
auto ltrType = literal.type().name();
if (literal.type() == typeid(str))
{
return std::any_cast<std::string>(literal);
}
if (literal.type() == typeid(bool))
{
return std::any_cast<bool>(literal);
}
return std::any_cast<double>(literal);
}
std::any VisitUnaryExpr(const Unary& expr) override
{
std::vector<ExprPtr> ptrs;
ptrs.push_back(expr.GetRight());
return Parenthesize(expr.GetOperator().LiteralToString(), ptrs);
}
std::any Print(ExprPtr expr)
{
std::any re = expr->Accept(reinterpret_cast<ExprVisitor<std::any>&>(*this));
std::string str;
if (re.type() == typeid(str))
return std::any_cast<std::string>(re);
return std::to_string(std::any_cast<double>(re));
}
};