-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExpressionParser.cpp
More file actions
52 lines (45 loc) · 1.19 KB
/
ExpressionParser.cpp
File metadata and controls
52 lines (45 loc) · 1.19 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
#include <sstream>
#include "ExpressionParser.h"
#include "ParseTree.h"
#include "DerivationVisitor.h"
#include "Context.h"
#include "Start.h"
#include "DivideByZeroException.h"
#include "InvalidDerivationException.h"
ParseTree * ExpressionParser::parse (const std::string & expression)
{
std::vector<std::string> * tokens = new std::vector<std::string> ();
std::stringstream input;
input << expression;
std::string token;
while (!input.eof ())
{
input >> token;
tokens->push_back (token);
}
return this->derive (tokens);
}
ParseTree * ExpressionParser::derive (std::vector<std::string> * tokens)
{
Context * context = new Context (tokens);
std::stack<Symbol *> & symbols = context->getSymbols ();
Start * startSymbol = new Start ();
symbols.push (startSymbol);
DerivationVisitor * derivationVisitor = new DerivationVisitor (context);
while (context->hasNextToken ())
{
Symbol * symbol = symbols.top ();
try
{
symbol->accept (*derivationVisitor);
}
catch (InvalidDerivationException & e)
{
delete derivationVisitor;
delete startSymbol;
throw e;
}
}
delete derivationVisitor;
return new ParseTree (startSymbol);
}