-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.cpp
111 lines (102 loc) · 2.79 KB
/
main.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
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
//#include "widget.h"
//#include <QApplication>
// int
// main(int argc, char* argv[])
//{
// QApplication a(argc, argv);
// Widget w;
// w.show();
// return a.exec();
//}
#include "peg_parser/generator.h"
#include "qglobal.h"
#include <cstdlib>
#include <iostream>
#include <string>
int
main(int argc, char* argv[])
{
Q_UNUSED(argc);
Q_UNUSED(argv);
std::vector<std::pair<std::string, float>> exprs = {
{ "1", 1. },
{ "1.1", 1.1 },
{ "1.01", 1.01 },
{ "+1.001", 1.001 },
{ "-1.001", -1.001 },
{ "1+1", 2 },
{ "1-1", 0 },
{ "1+2+3", 6 },
{ "1-1+2", 2 },
{ "(1)", 1 },
{ "(1+1)", 2 },
{ "(2-1)", 1 },
{ "-(2-1)", -1 },
{ "-(1)", -1 },
{ "-(-1)", 1 },
{ "-(1)-(-1)", 0 },
{ "-(1+2)-(2+2)", -7 },
{ "-(1+2)+(2+2)", 1 },
{ "1*1", 1 },
{ "1*2", 2 },
{ "1*(1+1)", 2 },
{ "(1+1)*(1+1)", 4 },
{ "-1*1", -1 },
{ "-(1+1)*(1+1)", -4 },
{ "-1*(-1)", 1 },
{ "(-1)*(-1)", 1 },
{ "(1)+(2)", 3 },
{ "(1)*(2)*(3)", 6 },
{ "(1+1)*(-1)", -2 },
{ "(1+2)*(1-2)*(2-1)-1*(-1)", -2 },
{ "1/2", 0.5 },
{ "1/(1+1)", 0.5 },
{ "(1-4*2)/4", -1.75 },
{ "((1))", 1 },
{ "(-(1))", -1 },
{ "(((-1)))", -1 },
{ "((-1)+1)", 0 },
{ "(7+1.44)*3-1.44*7+2*(3-1.4)", 18.44 },
{ "1(1+1)", 2 },
{ "(1+1)(1+1)", 4 },
{ "-1*1", -1 },
{ "-(1+1)(1+1)", -4 },
{ "-1(-1)", 1 },
{ "(-1)(-1)", 1 },
{ "(1)+(2)", 3 },
{ "(1)*(2)(3)", 6 },
{ "(1+1)(-1)", -2 },
{ "(1+2)*(1-2)(2-1)-1(-1)", -2 },
{ "(7+1.44)3-1.44*7+2(3-1.4)", 18.44 },
{ "1+(1+1)1.44*(7-1)", 18.28 }
};
peg_parser::ParserGenerator<float> g;
// g.setSeparator(g["Whitespace"] << "[\t \n]");
g.setStart(g["Expression"]);
for (const auto& expr : exprs) {
std::cout << "_____________________________________________" << std::endl;
try {
std::cout << "expr = " << expr.first << std::endl;
auto result = g.run(expr.first); // -> 5
std::cout << expr.first << " = " << result << std::endl;
if (std::fabs(result - expr.second) > 1.e-5) {
std::cout << "expected: " << expr.second << std::endl;
std::cout << " got: " << result << std::endl;
std::cout << "std::fabs(result - expr.second) = "
<< std::fabs(result - expr.second) << std::endl;
}
Q_ASSERT(std::fabs(result - expr.second) < 1.e-5);
} catch (peg_parser::SyntaxError& error) {
auto syntax = error.syntax;
std::cout << expr.first << std::endl;
std::cout << std::string(syntax->begin, ' ');
std::cout << std::string(syntax->length(), '~');
std::cout << "^\n";
std::cout << " "
<< "Syntax error while parsing " << syntax->rule->name
<< std::endl;
return EXIT_FAILURE;
}
}
return EXIT_SUCCESS;
}