big restructure, all around good changes

This commit is contained in:
rhpidfyre 2025-01-19 18:43:03 -05:00
parent 375cc7a88f
commit 4cda728b2e
7 changed files with 100 additions and 122 deletions

View File

@ -4,7 +4,6 @@ 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;

View File

@ -1,24 +0,0 @@
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, ps::{self, Ps}, rc::{self}, terminal, vm::LuauVm history::History, rc::{self}, terminal::TermProcessor, vm::LuauVm
}; };
pub trait MapDisplay<T, E: fmt::Display> { pub trait MapDisplay<T, E: fmt::Display> {
@ -24,28 +24,43 @@ 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) {
ceprintln!("<bold,r>[!]:</> {err}") color_print::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 nojit: bool, pub vm: VmConfig,
pub nosandbox: bool
} }
pub struct LambdaShell { pub struct Rt {
history: History, pub ps: Rc<RefCell<String>>,
config: Config, pub input: String,
ps: Ps, pub vm: Luau,
} }
impl LambdaShell { pub struct Pse {
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 {
ps: Ps::set(ps::DEFAULT_PS.to_owned()), rt: Rt {
ps: Rc::new(RefCell::new(Self::DEFAULT_PS.to_owned())),
input: String::new(),
vm: Luau::new(),
},
history: History::init(), history: History::init(),
config, config,
} }
@ -56,14 +71,7 @@ impl LambdaShell {
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));
} }
} };
terminal::Processor::init() self.term_input_processor().map_or_display(|()| self.history.write_to_file_fallible())
.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

