-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathcalculator.hpp
119 lines (89 loc) · 2.13 KB
/
calculator.hpp
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
#ifndef JUMBLE_CALCULATOR_HPP_INCLUDED
#define JUMBLE_CALCULATOR_HPP_INCLUDED
#include "jumble/util/common.hpp"
#include <string>
#include <iostream>
#include <vector>
JUMBLE_NAMESPACE_BEGIN
class Token {
friend bool operator==(const Token& lhs, const Token& rhs) noexcept {
return lhs.type_ == rhs.type_ && lhs.val_ == rhs.val_;
}
friend bool operator!=(const Token& lhs, const Token& rhs) noexcept {
return !(lhs == rhs);
}
public:
enum Type {
END_INPUT,
NUMBER,
OPERATOR
};
public:
static Token end() noexcept {
return Token(Type::END_INPUT, "$");
}
static Token num(const std::string& v) noexcept {
return Token(Type::NUMBER, v);
}
static Token oper(const std::string& v) noexcept {
return Token(Type::OPERATOR, v);
}
Type type() const noexcept {
return type_;
}
const std::string& val() const noexcept {
return val_;
}
private:
Token(const Type t, const std::string& v) noexcept
: type_(t), val_(v) {}
private:
Type type_;
std::string val_;
};
class Lexer {
public:
Lexer(std::istream& i) noexcept : cur(' '), is(i) {}
// Read and parser one token from input stream
Token scan();
private:
char cur;
std::istream &is;
};
class Parser {
public:
Parser(std::istream& i) noexcept : cur(Token::end()), lexer(i) {}
/*
Parse an infix arithmetic expression and return its postfix tokens.
@throw std::runtime_error if parse failed
*/
const std::vector<Token>& parse();
private:
void read() {
cur = lexer.scan();
}
// Recursive descent of nonterminals
void expr();
void A();
void tmpA();
void B();
void tmpB();
void factor();
private:
Token cur;
Lexer lexer;
std::vector<Token> postfix;
};
class Calculator {
public:
Calculator(std::istream& i) noexcept : parser(i) {}
/*
Return the result of an infix arithmetic expression.
@throw std::runtime_error if the expression is invalid
*/
long calculate();
private:
Parser parser;
};
JUMBLE_NAMESPACE_END
#endif