-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparse.cpp
107 lines (83 loc) · 2.13 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
#include "parse.hpp"
#include <stack>
bool setHead(Expression &exp, const Token &token, bool &isStringLiteral) {
Atom a(token);
if (isStringLiteral)
a.setStringLiteral();
exp.head() = a;
return !a.isNone();
}
bool append(Expression *exp, const Token &token, bool &isStringKind) {
Atom a(token);
if (isStringKind)
a.setStringLiteral();
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 stringLiteral = false;
// stack tracks the last node created
std::stack<Expression *> stack;
std::size_t num_tokens_seen = 0;
std::size_t num_quotes_seen = 0;
for (auto &t : tokens) {
if (t.type() == Token::OPEN) {
athead = true;
}
else if (t.type() == Token::CLOSE) {
if (stack.empty() || num_quotes_seen%2 == 1) {
return Expression();
}
stack.pop();
if (stack.empty()) {
num_tokens_seen += 1;
break;
}
}
else if (t.type() == Token::STRINGLITERAL)
{
stringLiteral = true;
num_quotes_seen++;
if (num_quotes_seen >= 2 && num_quotes_seen%2 == 0)
stringLiteral = false;
}
else {
if (athead) {
if (stack.empty()) {
if (!setHead(ast, t,stringLiteral)) { // is this a non kind
return Expression();
}
stack.push(&ast);
}
else {
if (stack.empty()) {
return Expression();
}
if (!append(stack.top(), t,stringLiteral)) {
return Expression();
}
stack.push(stack.top()->tail());
}
athead = false;
}
else {
if (stack.empty()) {
return Expression();
}
if (!append(stack.top(), t,stringLiteral)) {
return Expression();
}
}
}
num_tokens_seen += 1;
}
if (stack.empty() && (num_tokens_seen == tokens.size())) {
return ast;
}
return Expression();
};