-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathmain.cpp
126 lines (112 loc) · 2.76 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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
#include <iostream>
#include "lexer.h"
#include "parser.h"
/*
Simple calculator
This program implements a basic expression calculator.
Input from cin; output to cout.
The grammar for input is:
Calculation:
Statement
Calculation Statement
Help
Print
Quit
Statement:
Declaration
Assignment
Expression
Declaration:
"let" Name "=" Expression
"const" Name "=" Expression
Assignment:
Name "=" Expression
Help:
"h"
Print:
";"
Quit:
"q"
Expression:
Term
Expression "+" Term
Expression "-" Term
Term:
Primary
Term "*" Primary
Term "/" Primary
Term "%" Primary
Primary:
Number
Name
Function
"(" Expression ")"
"+" Primary
"-" Primary
Number:
floating-point-literal
Function:
Name "(" Expression ")"
Name "(" Expression "," Expression ")"
Name:
identifier
Input comes from cin through the Token_stream called ts.
*/
using namespace std;
const string prompt = "> "; // prompt user input
const string result = "= "; // used to indicate that what follows is a result
Token_stream ts(cin);
Parser parser(ts);
void calculate();
void clean_up_mess();
void show_help();
int main() {
cout << "Simple calculator.\nEnter 'h' to show help.\n";
calculate();
return 0;
}
// expression calculation loop
void calculate() {
while (cin) {
try {
cout << prompt;
Token t = ts.get();
while (t.kind == print)
t = ts.get();
if (t.kind == help)
show_help();
else if (t.kind == quit)
break;
else {
ts.putback(t);
cout << result << parser.statement() << endl;
}
}
catch (exception& e) {
cerr << e.what() << endl;
clean_up_mess();
}
}
}
void clean_up_mess() {
ts.ignore(print);
}
void show_help() {
cout << "Enter expressions of floating-point numbers, terminating with ';'.\n"
"Available operators:\n"
" +, -, *, /, %, ()\n"
"Available functions:\n"
" sin(x), cos(x), tan(x), exp(x), log(x), sqrt(x), fabs(x), pow(x, y)\n"
"Variable declaration:\n"
" let name = expression;\n"
"Constant declaration:\n"
" const name = expression;\n"
"Assignment:\n"
" name = expression;\n"
"Predefined constants:\n"
" pi, e\n"
"Show help:\n"
" h\n"
"Quit:\n"
" q\n";
}