-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathp_printers.cpp
103 lines (88 loc) · 1.55 KB
/
p_printers.cpp
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
91
92
93
94
95
96
97
98
99
100
101
102
#include "p_printers.hpp"
#include <string>
#include <iostream>
#include <vector>
using std::string;
using std::cout;
using std::ostream;
using std::endl;
using std::vector;
using std::to_string;
void printI(string s, int ind, ostream& ss = cout)
{
for(int i = 0; i < ind; ++i)
ss << " ";
ss << s << endl;
}
void p_printer::start(string s)
{
printI(s, ind, ss);
ind++;
}
void p_printer::done(bool good)
{
if(good) cout << ss.str();
}
void p_printer::end()
{
ind--;
}
void p_printer::match(token t)
{
printI((string)t, ind, ss);
}
string p_printer_dot::nextNode()
{
string s = "n";
s += to_string(nodeCount);
nodeCount += 1;
return s;
}
void p_printer_dot::start(string prod)
{
string node = nextNode();
ss << node << " [label=\"" << prod << "\" shape=box];" << endl;
if(!st.empty()) {
ss << st.back() << "->" << node
<< ";" << endl;
}
st.push_back(node);
}
void p_printer_dot::end()
{
if(!st.empty())
st.pop_back();
}
void p_printer_dot::matchStr(string s)
{
string node = nextNode();
ss << node << " [label=\"" << s << "\" shape=diamond];" << endl;
ss << st.back() << "->" << node
<< ";" << endl;
}
void p_printer_dot::match(token t)
{
matchStr(represent(t));
}
void p_printer_dot::done(bool good)
{
if(!good)
return;
cout << "digraph G {" << endl;
cout << ss.str();
cout << "}" << endl;
}
string p_printer_dot::represent(token t)
{
switch(t.k)
{
case token::KEYWORD:
return token::KWSTR[t.v];
case token::IDENTIFIER:
return t.id;
case token::INTEGER:
return to_string(t.v);
default:
return "Invalid token";
}
}