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
|
#include <boost/optional.hpp>
#include <boost/program_options.hpp>
#include <iostream>
#include <limits>
#include "src/parser.h"
boost::optional<boost::program_options::variables_map> input(
int argc,
char** argv
) {
boost::program_options::options_description optionDescription(
"Supported options"
);
optionDescription.add_options()
(
"input",
boost::program_options::value<std::vector<std::string>>(),
"terms to be evaluated"
)
(
"tree",
boost::program_options::value<bool>()->implicit_value(true),
"return the binary expression tree instead of evaluating"
)
;
boost::program_options::variables_map variables;
try {
boost::program_options::store(
boost::program_options::parse_command_line(
argc, argv, optionDescription
),
variables
);
boost::program_options::notify(variables);
}
catch ( const std::exception& exception ) {
std::cerr << exception.what() << std::endl;
std::cout << optionDescription << std::endl;
return boost::optional<boost::program_options::variables_map>();
}
return boost::make_optional(variables);
}
bool process(const boost::program_options::variables_map& variables) {
const bool replMode{ variables.count("input") == 0 };
const bool treeMode{ variables.count("tree") ? variables["tree"].as<bool>()
: false };
if ( replMode ) {
std::cout.precision(
std::numeric_limits<double>::digits10
);
std::string term;
while ( std::cin >> term ) {
try {
if ( treeMode) {
std::cout << SimpleParser::print(term);
} else {
std::cout << SimpleParser::calculate(term);
}
std::cout << std::endl;
}
catch ( std::exception &exception ) {
std::cerr << exception.what() << std::endl;
}
}
return true;
} else {
const std::vector<std::string> inputTerms{
variables["input"].as<std::vector<std::string>>()
};
try {
std::for_each(
inputTerms.cbegin(),
inputTerms.cend(),
[treeMode](const std::string& term) {
if ( treeMode) {
std::cout << SimpleParser::print(term);
} else {
std::cout << term
<< " = "
<< SimpleParser::calculate(term);
}
std::cout << std::endl;
}
);
}
catch ( std::exception &exception ) {
std::cerr << exception.what() << std::endl;
return false;
}
return true;
}
}
int main(int argc, char** argv) {
if ( auto variables = input(argc, argv) ) {
if ( process(*variables) ) {
return 0;
} else {
return 1;
}
} else {
return 1;
}
}
|