-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathcalculator.cpp
75 lines (64 loc) · 2.52 KB
/
calculator.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
/**
* This example demonstrate how we can use peg_parser::parser to define a
* simple command-line calculator. The parser supports the basic operators `+`,
* `-`, `*`, `/`, `^` as well as using and assigning variables via `=`.
*
* Note, that The grammar is defined in a left-recursive way. While this is
* easiest to implement, it recomended to rewrite left-recursive grammars
* sequentially for optimal performance.
*/
#include <peg_parser/generator.h>
#include <cmath>
#include <iostream>
#include <unordered_map>
int main() {
using namespace std;
using VariableMap = unordered_map<string, float>;
peg_parser::ParserGenerator<float, VariableMap &> calculator;
auto &g = calculator;
g.setSeparator(g["Whitespace"] << "[\t ]");
g["Expression"] << "Set | Sum";
g["Set"] << "Name '=' Sum" >> [](auto e, auto &v) { return v[e[0].string()] = e[1].evaluate(v); };
g["Sum"] << "Add | Subtract | Product";
g["Product"] << "Multiply | Divide | Exponent";
g["Exponent"] << "Power | Atomic";
g["Atomic"] << "Number | Brackets | Variable";
g["Brackets"] << "'(' Sum ')'";
g["Add"] << "Sum '+' Product" >>
[](auto e, auto &v) { return e[0].evaluate(v) + e[1].evaluate(v); };
g["Subtract"] << "Sum '-' Product" >>
[](auto e, auto &v) { return e[0].evaluate(v) - e[1].evaluate(v); };
g["Multiply"] << "Product '*' Exponent" >>
[](auto e, auto &v) { return e[0].evaluate(v) * e[1].evaluate(v); };
g["Divide"] << "Product '/' Exponent" >>
[](auto e, auto &v) { return e[0].evaluate(v) / e[1].evaluate(v); };
g["Power"] << "Atomic ('^' Exponent)" >>
[](auto e, auto &v) { return pow(e[0].evaluate(v), e[1].evaluate(v)); };
g["Variable"] << "Name" >> [](auto e, auto &v) { return v[e[0].string()]; };
g["Name"] << "[a-zA-Z] [a-zA-Z0-9]*";
g["Number"] << "'-'? [0-9]+ ('.' [0-9]+)?" >> [](auto e, auto &) { return stod(e.string()); };
g.setStart(g["Expression"]);
cout << "Enter an expression to be evaluated.\n";
VariableMap variables;
while (true) {
string str;
cout << "> ";
getline(cin, str);
if (str == "q" || str == "quit") {
break;
}
try {
auto result = calculator.run(str, variables);
cout << str << " = " << result << endl;
} catch (peg_parser::SyntaxError &error) {
auto syntax = error.syntax;
cout << " ";
cout << string(syntax->begin, ' ');
cout << string(syntax->length(), '~');
cout << "^\n";
cout << " "
<< "Syntax error while parsing " << syntax->rule->name << endl;
}
}
return 0;
}