@@ -10,51 +10,58 @@ struct Repl {
10
10
const std::string_view EXIT_TOKEN{" exit" };
11
11
bool verbose{}; // toggled on with '-v' and off with '-q'
12
12
bool is_running{true };
13
+ kalcy::Parser parser{};
13
14
14
15
auto print_help () -> void {
15
16
std::cout << " Usage: [OPTION] | [EXPRESSION]\n " ;
16
17
std::cout << " \n Description:\n\n " ;
17
- std::cout << std::format (" {:<15} {}\n " , " -h, -- help" , " Display this help message, providing information about available options." );
18
+ std::cout << std::format (" {:<15} {}\n " , " -h, -help" , " Display this help message, providing information about available options." );
18
19
std::cout << std::format (" {:<15} {}\n " , " -v" , " Toggle verbose mode to control the level of detail in the output." );
19
- std::cout << std::format (" {:<15} {}\n " , " exit" , " Terminate the REPL input loop." );
20
+ std::cout << std::format (" {:<15} {}\n\n " , " exit" , " Terminate the REPL input loop." );
20
21
}
21
22
22
23
auto start () -> bool {
23
24
while (is_running) {
24
- std::string text {};
25
+ auto text = std::string{};
25
26
std::cout << std::format (" {} > " , verbose ? " [verbose]" : " " );
26
27
std::getline (std::cin, text);
27
28
// run kalcy on input expression
28
29
if (!text.empty ()) {
29
- if (!run (text)) { return EXIT_FAILURE; }
30
+ if (!run (text)) { return EXIT_FAILURE; }
30
31
} else {
31
32
print_help ();
32
33
}
33
34
}
34
35
// print epilogue
35
36
std::cout << std::format (" \n ^^ kalcy v{}\n " , kalcy::version_v);
36
- return EXIT_SUCCESS ;
37
+ return true ;
37
38
}
38
39
39
40
auto run (std::string_view const text) -> bool {
40
41
try {
41
42
if (text == " exit" ) {
42
43
is_running = false ;
43
- } else if (text == " -v" ) {
44
- verbose = !verbose;
45
- } else if (text == " -h" || text == " -help" ) {
44
+ return true ;
45
+ }
46
+
47
+ if (text == " -h" || text == " -help" ) {
46
48
print_help ();
49
+ return true ;
50
+ }
51
+
52
+ if (text == " -v" ) {
53
+ verbose = !verbose;
47
54
} else {
48
55
// parse text into an expression
49
- auto expr = kalcy::Parser{} .parse (text);
56
+ auto expr = parser .parse (text);
50
57
assert (expr != nullptr );
51
58
// evaluate parsed expression
52
59
// a custom Env can be used and passed, if desired
53
60
std::cout << kalcy::evaluate (*expr) << " \n " ;
54
61
// print AST if verbose
55
62
if (verbose) { std::cout << std::format (" expression\t : {}\n AST\t\t : {}\n " , text, kalcy::to_string (*expr)); }
63
+ return true ;
56
64
}
57
- return true ;
58
65
} catch (kalcy::Error const & err) {
59
66
// print error
60
67
std::cerr << err.what () << " \n " ;
@@ -69,5 +76,7 @@ struct Repl {
69
76
auto main () -> int {
70
77
71
78
Repl repl{};
72
- repl.start ();
79
+ try {
80
+ repl.start ();
81
+ } catch (std::exception const & e) { std::cerr << e.what () << " \n " ; }
73
82
}
0 commit comments