@ -2,7 +2,7 @@ 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, history::History, session}; use crate::{commands::Command, session::{self, Pse}};
#[derive(Debug, Error)] #[derive(Debug, Error)]
pub enum InputHandleError { pub enum InputHandleError {
@ -26,10 +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, history: &mut History) -> InputResult<()>; fn key_enter(&mut self) -> InputResult<()>;
fn key_backspace(&mut self) -> InputResult<()>; fn key_backspace(&mut self) -> InputResult<()>;
} }
impl SpecificKeybinds for Processor { impl SpecificKeybinds for Pse {
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<()> {
@ -39,22 +39,22 @@ impl SpecificKeybinds for Processor {
_ => Ok(()) _ => Ok(())
} }
} else { } else {
self.render(Some(keycode.to_string())) self.term_render(Some(keycode.to_string()))
} }
} }
fn key_enter(&mut self, history: &mut History) -> InputResult<()> { fn key_enter(&mut self) -> InputResult<()> {
if self.0 == Self::TERM_ID_1 { return Err(InputHandleError::UserExit) }; if self.rt.input == 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.0).exec(history); Command::new(&self.rt.input).exec(&mut self.history);
self.0.clear(); self.rt.input.clear();
Ok(()) Ok(())
} }
fn key_backspace(&mut self) -> InputResult<()> { fn key_backspace(&mut self) -> InputResult<()> {
match self.0.pop() { match self.rt.input.pop() {
Some(_) => self.render(None), Some(_) => self.term_render(None),
None => { None => {
//the string is empty, do terminal beep //the string is empty, do terminal beep
Ok(()) Ok(())
@ -63,28 +63,29 @@ impl SpecificKeybinds for Processor {
} }
} }
pub struct Processor(String); pub trait TermProcessor {
impl Processor { fn term_render(&mut self, def: Option<String>) -> InputResult<()>;
pub const fn init() -> Self { fn term_input_handler(&mut self, input_key: KeyEvent) -> Option<()>;
Self(String::new()) fn term_input_mainthread(&mut self) -> io::Result<()>;
} fn term_input_processor(&mut self) -> io::Result<()>;
}
pub fn render(&mut self, def: Option<String>) -> InputResult<()> { impl TermProcessor for Pse {
fn term_render(&mut self, def: Option<String>) -> InputResult<()> {
match def { match def {
Some(def_string) => { Some(def_string) => {
self.0.push_str(&def_string); 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 => { None => {
write!(io::stdout(), "{}", self.0).map_err(InputHandleError::Write)? write!(io::stdout(), "{}", self.rt.input).map_err(InputHandleError::Write)?
} }
}; };
io::stdout().flush().map_err(InputHandleError::Flush) io::stdout().flush().map_err(InputHandleError::Flush)
} }
pub fn input_handler(&mut self, input_key: KeyEvent, history: &mut History) -> Option<()> { fn term_input_handler(&mut self, input_key: KeyEvent) -> Option<()> {
let input_handle = match input_key.code { let input_handle = match input_key.code {
KeyCode::Enter => self.key_enter(history), KeyCode::Enter => self.key_enter(),
KeyCode::Backspace => self.key_backspace(), KeyCode::Backspace => self.key_backspace(),
KeyCode::Tab => todo!(), KeyCode::Tab => todo!(),
KeyCode::Right => todo!(), KeyCode::Right => todo!(),
@ -94,28 +95,24 @@ impl Processor {
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.render(Some("^C".to_owned())).ok(), InputHandleError::Sigterm => self.term_render(Some("^C".to_owned())).ok(),
InputHandleError::Write(e) => session::shell_error_none(e), input_err => session::shell_error_none(input_err)
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 input_mainthread(&mut self, history: &mut History) -> io::Result<()> { fn term_input_mainthread(&mut self) -> io::Result<()> {
crossterm::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.input_handler(event, history).is_none() { break Ok(()) } if self.term_input_handler(event).is_none() { break Ok(()) }
} }
} }
} }
pub fn input_processor(&mut self, history: &mut History) -> io::Result<()> { fn term_input_processor(&mut self) -> io::Result<()> {
self.input_mainthread(history)?; self.term_input_mainthread()?;
terminal::disable_raw_mode()?; terminal::disable_raw_mode()?;
crossterm::execute!(io::stdout(), event::DisableBracketedPaste) crossterm::execute!(io::stdout(), event::DisableBracketedPaste)
} }

View File

@ -1,11 +1,10 @@
use mlua::{Function, Lua as Luau, MultiValue, Result as lResult, Table, Value}; use mlua::{Function, MultiValue, Result as lResult, Table, Value};
use color_print::{cformat, ceprintln}; use color_print::cformat;
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::{ps::Ps, session::MapDisplay}; use crate::session::{Pse, MapDisplay};
mod shell; mod shell;
mod terminal; mod terminal;
@ -18,27 +17,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| {
ceprintln!("<bold>====</>\n<r><bold>[!]:</> {luau_rt_err}</>\n<bold>====</>"); color_print::ceprintln!("<bold>====</>\n<r><bold>[!]:</> {luau_rt_err}</>\n<bold>====</>");
None None
}, f) }, f)
} }
} }
trait Globals { trait VmGlobals {
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 glob_warn(&self, luau_globals: &Table) -> lResult<()>; fn vm_glob_warn(&self, luau_globals: &Table) -> lResult<()>;
fn glob_version(&self, luau_globals: &Table) -> lResult<()>; fn vm_glob_version(&self, luau_globals: &Table) -> lResult<()>;
} }
impl Globals for LuauVm { impl VmGlobals for Pse {
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 glob_warn(&self, luau_globals: &Table) -> lResult<()> { fn vm_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.vm.create_function(move |this, args: MultiValue| -> lResult<()> { luau_globals.raw_set("warn", self.rt.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()))
@ -48,34 +47,31 @@ impl Globals for LuauVm {
})?) })?)
} }
fn glob_version(&self, luau_globals: &Table) -> lResult<()> { fn vm_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 struct LuauVm { pub trait LuauVm {
vm: Luau, fn vm_setglobs(&self) -> lResult<()>;
ps: Rc<RefCell<Ps>> fn vm_exec(&self, source: String);
} }
impl LuauVm { impl LuauVm for Pse {
pub(crate) fn new(ps: Rc<RefCell<Ps>>) -> Self { fn vm_setglobs(&self) -> lResult<()> {
Self { vm: Luau::new(), ps } 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.vm.sandbox(true)?; self.rt.vm.enable_jit(self.config.vm.jit);
Ok(()) self.rt.vm.sandbox(true)
} }
pub fn exec(&self, source: String) { fn vm_exec(&self, source: String) {
self.setglobs().map_or_display_none(|()| self.vm.load(source).exec().map_or_luau_rt_err(Some)); self.vm_setglobs().map_or_display_none(|()| self.rt.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::{ps::{Ps, PsMut}, vm::LuauVm}; use crate::session::Pse;
const DEFAULT_HOSTNAME: &str = "hostname";
fn luau_sys_details(luau: &Luau) -> lResult<Table> { fn luau_sys_details(luau: &Luau) -> lResult<Table> {
const DEFAULT_HOSTNAME: &str = "hostname";
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,27 +19,29 @@ fn luau_sys_details(luau: &Luau) -> lResult<Table> {
Ok(system) Ok(system)
} }
struct Shell(Rc<RefCell<Ps>>); struct Shell(Rc<RefCell<String>>);
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().get().to_owned())); fields.add_field_method_get("PROMPT", |_, this| Ok(this.0.borrow().to_string()));
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" { this.0.borrow_mut().modify(t_value); } if t_index == "PROMPT" {
let mut prompt = this.0.borrow_mut();
*prompt = t_value;
}
Ok(()) Ok(())
}); });
} }
} }
pub trait ShellGlobal { pub trait ShellGlobal {
fn glob_shell(&self, luau_globals: &Table) -> lResult<()>; fn vm_glob_shell(&self, luau_globals: &Table) -> lResult<()>;
} }
impl ShellGlobal for LuauVm { impl ShellGlobal for Pse {
fn glob_shell(&self, luau_globals: &Table) -> lResult<()> { fn vm_glob_shell(&self, luau_globals: &Table) -> lResult<()> {
luau_globals.raw_set("SHELL", Shell(Rc::clone(&self.ps)))?; luau_globals.raw_set("SHELL", Shell(Rc::clone(&self.rt.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::vm::LuauVm; use crate::session::Pse;
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 glob_terminal(&self, luau_globals: &Table) -> lResult<()>; fn vm_glob_terminal(&self, luau_globals: &Table) -> lResult<()>;
} }
impl TerminalGlobal for LuauVm { impl TerminalGlobal for Pse {
fn glob_terminal(&self, luau_globals: &Table) -> lResult<()> { fn vm_glob_terminal(&self, luau_globals: &Table) -> lResult<()> {
luau_globals.raw_set("TERMINAL", Terminal) luau_globals.raw_set("TERMINAL", Terminal)
} }
} }