-
Notifications
You must be signed in to change notification settings - Fork 0
/
parse.cpp
115 lines (93 loc) · 1.96 KB
/
parse.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
103
104
105
106
107
108
109
110
111
112
113
114
115
#include "parse.hpp"
#include <stack>
bool setHead(Expression &exp, const Token &token, bool isstring) {
Atom a;
if (isstring)
{
a = Atom(token.asString());
a.setStringType();
}
else
a = Atom(token);
exp.head() = a;
return !a.isNone();
}
bool append(Expression *exp, const Token &token, bool isstring) {
Atom a;
if (isstring)
{
a = Atom(token.asString());
a.setStringType();
}
else
a = Atom(token);
exp->append(a);
return !a.isNone();
}
Expression parse(const TokenSequenceType &tokens) noexcept {
Expression ast;
// cannot parse empty
if (tokens.empty())
return Expression();
bool athead = false;
bool instringconstant = false;
// stack tracks the last node created
std::stack<Expression *> stack;
std::size_t num_tokens_seen = 0;
for (auto &t : tokens) {
if (t.type() == Token::OPENQUOTATION) {
instringconstant = true;
}
else if (t.type() == Token::CLOSEQUOTATION) {
instringconstant = false;
}
else if (t.type() == Token::OPEN) {
athead = true;
}
else if (t.type() == Token::CLOSE) {
if (stack.empty()) {
return Expression();
}
stack.pop();
if (stack.empty()) {
num_tokens_seen += 1;
break;
}
}
else {
if (athead) {
if (stack.empty()) {
if (!setHead(ast, t, instringconstant)) {
return Expression();
}
stack.push(&ast);
}
else {
if (stack.empty()) {
return Expression();
}
// if adding a nontype is true
if (!append(stack.top(), t, instringconstant)) {
return Expression();
}
stack.push(stack.top()->tail());
}
athead = false;
}
else {
if (stack.empty()) {
return Expression();
}
if (!append(stack.top(), t, instringconstant)) {
return Expression();
}
}
}
num_tokens_seen += 1;
}
// open will make it push into stack and close will make it pop out of stact
if (stack.empty() && (num_tokens_seen == tokens.size())) {
return ast;
}
return Expression();
};