Compare commits

..

No commits in common. "0282b26265155238e7ae7a4558082a7e8738145d" and "375cc7a88f006631bed35eedadabe6362d711aa1" have entirely different histories.

7 changed files with 138 additions and 122 deletions

View File

@ -4,6 +4,7 @@ pub mod session;
pub mod commands; pub mod commands;
pub mod history; pub mod history;
pub mod terminal; pub mod terminal;
pub mod ps;
pub mod rc; pub mod rc;
pub mod vm; pub mod vm;

24
src/ps.rs Normal file
View File

@ -0,0 +1,24 @@
pub const DEFAULT_PS: &str = concat!("pse-", env!("CARGO_PKG_VERSION"), " ");
pub trait PsMut {
fn get(&self) -> &str;
fn modify(&mut self, prompt: String);
}
impl PsMut for Ps {
#[inline]
fn get(&self) -> &str {
self.0.as_str()
}
#[inline]
fn modify(&mut self, prompt: String) {
self.0 = prompt
}
}
#[derive(Debug)]
pub struct Ps(String);
impl Ps {
pub const fn set(prompt: String) -> Self {
Self(prompt)
}
}

View File

@ -1,9 +1,9 @@
use mlua::Lua as Luau;
use std::{cell::RefCell, fs, rc::Rc}; use std::{cell::RefCell, fs, rc::Rc};
use core::fmt; use core::fmt;
use color_print::ceprintln;
use crate::{ use crate::{
history::History, rc::{self}, terminal::TermProcessor, vm::LuauVm history::History, ps::{self, Ps}, rc::{self}, terminal, vm::LuauVm
}; };
pub trait MapDisplay<T, E: fmt::Display> { pub trait MapDisplay<T, E: fmt::Display> {
@ -24,43 +24,28 @@ impl<T, E: fmt::Display> MapDisplay<T, E> for Result<T, E> {
} }
pub fn shell_error<E: fmt::Display>(err: E) { pub fn shell_error<E: fmt::Display>(err: E) {
color_print::ceprintln!("<bold,r>[!]:</> {err}") ceprintln!("<bold,r>[!]:</> {err}")
} }
pub fn shell_error_none<T, E: fmt::Display>(err: E) -> Option<T> { pub fn shell_error_none<T, E: fmt::Display>(err: E) -> Option<T> {
shell_error(err); shell_error(err);
None None
} }
#[derive(Debug, Clone)]
pub struct VmConfig {
pub sandbox: bool,
pub jit: bool,
}
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Config { pub struct Config {
pub norc: bool, pub norc: bool,
pub vm: VmConfig, pub nojit: bool,
pub nosandbox: bool
} }
pub struct Rt { pub struct LambdaShell {
pub ps: Rc<RefCell<String>>, history: History,
pub input: String, config: Config,
pub vm: Luau, ps: Ps,
} }
pub struct Pse { impl LambdaShell {
pub config: Config,
pub history: History,
pub rt: Rt
}
impl Pse {
const DEFAULT_PS: &str = concat!("pse-", env!("CARGO_PKG_VERSION"), "$ ");
pub fn create(config: Config) -> Self { pub fn create(config: Config) -> Self {
Self { Self {
rt: Rt { ps: Ps::set(ps::DEFAULT_PS.to_owned()),
ps: Rc::new(RefCell::new(Self::DEFAULT_PS.to_owned())),
input: String::new(),
vm: Luau::new(),
},
history: History::init(), history: History::init(),
config, config,
} }
@ -71,7 +56,14 @@ impl Pse {
if let Some(conf_file) = rc::config_file() { if let Some(conf_file) = rc::config_file() {
fs::read_to_string(conf_file).map_or_display(|luau_conf| self.vm_exec(luau_conf)); fs::read_to_string(conf_file).map_or_display(|luau_conf| self.vm_exec(luau_conf));
} }
}; }
self.term_input_processor().map_or_display(|()| self.history.write_to_file_fallible()) terminal::Processor::init()
.input_processor(&mut self.history)
.map_or_display(|()| self.history.write_to_file_fallible());
}
pub fn vm_exec(&self, source: String) {
let p = Rc::new(RefCell::new(&self.ps));
LuauVm::new(Rc::clone(p)).exec(source);
} }
} }

View File

