buffalo
Loading...
Searching...
No Matches
calculator.cpp
Go to the documentation of this file.
1#include <iostream>
2#include <cmath>
3#include <buffalo/buffalo.h>
4
5/*
6 * Grammar Definition
7 */
9
10/*
11 * Terminals
12 */
13bf::DefineTerminal<G, R"(\d+(\.\d+)?)", double> NUMBER([](auto const &tok) {
14 return std::stod(std::string(tok.raw));
15});
16
18
23
24bf::DefineTerminal<G, R"(\‍()"> PAR_OPEN;
26
27/*
28 * Non-Terminals
29 */
31 = bf::PR<G>(NUMBER)<=>[](auto &$) { return $[0]; }
32 | (PAR_OPEN + expression + PAR_CLOSE)<=>[](auto &$) { return $[1]; }
33 | (expression + OP_EXP + expression)<=>[](auto &$) { return std::pow($[0], $[2]); }
34 | (expression + OP_MUL + expression)<=>[](auto &$) { return $[0] * $[2]; }
35 | (expression + OP_DIV + expression)<=>[](auto &$) { return $[0] / $[2]; }
36 | (expression + OP_ADD + expression)<=>[](auto &$) { return $[0] + $[2]; }
37 | (expression + OP_SUB + expression)<=>[](auto &$) { return $[0] - $[2]; }
38 ;
39
41 = bf::PR<G>(expression)<=>[](auto &$)
42 {
43 return $[0];
44 }
45 ;
46
47int main(int argc, char const **argv)
48{
49 if(argc < 2)
50 {
51 std::cerr << "Usage: calculator expression" << std::endl;
52 return 1;
53 }
54
55 auto calculator = *bf::SLRParser<G>::Build(statement);
56
57 auto result = calculator.Parse(argv[1]);
58 if(!result)
59 {
60 std::cerr << result.error().message << std::endl;
61 return 1;
62 }
63
64 std::cout << *result << std::endl;
65}
bf::GrammarDefinition< double > G
Definition calculator.cpp:8
bf::DefineNonTerminal< G > expression
bf::DefineTerminal< G, R"(\*)"> OP_MUL(bf::Left)
bf::DefineTerminal< G, R"(\‍()"> PAR_OPEN;bf::DefineTerminal< G, R"(\‍))"> PAR_CLOSE
bf::DefineTerminal< G, R"(\+)"> OP_ADD(bf::Left)
bf::DefineNonTerminal< G > statement
bf::DefineTerminal< G, R"(\^)"> OP_EXP(bf::Right)
bf::DefineTerminal< G, R"(\d+(\.\d+)?)", double > NUMBER([](auto const &tok) { return std::stod(std::string(tok.raw));})
int main(int argc, char const **argv)
bf::DefineTerminal< G, R"(\/)"> OP_DIV(bf::Left)
bf::DefineTerminal< G, R"(\-)"> OP_SUB(bf::Left)
static std::expected< SLRParser, Error > Build(NonTerminal< G > &start)
Definition buffalo.h:1147
@ Left
Definition buffalo.h:196
@ Right
Definition buffalo.h:197
ProductionRule< G > PR
Definition buffalo.h:438