-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathparser.cpp
executable file
·99 lines (83 loc) · 2.1 KB
/
parser.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
#include "parser.h"
#include <QDebug>
CParser::CParser(CLexer *pLexer) : m_pLexer(pLexer) {}
double CParser::parsePrimaryExpression()
{
m_pLexer->getNextToken();
switch(m_pLexer->getCurrentToken())
{
case ETokenType::NUMBER:
{
double dNumber = m_pLexer->getNumber();
m_pLexer->getNextToken();
return dNumber;
}
case ETokenType::MINUS:
return -parsePrimaryExpression();
case ETokenType::LEFT_PAREN:
{
double dResult = parseAddSub();
if (m_pLexer->getCurrentToken() != ETokenType::RIGHT_PAREN)
{
qDebug() << "Error: missing brackets.";
exit(-1);
}
m_pLexer->getNextToken();
return dResult;
}
default:
qDebug() << "Error: exprected primary expression.";
exit(-1);
}
}
double CParser::parseMulDiv()
{
double dResult = parsePrimaryExpression();
while (true)
{
switch (m_pLexer->getCurrentToken())
{
case ETokenType::MUL:
dResult *= parsePrimaryExpression();
break;
case ETokenType::DIV:
{
double dTemp = parsePrimaryExpression();
if (dTemp != 0.0)
{
dResult /= dTemp;
break;
}
else
{
qDebug() << "Error: division by zero.";
exit(-1);
}
}
default:
return dResult;
}
}
}
double CParser::parseAddSub()
{
double dResult = parseMulDiv();
while (true)
{
switch (m_pLexer->getCurrentToken())
{
case ETokenType::PLUS:
dResult += parseMulDiv();
break;
case ETokenType::MINUS:
dResult -= parseMulDiv();
break;
default:
return dResult;
}
}
}
double CParser::calculate()
{
return parseAddSub();
}