Skip to content

Commit

Permalink
feat: save history on REPL
Browse files Browse the repository at this point in the history
  • Loading branch information
fcoury committed Jul 4, 2024
1 parent 8d5f3ab commit a5311f2
Show file tree
Hide file tree
Showing 3 changed files with 239 additions and 23 deletions.
188 changes: 188 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,6 @@ edition = "2021"
anyhow = "1.0.86"
clap = { version = "4.5.8", features = ["derive"] }
indexmap = "2.2.6"
rustyline = "14.0.0"
simple-home-dir = "0.3.5"
thiserror = "1.0.61"
72 changes: 49 additions & 23 deletions src/repl.rs
Original file line number Diff line number Diff line change
@@ -1,34 +1,60 @@
use std::io::{self, Write};
use rustyline::{error::ReadlineError, history::FileHistory, CompletionType, Config, Editor};
use simple_home_dir::home_dir;

use crate::{interpreter::Interpreter, lexer::Lexer, parser::Parser};

#[allow(dead_code)]
pub fn repl() -> io::Result<()> {
pub fn repl() -> anyhow::Result<()> {
let config = Config::builder()
.history_ignore_space(true)
.completion_type(CompletionType::List)
.build();
let history_file = format!("{}/.husk_history", home_dir().unwrap().to_str().unwrap());
let mut rl: Editor<(), FileHistory> = Editor::with_config(config)?;
let mut interpreter = Interpreter::new();
rl.load_history(&history_file).unwrap_or_default();

loop {
print!("> ");
io::stdout().flush()?;

let mut input = String::new();
io::stdin().read_line(&mut input)?;

let input = input.trim();
if input == "exit" {
break;
}

let mut lexer = Lexer::new(input.to_string());
let tokens = lexer.lex_all();

let mut parser = Parser::new(tokens);
match parser.parse() {
Ok(ast) => match interpreter.interpret(&ast) {
Ok(val) => println!("{}", val),
Err(e) => println!("{}", e.pretty_print(input)),
},
Err(e) => println!("{}", e.pretty_print(input)),
let readline = rl.readline("> ");
match readline {
Ok(line) => {
if line == "exit" {
break;
}

if line == "clear" {
// clear screen
println!("\x1B[2J\x1B[1;1H");
continue;
}

rl.add_history_entry(line.as_str())?;
let mut lexer = Lexer::new(&line);
let tokens = lexer.lex_all();

let mut parser = Parser::new(tokens);
match parser.parse() {
Ok(ast) => match interpreter.interpret(&ast) {
Ok(val) => println!("{}", val),
Err(e) => println!("{}", e.pretty_print(line)),
},
Err(e) => println!("{}", e.pretty_print(line)),
}
}
Err(ReadlineError::Interrupted) => {
println!("CTRL-C");
break;
}
Err(ReadlineError::Eof) => {
println!("CTRL-D");
break;
}
Err(err) => {
println!("Error: {:?}", err);
break;
}
}
rl.append_history(&history_file).unwrap();
}

Ok(())
Expand Down

0 comments on commit a5311f2

Please sign in to comment.