main -> relish

This commit is contained in:
Ava Apples Affine 2023-04-17 20:24:50 -07:00
parent 014be6ece3
commit db55c54dd3
Signed by: affine
GPG key ID: 3A4645B8CF806069

201
src/bin/relish.rs Normal file
View file

@ -0,0 +1,201 @@
/* relish: versatile lisp shell
* Copyright (C) 2021 Aidan Hahn
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use relish::ast::{eval, lex, Ctr, Seg, SymTable, run, load_defaults, load_environment};
use relish::stdlib::{dynamic_stdlib, static_stdlib};
use relish::aux::ShellState;
use std::cell::RefCell;
use std::rc::Rc;
use std::borrow::Cow;
use std::env;
use nix::unistd;
use nu_ansi_term::{Color, Style};
use dirs::home_dir;
use reedline::{
FileBackedHistory, DefaultHinter, DefaultValidator, Reedline, Signal,
Prompt, PromptEditMode, PromptHistorySearch, PromptHistorySearchStatus,
};
#[derive(Clone)]
pub struct CustomPrompt(String, String, String);
impl Prompt for CustomPrompt {
fn render_prompt_left(&self) -> Cow<str> {
{
Cow::Owned(self.0.to_owned())
}
}
fn render_prompt_right(&self) -> Cow<str> {
{
Cow::Owned(self.1.to_owned())
}
}
fn render_prompt_indicator(&self, _edit_mode: PromptEditMode) -> Cow<str> {
Cow::Owned(self.2.to_owned())
}
fn render_prompt_multiline_indicator(&self) -> Cow<str> {
Cow::Borrowed("++++")
}
fn render_prompt_history_search_indicator(
&self,
history_search: PromptHistorySearch,
) -> Cow<str> {
let prefix = match history_search.status {
PromptHistorySearchStatus::Passing => "",
PromptHistorySearchStatus::Failing => "failing ",
};
Cow::Owned(format!(
"({}reverse-search: {}) ",
prefix, history_search.term
))
}
}
fn main() {
const HIST_FILE: &str = "/.relish_hist";
const CONFIG_FILE_DEFAULT: &str = "/.relishrc";
// default config file dirs
let home_dir = home_dir().unwrap().to_str().unwrap().to_owned();
let hist_file_name = home_dir.clone() + HIST_FILE;
let cfg_file_name = home_dir + CONFIG_FILE_DEFAULT;
let shell_state_bindings = Rc::new(RefCell::from(ShellState {
parent_pid: unistd::Pid::from_raw(0),
parent_pgid: unistd::Pid::from_raw(0),
children: vec![],
last_exit_code: 0,
}));
// setup symtable
let mut syms = SymTable::new();
load_defaults(&mut syms);
load_environment(&mut syms);
static_stdlib(&mut syms).unwrap_or_else(|err: String| eprintln!("{}", err));
// reload this later with the state bindings
dynamic_stdlib(&mut syms, None).unwrap_or_else(|err: String| eprintln!("{}", err));
// if there are args those are scripts, run them and exit
if env::args().count() > 1 {
let mut iter = env::args();
iter.next();
for i in iter {
run(i, &mut syms).unwrap();
}
return
}
// this is a user shell. attempt to load configuration
{
// scope the below borrow of syms
let cfg_file = env::var("RELISH_CFG_FILE").unwrap_or(cfg_file_name);
run(cfg_file.clone(), &mut syms)
.unwrap_or_else(|err: String| eprintln!("failed to load script {}\n{}", cfg_file, err));
}
dynamic_stdlib(&mut syms, Some(shell_state_bindings)).unwrap_or_else(|err: String| eprintln!("{}", err));
// setup readline
let mut rl = Reedline::create();
let maybe_hist: Box<FileBackedHistory>;
if !hist_file_name.is_empty() {
maybe_hist = Box::new(FileBackedHistory::with_file(5000, hist_file_name.into())
.expect("error reading history!"));
rl = rl.with_history(maybe_hist);
}
rl = rl.with_hinter(Box::new(
DefaultHinter::default()
.with_style(Style::new().italic().fg(Color::LightGray)),
)).with_validator(Box::new(DefaultValidator));
// repl :)
loop {
let readline_prompt = make_prompt(&mut syms);
let user_doc = rl.read_line(&readline_prompt).unwrap();
match user_doc {
Signal::Success(line) => {
println!(""); // add a new line before output gets printed
let l = line.as_str().to_owned();
match lex(&l) {
Ok(a) => match eval(&a, &mut syms) {
Ok(a) => println!("{}", a),
Err(s) => println!("{}", s),
},
Err(s) => println!("{}", s),
}
},
Signal::CtrlD => {
println!("EOF!");
return
},
Signal::CtrlC => {
println!("Interrupted!");
},
}
}
}
fn make_prompt(syms: &mut SymTable) -> CustomPrompt {
let l_ctr = *syms
.call_symbol(&"CFG_RELISH_L_PROMPT".to_string(), &Seg::new(), true)
.unwrap_or_else(|err: String| {
eprintln!("{}", err);
Box::new(Ctr::String("<prompt broken!>".to_string()))
});
let r_ctr = *syms
.call_symbol(&"CFG_RELISH_R_PROMPT".to_string(), &Seg::new(), true)
.unwrap_or_else(|err: String| {
eprintln!("{}", err);
Box::new(Ctr::String("<prompt broken!>".to_string()))
});
let d_ctr = *syms
.call_symbol(&"CFG_RELISH_PROMPT_DELIMITER".to_string(), &Seg::new(), true)
.unwrap_or_else(|err: String| {
eprintln!("{}", err);
Box::new(Ctr::String("<prompt broken!>".to_string()))
});
let l_str: String;
let r_str: String;
let d_str: String;
if let Ctr::String(s) = l_ctr {
l_str = s;
} else {
l_str = l_ctr.to_string();
}
if let Ctr::String(s) = r_ctr {
r_str = s;
} else {
r_str = r_ctr.to_string();
}
if let Ctr::String(s) = d_ctr {
d_str = s;
} else {
d_str = d_ctr.to_string();
}
CustomPrompt(l_str, r_str, d_str)
}