Skip to content

Commit

Permalink
Add simple REPL functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
NikolaJelic committed Oct 6, 2023
1 parent 300c112 commit 00fd962
Show file tree
Hide file tree
Showing 3 changed files with 72 additions and 0 deletions.
1 change: 1 addition & 0 deletions examples/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
add_subdirectory(quickstart)
add_subdirectory(repl)
12 changes: 12 additions & 0 deletions examples/repl/CMakeLists.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
project(kalcy-repl)

add_executable(${PROJECT_NAME})

target_link_libraries(${PROJECT_NAME} PRIVATE
kalcy::kalcy
kalcy::kalcy-compile-options
)

target_sources(${PROJECT_NAME} PRIVATE
repl.cpp
)
59 changes: 59 additions & 0 deletions examples/repl/repl.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
#include <kalcy/kalcy.hpp>
#include <cassert>
#include <format>
#include <iomanip>
#include <iostream>
#include <sstream>

namespace {
struct Repl {
const std::string_view EXIT_TOKEN{"exit"};
bool verbose{}; // toggled on with '-v' and off with '-q'
bool is_running{true};

auto start() -> bool {
while (is_running) {
std::string text{};
std::cout << std::format("[{}] > ", verbose ? "verbose" : "quiet");
std::getline(std::cin, text);
// run kalcy on input expression
if (!run(text)) { return EXIT_FAILURE; }
}
// print epilogue
std::cout << std::format("\n^^ kalcy v{}\n", kalcy::version_v);
}

auto run(std::string_view const text) -> bool {
try {
// return false when the user enters the exit token
if (text == EXIT_TOKEN) {
is_running = false;
} else if (text == "-v") {
verbose = !verbose;
} else {
// parse text into an expression
auto expr = kalcy::Parser{}.parse(text);
assert(expr != nullptr);
// evaluate parsed expression
// a custom Env can be used and passed, if desired
std::cout << kalcy::evaluate(*expr) << "\n";
// print AST if verbose
if (verbose) { std::cout << std::format("expression\t: {}\nAST\t\t: {}\n", text, kalcy::to_string(*expr)); }
}
return true;
} catch (kalcy::Error const& err) {
// print error
std::cerr << err.what() << "\n";
// highlight error location under text
std::cerr << " | " << text << "\n | " << err.build_highlight() << "\n";
return false;
}
}
};
} // namespace

auto main(int argc, char** argv) -> int {

Repl repl{};
repl.start();
}

0 comments on commit 00fd962

Please sign in to comment.