2015-02-22 04:19:54 +00:00
|
|
|
//
|
|
|
|
// calc3.cc
|
|
|
|
//
|
|
|
|
// Copyright (c) 2015 Yuji Hirose. All rights reserved.
|
|
|
|
// MIT License
|
|
|
|
//
|
|
|
|
|
|
|
|
#include <peglib.h>
|
|
|
|
#include <iostream>
|
|
|
|
#include <cstdlib>
|
|
|
|
|
2015-08-10 20:37:56 +00:00
|
|
|
using namespace peg;
|
2015-02-22 04:19:54 +00:00
|
|
|
|
|
|
|
int main(int argc, const char** argv)
|
|
|
|
{
|
2019-11-21 16:52:31 +00:00
|
|
|
if (argc < 2 || std::string("--help") == argv[1]) {
|
|
|
|
std::cout << "usage: calc3 [formula]" << std::endl;
|
2015-02-22 04:19:54 +00:00
|
|
|
return 1;
|
|
|
|
}
|
|
|
|
|
2019-11-21 16:52:31 +00:00
|
|
|
std::function<long (const Ast&)> eval = [&](const Ast& ast) {
|
2015-06-14 12:06:09 +00:00
|
|
|
if (ast.name == "NUMBER") {
|
|
|
|
return stol(ast.token);
|
|
|
|
} else {
|
|
|
|
const auto& nodes = ast.nodes;
|
|
|
|
auto result = eval(*nodes[0]);
|
|
|
|
for (auto i = 1u; i < nodes.size(); i += 2) {
|
|
|
|
auto num = eval(*nodes[i + 1]);
|
|
|
|
auto ope = nodes[i]->token[0];
|
|
|
|
switch (ope) {
|
|
|
|
case '+': result += num; break;
|
|
|
|
case '-': result -= num; break;
|
|
|
|
case '*': result *= num; break;
|
|
|
|
case '/': result /= num; break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return result;
|
|
|
|
}
|
|
|
|
};
|
2015-06-04 15:41:14 +00:00
|
|
|
|
2015-08-10 20:37:56 +00:00
|
|
|
parser parser(R"(
|
2015-11-26 01:53:04 +00:00
|
|
|
EXPRESSION <- TERM (TERM_OPERATOR TERM)*
|
2015-08-07 03:09:37 +00:00
|
|
|
TERM <- FACTOR (FACTOR_OPERATOR FACTOR)*
|
2015-11-26 01:53:04 +00:00
|
|
|
FACTOR <- NUMBER / '(' EXPRESSION ')'
|
|
|
|
|
2016-01-24 01:26:54 +00:00
|
|
|
TERM_OPERATOR <- < [-+] >
|
|
|
|
FACTOR_OPERATOR <- < [/*] >
|
|
|
|
NUMBER <- < [0-9]+ >
|
2015-11-26 01:53:04 +00:00
|
|
|
|
|
|
|
%whitespace <- [ \t\r\n]*
|
2015-08-07 03:09:37 +00:00
|
|
|
)");
|
2015-02-22 04:19:54 +00:00
|
|
|
|
2015-07-31 17:06:31 +00:00
|
|
|
parser.enable_ast();
|
2015-02-22 04:19:54 +00:00
|
|
|
|
2015-03-11 17:53:24 +00:00
|
|
|
auto expr = argv[1];
|
2019-11-21 16:52:31 +00:00
|
|
|
std::shared_ptr<Ast> ast;
|
2015-03-11 17:53:24 +00:00
|
|
|
if (parser.parse(expr, ast)) {
|
2015-07-31 17:06:31 +00:00
|
|
|
ast = AstOptimizer(true).optimize(ast);
|
2019-11-21 16:52:31 +00:00
|
|
|
std::cout << ast_to_s(ast);
|
|
|
|
std::cout << expr << " = " << eval(*ast) << std::endl;
|
2015-02-22 04:19:54 +00:00
|
|
|
return 0;
|
|
|
|
}
|
|
|
|
|
2019-11-21 16:52:31 +00:00
|
|
|
std::cout << "syntax error..." << std::endl;
|
2015-02-22 04:19:54 +00:00
|
|
|
|
|
|
|
return -1;
|
|
|
|
}
|
|
|
|
|
|
|
|
// vim: et ts=4 sw=4 cin cino={1s ff=unix
|