-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTransformer.cpp
More file actions
123 lines (113 loc) · 2.66 KB
/
Transformer.cpp
File metadata and controls
123 lines (113 loc) · 2.66 KB
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
116
117
118
119
120
121
122
123
#include "Transformer.h"
namespace ds {
// helper function for precedence
// 1: a > b, 2 a = b, 3: a <b
// * +/- =
bool precOrSame(Token a ,Token b)
{
// return true if a >= b
if (a.kind == b.kind)
{
return true;
}
// a is different than b
else if (a.is(Token::Kind::Asterisk))
{
return true;
}
else if (b.is(Token::Kind::Asterisk))
{
return false;
}
else if (a.is(Token::Kind::Equal))
{
return false;
}
else if (b.is(Token::Kind::Equal))
{
return true;
}
// a and b could be either + or -
return true; // same precendece
}
/**
* Transform the token stream from infix to postfix form.
*
* @param infix list of tokens in infix notation
* @return stack<Token> token stack in postfix notation
*/
stack<Token>
InfixToPostfixTransformer::infixToPostfix(const VList<Token> &infix) {
// create postfix stack
stack<Token> postfixStk;
// create opStk for operators
stack<Token> opStk;
// for loop
for (int i = 0; i < infix.size(); i++)
{
// iterate through the infix token list
Token tk = infix.get(i); // the i-th token
// if tk is a number or a variable:
if (tk.is_one_of(Token::Kind::Number, Token::Kind::Variable))
{
postfixStk.push(tk);
}
// if tk is a plus, minus, equal, or asterisk:
else if (tk.is_one_of(Token::Kind::Plus, Token::Kind::Minus, Token::Kind::Equal, Token::Kind::Asterisk))
{
while (!(opStk.empty()) && !(opStk.top().is(Token::Kind::LeftParen)) &&
precOrSame(opStk.top(), tk))
{
// transfer tokens from opStk to postfixStk
postfixStk.push(opStk.top());
opStk.pop();
}
// push tk to opStk
opStk.push(tk);
}
// if tk is a '(' leftparen:
else if (tk.is(Token::Kind::LeftParen))
{
opStk.push(tk);
}
// if tk is a ')' rightparen:
else if (tk.is(Token::Kind::RightParen))
{
while (!opStk.empty())
{
// if left paren break
if (opStk.top().is(Token::Kind::LeftParen))
{
opStk.pop();
break;
}
else
{
// transfer tokens from opStk to postfixStk
postfixStk.push(opStk.top());
opStk.pop();
}
}
}
else if(tk.is(Token::Kind::Semicolon))
{
while (!opStk.empty())
{
// transfer tokens from opStk to postfixStk
postfixStk.push(opStk.top());
opStk.pop();
}
// push semicolon
postfixStk.push(tk);
}
}
// transfer tokens from opStk to postfixStk
while (!opStk.empty())
{
postfixStk.push(opStk.top());
opStk.pop();
}
// final return
return postfixStk;
}
} // namespace ds