xo-reader: + exprrepl example

This commit is contained in:
Roland Conybeare 2025-07-04 10:11:34 -05:00
commit cc02c0053d
4 changed files with 74 additions and 1 deletions

View file

@ -28,7 +28,7 @@ $ cmake -B .build0 -S xo-cmake -DCMAKE_INSTALL_PREFIX=${PREFIX}
$ cmake --build .build0
$ cmake --install .build0
# phase 2
$ cmake -B .build -S . -DCMAKE_INSTALL_PREFIX=${PREFIX}
$ cmake -B .build -S . -DCMAKE_INSTALL_PREFIX=${PREFIX} -DXO_ENABLE_EXAMPLES=1
$ cmake --build .build
$ cmake --install .build
```

View file

@ -0,0 +1 @@
add_subdirectory(exprrepl)

View file

@ -0,0 +1,11 @@
# xo-reader/example/exprrepl/CMakeLists.txt
set(SELF_EXE xo_expression_repl)
set(SELF_SRCS exprrepl.cpp)
if (XO_ENABLE_EXAMPLES)
xo_add_executable(${SELF_EXE} ${SELF_SRCS})
xo_dependency(${SELF_EXE} xo_reader)
endif()
# end CMakeLists.txt

View file

@ -0,0 +1,61 @@
/** @file exprrepl.cpp **/
#include "xo/reader/reader.hpp"
#include <iostream>
#include <unistd.h> // for isatty
bool repl_getline(bool interactive, std::istream& in, std::ostream& out, std::string& input)
{
if (interactive) {
out << "> ";
std::flush(out);
}
bool retval = static_cast<bool>(std::getline(in, input));
if (retval) {
// want reader to see newline, it's syntax
input.push_back('\n');
}
return retval;
}
int
main() {
using namespace xo::scm;
using namespace std;
using span_type = xo::scm::span<const char>;
bool interactive = isatty(STDIN_FILENO);
reader rdr;
rdr.begin_interactive_session();
string input_str;
bool eof = false;
span_type input;
while (repl_getline(interactive, cin, cout, input_str)) {
input = span_type::from_string(input_str);
while (!input.empty()) {
auto [expr, consumed] = rdr.read_expr(input, eof);
if (expr) {
cout << expr << endl;
}
input = input.after_prefix(consumed);
}
}
auto [expr, _] = rdr.read_expr(input, true /*eof*/);
if (expr) {
cout << expr << endl;
}
}