@ -1,8 +1,8 @@
use crossterm::{cursor, event::{self, Event, KeyCode, KeyEvent, KeyModifiers}, execute, terminal}; use crossterm::{event::{self, Event, KeyCode, KeyEvent, KeyModifiers}, terminal};
use std::io::{self, Write}; use std::io::{self, Write};
use thiserror::Error; use thiserror::Error;
use crate::{commands::Command, session::{self, Pse}}; use crate::{commands::Command, history::History, session};
#[derive(Debug, Error)] #[derive(Debug, Error)]
pub enum InputHandleError { pub enum InputHandleError {
@ -26,12 +26,10 @@ type InputResult<T> = Result<T, InputHandleError>;
trait SpecificKeybinds { trait SpecificKeybinds {
const TERM_ID_1: &str; const TERM_ID_1: &str;
fn key_ctrl(&mut self, input_key: KeyEvent, keycode: KeyCode) -> InputResult<()>; fn key_ctrl(&mut self, input_key: KeyEvent, keycode: KeyCode) -> InputResult<()>;
fn key_enter(&mut self) -> InputResult<()>; fn key_enter(&mut self, history: &mut History) -> InputResult<()>;
fn key_backspace(&mut self) -> InputResult<()>; fn key_backspace(&mut self) -> InputResult<()>;
fn key_arrow_right(&mut self) -> InputResult<()>;
fn key_arrow_left(&mut self) -> InputResult<()>;
} }
impl SpecificKeybinds for Pse { impl SpecificKeybinds for Processor {
const TERM_ID_1: &str = "exit"; const TERM_ID_1: &str = "exit";
fn key_ctrl(&mut self, input_key: KeyEvent, keycode: KeyCode) -> InputResult<()> { fn key_ctrl(&mut self, input_key: KeyEvent, keycode: KeyCode) -> InputResult<()> {
@ -41,85 +39,84 @@ impl SpecificKeybinds for Pse {
_ => Ok(()) _ => Ok(())
} }
} else { } else {
self.term_render(keycode.to_string()) self.render(Some(keycode.to_string()))
} }
} }
fn key_enter(&mut self) -> InputResult<()> { fn key_enter(&mut self, history: &mut History) -> InputResult<()> {
if self.rt.input == Self::TERM_ID_1 { return Err(InputHandleError::UserExit) }; if self.0 == Self::TERM_ID_1 { return Err(InputHandleError::UserExit) };
terminal::disable_raw_mode().map_err(InputHandleError::DisableRaw)?; terminal::disable_raw_mode().map_err(InputHandleError::DisableRaw)?;
Command::new(&self.rt.input).exec(&mut self.history); Command::new(&self.0).exec(history);
self.rt.input.clear(); self.0.clear();
Ok(()) Ok(())
} }
fn key_backspace(&mut self) -> InputResult<()> { fn key_backspace(&mut self) -> InputResult<()> {
if self.rt.input.pop().is_some() { match self.0.pop() {
execute!( Some(_) => self.render(None),
io::stdout(), None => {
cursor::MoveLeft(1),
terminal::Clear(terminal::ClearType::UntilNewLine)
).map_err(InputHandleError::Flush)
} else {
//the string is empty, do terminal beep //the string is empty, do terminal beep
Ok(()) Ok(())
},
}
} }
} }
fn key_arrow_right(&mut self) -> InputResult<()> { pub struct Processor(String);
execute!(io::stdout(), cursor::MoveRight(1)).map_err(InputHandleError::Flush) impl Processor {
pub const fn init() -> Self {
Self(String::new())
} }
fn key_arrow_left(&mut self) -> InputResult<()> { pub fn render(&mut self, def: Option<String>) -> InputResult<()> {
execute!(io::stdout(), cursor::MoveLeft(1)).map_err(InputHandleError::Flush) match def {
} Some(def_string) => {
} self.0.push_str(&def_string);
pub trait TermProcessor {
fn term_render(&mut self, def_string: String) -> InputResult<()>;
fn term_input_handler(&mut self, input_key: KeyEvent) -> Option<()>;
fn term_input_mainthread(&mut self) -> io::Result<()>;
fn term_input_processor(&mut self) -> io::Result<()>;
}
impl TermProcessor for Pse {
fn term_render(&mut self, def_string: String) -> InputResult<()> {
self.rt.input.push_str(&def_string);
write!(io::stdout(), "{def_string}").map_err(InputHandleError::Write)?; write!(io::stdout(), "{def_string}").map_err(InputHandleError::Write)?;
},
None => {
write!(io::stdout(), "{}", self.0).map_err(InputHandleError::Write)?
}
};
io::stdout().flush().map_err(InputHandleError::Flush) io::stdout().flush().map_err(InputHandleError::Flush)
} }
fn term_input_handler(&mut self, input_key: KeyEvent) -> Option<()> { pub fn input_handler(&mut self, input_key: KeyEvent, history: &mut History) -> Option<()> {
let input_handle = match input_key.code { let input_handle = match input_key.code {
KeyCode::Enter => self.key_enter(), KeyCode::Enter => self.key_enter(history),
KeyCode::Backspace => self.key_backspace(), KeyCode::Backspace => self.key_backspace(),
KeyCode::Tab => todo!(), KeyCode::Tab => todo!(),
KeyCode::Right => self.key_arrow_right(), KeyCode::Right => todo!(),
KeyCode::Left => self.key_arrow_left(), KeyCode::Left => todo!(),
KeyCode::Up => todo!(), KeyCode::Up => todo!(),
KeyCode::Down => todo!(), KeyCode::Down => todo!(),
keycode => self.key_ctrl(input_key, keycode) keycode => self.key_ctrl(input_key, keycode)
}; };
input_handle.map_or_else(|inp_err| match inp_err { input_handle.map_or_else(|inp_err| match inp_err {
InputHandleError::UserExit => None, InputHandleError::UserExit => None,
InputHandleError::Sigterm => self.term_render("^C".to_owned()).ok(), InputHandleError::Sigterm => self.render(Some("^C".to_owned())).ok(),
input_err => session::shell_error_none(input_err) InputHandleError::Write(e) => session::shell_error_none(e),
InputHandleError::Flush(e) => session::shell_error_none(e),
InputHandleError::Key(e) => session::shell_error_none(e),
InputHandleError::DisableRaw(e) => session::shell_error_none(e),
InputHandleError::EnableRaw(e) => session::shell_error_none(e)
}, Some) }, Some)
} }
fn term_input_mainthread(&mut self) -> io::Result<()> { fn input_mainthread(&mut self, history: &mut History) -> io::Result<()> {
execute!(io::stdout(), event::EnableBracketedPaste)?; crossterm::execute!(io::stdout(), event::EnableBracketedPaste)?;
loop { loop {
terminal::enable_raw_mode()?; terminal::enable_raw_mode()?;
if let Event::Key(event) = event::read()? { if let Event::Key(event) = event::read()? {
if self.term_input_handler(event).is_none() { break Ok(()) } if self.input_handler(event, history).is_none() { break Ok(()) }
} }
} }
} }
fn term_input_processor(&mut self) -> io::Result<()> { pub fn input_processor(&mut self, history: &mut History) -> io::Result<()> {
self.term_input_mainthread()?; self.input_mainthread(history)?;
terminal::disable_raw_mode()?; terminal::disable_raw_mode()?;
execute!(io::stdout(), event::DisableBracketedPaste) crossterm::execute!(io::stdout(), event::DisableBracketedPaste)
} }
} }

