-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patheval.cpp
111 lines (97 loc) · 2.11 KB
/
eval.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
/*
* my_eval.cpp
*
* Created on: 01.09.2016
* Author: kruppa
*/
/*
* expr := summand (add_op summand)*
* summand := factor (mult_op factor)*
* factor := sign ( expr ) | sign number
* add_op := + | -
* mult_op := * | /
* sign := + | - | e
*/
#include <iostream>
#include <cstdlib>
#include "eval.h"
using std::cout;
using std::endl;
static eval_type parse_expr(const char * &expr);
static bool
consume(const char * &expr, const char c)
{
while (expr[0] == ' ')
expr++;
bool match = (expr[0] == c);
expr += match ? 1 : 0;
return match;
}
static bool
consume_or_die(const char * &expr, const char c)
{
if (!consume(expr, c)) {
cout << "Error: got character " << expr[0] << ", expected " << c << endl;
exit(EXIT_FAILURE);
}
return true;
}
static int
parse_sign(const char * &expr)
{
if (consume(expr, '-'))
return -1;
consume(expr, '+');
return 1;
}
static eval_type
parse_factor(const char * &expr)
{
eval_type result;
const int sign = parse_sign(expr);
if (consume(expr, '(')) {
result = parse_expr(expr);
consume_or_die(expr, ')');
} else {
char *end_expr;
result = strtoul(expr, &end_expr, 0);
expr = end_expr;
}
return sign*result;
}
static eval_type
parse_summand(const char * &expr)
{
eval_type result = parse_factor(expr);
while(1) {
if (consume(expr, '*')) {
result *= parse_factor(expr);
} else if (consume(expr, '/')) {
result /= parse_factor(expr);
} else
break;
}
return result;
}
static eval_type
parse_expr(const char * &expr)
{
eval_type result = parse_summand(expr);
while(1) {
if (consume(expr, '+')) {
result += parse_summand(expr);
} else if (consume(expr, '-')) {
result -= parse_summand(expr);
} else
break;
}
return result;
}
eval_type
eval(const char * expr, const char **endp)
{
eval_type result = parse_expr(expr);
if (endp != NULL)
*endp = expr;
return result;
}