View File

@ -1,10 +1,11 @@
use mlua::{Function, MultiValue, Result as lResult, Table, Value}; use mlua::{Function, Lua as Luau, MultiValue, Result as lResult, Table, Value};
use color_print::cformat; use color_print::{cformat, ceprintln};
use shell::ShellGlobal;
use terminal::TerminalGlobal; use terminal::TerminalGlobal;
use core::fmt; use core::fmt;
use std::{cell::RefCell, rc::Rc};
use shell::ShellGlobal;
use crate::session::{Pse, MapDisplay}; use crate::{ps::Ps, session::MapDisplay};
mod shell; mod shell;
mod terminal; mod terminal;
@ -17,27 +18,27 @@ impl<T, E: fmt::Display> LuauRuntimeErr<T> for Result<T, E> {
#[inline] #[inline]
fn map_or_luau_rt_err<R, F: FnOnce(T) -> Option<R>>(self, f: F) -> Option<R> { fn map_or_luau_rt_err<R, F: FnOnce(T) -> Option<R>>(self, f: F) -> Option<R> {
self.map_or_else(|luau_rt_err| { self.map_or_else(|luau_rt_err| {
color_print::ceprintln!("<bold>====</>\n<r><bold>[!]:</> {luau_rt_err}</>\n<bold>====</>"); ceprintln!("<bold>====</>\n<r><bold>[!]:</> {luau_rt_err}</>\n<bold>====</>");
None None
}, f) }, f)
} }
} }
trait VmGlobals { trait Globals {
const LIB_VERSION: &str; const LIB_VERSION: &str;
const CONV_ERROR: &str; const CONV_ERROR: &str;
const LIB_NAME: &str; const LIB_NAME: &str;
fn vm_glob_warn(&self, luau_globals: &Table) -> lResult<()>; fn glob_warn(&self, luau_globals: &Table) -> lResult<()>;
fn vm_glob_version(&self, luau_globals: &Table) -> lResult<()>; fn glob_version(&self, luau_globals: &Table) -> lResult<()>;
} }
impl VmGlobals for Pse { impl Globals for LuauVm {
const LIB_VERSION: &str = env!("CARGO_PKG_VERSION"); const LIB_VERSION: &str = env!("CARGO_PKG_VERSION");
const LIB_NAME: &str = env!("CARGO_PKG_NAME"); const LIB_NAME: &str = env!("CARGO_PKG_NAME");
const CONV_ERROR: &str = "<SHELL CONVERSION ERROR>"; const CONV_ERROR: &str = "<SHELL CONVERSION ERROR>";
fn vm_glob_warn(&self, luau_globals: &Table) -> lResult<()> { fn glob_warn(&self, luau_globals: &Table) -> lResult<()> {
let luau_print = luau_globals.get::<Function>("print")?; let luau_print = luau_globals.get::<Function>("print")?;
luau_globals.raw_set("warn", self.rt.vm.create_function(move |this, args: MultiValue| -> lResult<()> { luau_globals.raw_set("warn", self.vm.create_function(move |this, args: MultiValue| -> lResult<()> {
let luau_multi_values = args.into_iter() let luau_multi_values = args.into_iter()
.map(|value| cformat!("<bold,y>{}</>", value.to_string().unwrap_or(Self::CONV_ERROR.to_owned()))) .map(|value| cformat!("<bold,y>{}</>", value.to_string().unwrap_or(Self::CONV_ERROR.to_owned())))
.map(|arg_v| Value::String(this.create_string(arg_v).unwrap())) .map(|arg_v| Value::String(this.create_string(arg_v).unwrap()))
@ -47,31 +48,34 @@ impl VmGlobals for Pse {
})?) })?)
} }
fn vm_glob_version(&self, luau_globals: &Table) -> lResult<()> { fn glob_version(&self, luau_globals: &Table) -> lResult<()> {
let luau_info = luau_globals.get::<String>("_VERSION")?; let luau_info = luau_globals.get::<String>("_VERSION")?;
luau_globals.raw_set("_VERSION", format!("{luau_info}, {} {}", Self::LIB_NAME, Self::LIB_VERSION)) luau_globals.raw_set("_VERSION", format!("{luau_info}, {} {}", Self::LIB_NAME, Self::LIB_VERSION))
} }
} }
pub trait LuauVm { pub struct LuauVm {
fn vm_setglobs(&self) -> lResult<()>; vm: Luau,
fn vm_exec(&self, source: String); ps: Rc<RefCell<Ps>>
}
impl LuauVm {
pub(crate) fn new(ps: Rc<RefCell<Ps>>) -> Self {
Self { vm: Luau::new(), ps }
} }
impl LuauVm for Pse {
fn vm_setglobs(&self) -> lResult<()> {
let luau_globals = self.rt.vm.globals();
self.vm_glob_shell(&luau_globals)?;
self.vm_glob_terminal(&luau_globals)?;
self.vm_glob_warn(&luau_globals)?;
self.vm_glob_version(&luau_globals)?;
fn setglobs(&self) -> lResult<()> {
let luau_globals = self.vm.globals();
self.glob_shell(&luau_globals)?;
self.glob_terminal(&luau_globals)?;
self.glob_warn(&luau_globals)?;
self.glob_version(&luau_globals)?;
luau_globals.raw_set("getfenv", mlua::Nil)?; luau_globals.raw_set("getfenv", mlua::Nil)?;
luau_globals.raw_set("setfenv", mlua::Nil)?; luau_globals.raw_set("setfenv", mlua::Nil)?;
self.rt.vm.enable_jit(self.config.vm.jit); self.vm.sandbox(true)?;
self.rt.vm.sandbox(true) Ok(())
} }
fn vm_exec(&self, source: String) { pub fn exec(&self, source: String) {
self.vm_setglobs().map_or_display_none(|()| self.rt.vm.load(source).exec().map_or_luau_rt_err(Some)); self.setglobs().map_or_display_none(|()| self.vm.load(source).exec().map_or_luau_rt_err(Some));
} }
} }

View File

@ -2,11 +2,11 @@ use mlua::{Lua as Luau, MetaMethod, Result as lResult, Table, UserData, UserData
use std::{cell::RefCell, rc::Rc}; use std::{cell::RefCell, rc::Rc};
use whoami::fallible; use whoami::fallible;
use crate::session::Pse; use crate::{ps::{Ps, PsMut}, vm::LuauVm};
fn luau_sys_details(luau: &Luau) -> lResult<Table> {
const DEFAULT_HOSTNAME: &str = "hostname"; const DEFAULT_HOSTNAME: &str = "hostname";
fn luau_sys_details(luau: &Luau) -> lResult<Table> {
let system = luau.create_table()?; let system = luau.create_table()?;
system.raw_set("DESKTOP_ENV", whoami::desktop_env().to_string())?; system.raw_set("DESKTOP_ENV", whoami::desktop_env().to_string())?;
system.raw_set("DEVICENAME", whoami::devicename().to_string())?; system.raw_set("DEVICENAME", whoami::devicename().to_string())?;
@ -19,29 +19,27 @@ fn luau_sys_details(luau: &Luau) -> lResult<Table> {
Ok(system) Ok(system)
} }
struct Shell(Rc<RefCell<String>>); struct Shell(Rc<RefCell<Ps>>);
impl UserData for Shell { impl UserData for Shell {
fn add_fields<F: UserDataFields<Self>>(fields: &mut F) { fn add_fields<F: UserDataFields<Self>>(fields: &mut F) {
fields.add_field_method_get("PROMPT", |_, this| Ok(this.0.borrow().to_string())); fields.add_field_method_get("PROMPT", |_, this| Ok(this.0.borrow().get().to_owned()));
fields.add_field_method_get("SYSTEM", |luau, _| luau_sys_details(luau)); fields.add_field_method_get("SYSTEM", |luau, _| luau_sys_details(luau));
} }
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) { fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
methods.add_meta_method_mut(MetaMethod::NewIndex, |_, this, (t_index, t_value): (String, String)| -> lResult<()> { methods.add_meta_method_mut(MetaMethod::NewIndex, |_, this, (t_index, t_value): (String, String)| -> lResult<()> {
if t_index == "PROMPT" { if t_index == "PROMPT" { this.0.borrow_mut().modify(t_value); }
let mut prompt = this.0.borrow_mut();
*prompt = t_value;
}
Ok(()) Ok(())
}); });
} }
} }
pub trait ShellGlobal { pub trait ShellGlobal {
fn vm_glob_shell(&self, luau_globals: &Table) -> lResult<()>; fn glob_shell(&self, luau_globals: &Table) -> lResult<()>;
} }
impl ShellGlobal for Pse { impl ShellGlobal for LuauVm {
fn vm_glob_shell(&self, luau_globals: &Table) -> lResult<()> { fn glob_shell(&self, luau_globals: &Table) -> lResult<()> {
luau_globals.raw_set("SHELL", Shell(Rc::clone(&self.rt.ps))) luau_globals.raw_set("SHELL", Shell(Rc::clone(&self.ps)))?;
Ok(())
} }
} }

View File

@ -2,7 +2,7 @@ use mlua::{UserDataFields, Lua as Luau, Result as lResult, Table, UserData};
use const_format::str_split; use const_format::str_split;
use crossterm::style::Stylize; use crossterm::style::Stylize;
use crate::session::Pse; use crate::vm::LuauVm;
macro_rules! foreground_styles_luau { macro_rules! foreground_styles_luau {
($luau:expr, $style_table:expr, $($color:ident)+) => { ($luau:expr, $style_table:expr, $($color:ident)+) => {
@ -84,10 +84,10 @@ impl UserData for Terminal {
} }
pub trait TerminalGlobal { pub trait TerminalGlobal {
fn vm_glob_terminal(&self, luau_globals: &Table) -> lResult<()>; fn glob_terminal(&self, luau_globals: &Table) -> lResult<()>;
} }
impl TerminalGlobal for Pse { impl TerminalGlobal for LuauVm {
fn vm_glob_terminal(&self, luau_globals: &Table) -> lResult<()> { fn glob_terminal(&self, luau_globals: &Table) -> lResult<()> {
luau_globals.raw_set("TERMINAL", Terminal) luau_globals.raw_set("TERMINAL", Terminal)
} }
} }