2 Commits

Author SHA1 Message Date
4cda728b2e big restructure, all around good changes 2025-01-19 18:43:03 -05:00
375cc7a88f termianl rendering text, backspace needs fix 2025-01-19 02:54:00 -05:00
11 changed files with 238 additions and 259 deletions

112
Cargo.lock generated
View File

@ -10,9 +10,9 @@ checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
[[package]] [[package]]
name = "bitflags" name = "bitflags"
version = "2.7.0" version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1be3f42a67d6d345ecd59f675f3f012d6974981560836e938c22b424b85ce1be" checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36"
[[package]] [[package]]
name = "bstr" name = "bstr"
@ -32,9 +32,9 @@ checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.2.9" version = "1.2.10"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c8293772165d9345bdaaa39b45b2109591e63fe5e6fbc23c6ff930a048aa310b" checksum = "13208fcbb66eaeffe09b99fffbe1af420f00a7b35aa99ad683dfc1aa76145229"
dependencies = [ dependencies = [
"shlex", "shlex",
] ]
@ -45,12 +45,6 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "cfg_aliases"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
[[package]] [[package]]
name = "color-print" name = "color-print"
version = "0.3.7" version = "0.3.7"
@ -118,16 +112,6 @@ dependencies = [
"winapi", "winapi",
] ]
[[package]]
name = "ctrlc"
version = "3.4.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "90eeab0aa92f3f9b4e87f258c72b139c207d251f9cbc1080a0086b86a8870dd3"
dependencies = [
"nix",
"windows-sys 0.59.0",
]
[[package]] [[package]]
name = "either" name = "either"
version = "1.13.0" version = "1.13.0"
@ -144,31 +128,6 @@ dependencies = [
"windows-sys 0.59.0", "windows-sys 0.59.0",
] ]
[[package]]
name = "futures-core"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "05f29059c0c2090612e8d742178b0580d2dc940c837851ad723096f87af6663e"
[[package]]
name = "futures-task"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f90f7dce0722e95104fcb095585910c0977252f286e354b5e3bd38902cd99988"
[[package]]
name = "futures-util"
version = "0.3.31"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9fa08315bb612088cc391249efdc3bc77536f16c91f6cf495e6fbe85b20a4a81"
dependencies = [
"futures-core",
"futures-task",
"pin-project-lite",
"pin-utils",
"slab",
]
[[package]] [[package]]
name = "home" name = "home"
version = "0.5.11" version = "0.5.11"
@ -209,21 +168,6 @@ version = "0.2.169"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a" checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a"
[[package]]
name = "liblambdashell"
version = "0.1.0"
dependencies = [
"color-print",
"const_format",
"crossterm",
"ctrlc",
"home",
"mlua",
"thiserror",
"uzers",
"whoami",
]
[[package]] [[package]]
name = "libloading" name = "libloading"
version = "0.8.6" version = "0.8.6"
@ -234,6 +178,20 @@ dependencies = [
"windows-targets", "windows-targets",
] ]
[[package]]
name = "libpse"
version = "0.1.0"
dependencies = [
"color-print",
"const_format",
"crossterm",
"home",
"mlua",
"thiserror",
"uzers",
"whoami",
]
[[package]] [[package]]
name = "linux-raw-sys" name = "linux-raw-sys"
version = "0.4.15" version = "0.4.15"
@ -316,7 +274,6 @@ checksum = "9ea43c3ffac2d0798bd7128815212dd78c98316b299b7a902dabef13dc7b6b8d"
dependencies = [ dependencies = [
"bstr", "bstr",
"either", "either",
"futures-util",
"libloading", "libloading",
"mlua-sys", "mlua-sys",
"num-traits", "num-traits",
@ -338,18 +295,6 @@ dependencies = [
"pkg-config", "pkg-config",
] ]
[[package]]
name = "nix"
version = "0.29.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"
dependencies = [
"bitflags",
"cfg-if",
"cfg_aliases",
"libc",
]
[[package]] [[package]]
name = "nom" name = "nom"
version = "7.1.3" version = "7.1.3"
@ -398,18 +343,6 @@ dependencies = [
"windows-targets", "windows-targets",
] ]
[[package]]
name = "pin-project-lite"
version = "0.2.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3b3cff922bd51709b605d9ead9aa71031d81447142d828eb4a6eba76fe619f9b"
[[package]]
name = "pin-utils"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184"
[[package]] [[package]]
name = "pkg-config" name = "pkg-config"
version = "0.3.31" version = "0.3.31"
@ -524,15 +457,6 @@ dependencies = [
"libc", "libc",
] ]
[[package]]
name = "slab"
version = "0.4.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67"
dependencies = [
"autocfg",
]
[[package]] [[package]]
name = "smallvec" name = "smallvec"
version = "1.13.2" version = "1.13.2"

View File

@ -1,5 +1,5 @@
[package] [package]
name = "liblambdashell" name = "libpse"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
@ -7,9 +7,8 @@ edition = "2021"
color-print = "0.3.7" color-print = "0.3.7"
const_format = { version = "0.2.34", features = ["rust_1_64"] } const_format = { version = "0.2.34", features = ["rust_1_64"] }
crossterm = "0.28.1" crossterm = "0.28.1"
ctrlc = "3.4.5"
home = "0.5.9" home = "0.5.9"
mlua = { version = "0.10.0", features = ["luau-jit", "vendored", "async", "send"] } mlua = { version = "0.10.0", features = ["luau-jit", "vendored"] }
thiserror = "2.0.9" thiserror = "2.0.9"
uzers = "0.12.1" uzers = "0.12.1"
whoami = "1.5.2" whoami = "1.5.2"

View File

@ -12,7 +12,7 @@ impl PathBufIsValid for PathBuf {
} }
} }
trait ChangeDirectory { trait ChangeDirectory<'a> {
fn change_directory(&self, args: SplitWhitespace) -> Option<PathBuf>; fn change_directory(&self, args: SplitWhitespace) -> Option<PathBuf>;
fn set_current_dir(&self, new_path: &Path) -> Option<PathBuf>; fn set_current_dir(&self, new_path: &Path) -> Option<PathBuf>;
fn specific_user_dir(&self, user: String) -> Option<PathBuf>; fn specific_user_dir(&self, user: String) -> Option<PathBuf>;
@ -20,7 +20,7 @@ trait ChangeDirectory {
fn previous_dir(&self) -> Option<PathBuf>; fn previous_dir(&self) -> Option<PathBuf>;
fn home_dir(&self) -> Option<PathBuf>; fn home_dir(&self) -> Option<PathBuf>;
} }
impl ChangeDirectory for Command { impl<'a> ChangeDirectory<'a> for Command<'a> {
fn set_current_dir(&self, new_path: &Path) -> Option<PathBuf> { fn set_current_dir(&self, new_path: &Path) -> Option<PathBuf> {
std::env::set_current_dir(new_path).map_or_display_none(|()| Some(new_path.to_path_buf())) std::env::set_current_dir(new_path).map_or_display_none(|()| Some(new_path.to_path_buf()))
} }
@ -87,18 +87,19 @@ impl ChangeDirectory for Command {
} }
} }
pub struct Command(String); pub struct Command<'a>(&'a String);
impl Command { impl<'a> Command<'a> {
pub const fn new(input: String) -> Self { pub const fn new(input: &'a String) -> Self {
Self(input) Self(input)
} }
pub fn spawn_sys_cmd(&mut self, history: &mut History, command_process: io::Result<process::Child>) { pub fn spawn_sys_cmd(&mut self, history: &mut History, command_process: io::Result<process::Child>) {
if let Ok(mut child) = command_process { match command_process {
Ok(mut child) => {
history.add(self.0.as_str()); history.add(self.0.as_str());
child.wait().ok(); child.wait().ok();
} else { },
println!("lambdashell: Unknown command: {}", self.0) Err(_) => println!("pse: Unknown command: {}", self.0),
} }
} }

View File

@ -3,7 +3,7 @@ pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub mod session; pub mod session;
pub mod commands; pub mod commands;
pub mod history; pub mod history;
pub mod ps; pub mod terminal;
pub mod rc; pub mod rc;
pub mod vm; pub mod vm;

View File

@ -1,28 +0,0 @@
pub const DEFAULT_PS: &str = concat!("lambdashell-", env!("CARGO_PKG_VERSION"), " ");
#[derive(Debug)]
pub struct Ps(String);
impl Ps {
pub const fn set(prompt: String) -> Self {
Self(prompt)
}
//rustc: `std::string::String::as_str` is not yet stable as a const fn
pub fn get(&self) -> &str {
self.0.as_str()
}
pub fn modify(&mut self, prompt: String) {
self.0 = prompt
}
pub fn display(&self) {
print!("{}", self.0);
}
pub fn working_dir_name(&self) -> String {
std::env::current_dir().map_or("?".to_owned(), |path| path.file_name().map_or("?".to_owned(), |name| {
match name.to_os_string() == whoami::username_os() {
true => "~".to_owned(),
false => name.to_string_lossy().to_string(),
}
}))
}
}

View File

@ -18,7 +18,7 @@ pub fn config_dir() -> Option<PathBuf> {
let mut config = home::home_dir()?; let mut config = home::home_dir()?;
config.push(".config"); config.push(".config");
config.is_valid_dir_or_create()?; config.is_valid_dir_or_create()?;
config.push("lambdashell"); config.push("pse");
config.is_valid_dir_or_create() config.is_valid_dir_or_create()
} }

View File

@ -1,13 +1,10 @@
use std::{fs, io::{self}, sync::{Arc, Mutex}, thread}; use mlua::Lua as Luau;
use std::{cell::RefCell, fs, rc::Rc};
use core::fmt; use core::fmt;
use color_print::ceprintln;
use crate::{commands, history::History, ps::{self, Ps}, rc::{self}, vm::{self, LuauVm}}; use crate::{
history::History, rc::{self}, terminal::TermProcessor, vm::LuauVm
#[inline] };
pub fn shell_error<E: fmt::Display>(err: E) {
ceprintln!("<bold,r>[!]:</> {err}")
}
pub trait MapDisplay<T, E: fmt::Display> { pub trait MapDisplay<T, E: fmt::Display> {
fn map_or_display<F: FnOnce(T)>(self, f: F); fn map_or_display<F: FnOnce(T)>(self, f: F);
@ -26,86 +23,55 @@ impl<T, E: fmt::Display> MapDisplay<T, E> for Result<T, E> {
} }
} }
trait Errors { pub fn shell_error<E: fmt::Display>(err: E) {
fn error<E: fmt::Display>(&mut self, err: E); color_print::ceprintln!("<bold,r>[!]:</> {err}")
} }
impl Errors for LambdaShell { pub fn shell_error_none<T, E: fmt::Display>(err: E) -> Option<T> {
fn error<E: fmt::Display>(&mut self, err: E) {
shell_error(err); shell_error(err);
self.terminate = true; None
}
}
trait Signals {
fn sigterm_event(&mut self);
fn input(&mut self);
}
impl Signals for LambdaShell {
fn sigterm_event(&mut self) {
// task::spawn(async move {
// signal::ctrl_c().await.expect("Failed to listen for a sigterm signal.");
// // self.history.write_to_file_fallible();
// std::process::exit(0x0100);
// });
}
fn input(&mut self) {
thread::spawn(|| {
loop {
if self.terminate { break } else {
match self.wait() {
Ok(()) => self.ps.borrow().display(),
Err(flush_err) => self.error(flush_err),
}
}
}
});
}
} }
#[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 struct LambdaShell { pub struct Rt {
terminate: bool, pub ps: Rc<RefCell<String>>,
history: History, pub input: String,
config: Config, pub vm: Luau,
vm: LuauVm,
ps: Arc<Mutex<Ps>>,
} }
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 {
let ps = Arc::new(Mutex::new(Ps::set(ps::DEFAULT_PS.to_owned())));
Self { Self {
ps: Arc::clone(&ps), rt: Rt {
vm: vm::LuauVm::new(ps), ps: Rc::new(RefCell::new(Self::DEFAULT_PS.to_owned())),
input: String::new(),
vm: Luau::new(),
},
history: History::init(), history: History::init(),
terminate: false,
config, config,
} }
} }
fn wait(&mut self) -> Result<(), io::Error> { pub fn start(&mut self) {
io::Write::flush(&mut io::stdout()).map(|()| {
let mut input = String::new();
io::stdin().read_line(&mut input).map_or_display(|_size| match input.trim() {
"exit" => {
self.terminate = true;
self.history.add("exit");
},
trim => commands::Command::new(trim.to_owned()).exec(&mut self.history)
})
})
}
pub async fn start(&mut self) {
if !self.config.norc { if !self.config.norc {
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.ps.borrow().display(); self.term_input_processor().map_or_display(|()| self.history.write_to_file_fallible())
self.sigterm_event();
self.input();
} }
} }

119
src/terminal.rs Normal file
View File

@ -0,0 +1,119 @@
use crossterm::{event::{self, Event, KeyCode, KeyEvent, KeyModifiers}, terminal};
use std::io::{self, Write};
use thiserror::Error;
use crate::{commands::Command, session::{self, Pse}};
#[derive(Debug, Error)]
pub enum InputHandleError {
#[error("UserExit")]
UserExit,
#[error("Sigterm")]
Sigterm,
#[error("Render failure: {0}")]
Write(io::Error),
#[error("Flush failure: {0}")]
Flush(io::Error),
#[error("Disabling the terminal's raw mode failed: {0}")]
EnableRaw(io::Error),
#[error("Enabling the terminal's raw mode failed: {0}")]
DisableRaw(io::Error),
#[error("key input failure: {0}")]
Key(KeyCode),
}
type InputResult<T> = Result<T, InputHandleError>;
trait SpecificKeybinds {
const TERM_ID_1: &str;
fn key_ctrl(&mut self, input_key: KeyEvent, keycode: KeyCode) -> InputResult<()>;
fn key_enter(&mut self) -> InputResult<()>;
fn key_backspace(&mut self) -> InputResult<()>;
}
impl SpecificKeybinds for Pse {
const TERM_ID_1: &str = "exit";
fn key_ctrl(&mut self, input_key: KeyEvent, keycode: KeyCode) -> InputResult<()> {
if input_key.modifiers.contains(KeyModifiers::CONTROL) {
match keycode {
KeyCode::Char('c') => Err(InputHandleError::Sigterm),
_ => Ok(())
}
} else {
self.term_render(Some(keycode.to_string()))
}
}
fn key_enter(&mut self) -> InputResult<()> {
if self.rt.input == Self::TERM_ID_1 { return Err(InputHandleError::UserExit) };
terminal::disable_raw_mode().map_err(InputHandleError::DisableRaw)?;
Command::new(&self.rt.input).exec(&mut self.history);
self.rt.input.clear();
Ok(())
}
fn key_backspace(&mut self) -> InputResult<()> {
match self.rt.input.pop() {
Some(_) => self.term_render(None),
None => {
//the string is empty, do terminal beep
Ok(())
},
}
}
}
pub trait TermProcessor {
fn term_render(&mut self, def: Option<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: Option<String>) -> InputResult<()> {
match def {
Some(def_string) => {
self.rt.input.push_str(&def_string);
write!(io::stdout(), "{def_string}").map_err(InputHandleError::Write)?;
},
None => {
write!(io::stdout(), "{}", self.rt.input).map_err(InputHandleError::Write)?
}
};
io::stdout().flush().map_err(InputHandleError::Flush)
}
fn term_input_handler(&mut self, input_key: KeyEvent) -> Option<()> {
let input_handle = match input_key.code {
KeyCode::Enter => self.key_enter(),
KeyCode::Backspace => self.key_backspace(),
KeyCode::Tab => todo!(),
KeyCode::Right => todo!(),
KeyCode::Left => todo!(),
KeyCode::Up => todo!(),
KeyCode::Down => todo!(),
keycode => self.key_ctrl(input_key, keycode)
};
input_handle.map_or_else(|inp_err| match inp_err {
InputHandleError::UserExit => None,
InputHandleError::Sigterm => self.term_render(Some("^C".to_owned())).ok(),
input_err => session::shell_error_none(input_err)
}, Some)
}
fn term_input_mainthread(&mut self) -> io::Result<()> {
crossterm::execute!(io::stdout(), event::EnableBracketedPaste)?;
loop {
terminal::enable_raw_mode()?;
if let Event::Key(event) = event::read()? {
if self.term_input_handler(event).is_none() { break Ok(()) }
}
}
}
fn term_input_processor(&mut self) -> io::Result<()> {
self.term_input_mainthread()?;
terminal::disable_raw_mode()?;
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 terminal::TerminalGlobal;
use std::{cell::RefCell, rc::Rc};
use core::fmt;
use shell::ShellGlobal; use shell::ShellGlobal;
use terminal::TerminalGlobal;
use core::fmt;
use crate::{ps::Ps, session::MapDisplay}; use crate::session::{Pse, MapDisplay};
mod shell; mod shell;
mod terminal; mod terminal;
@ -18,25 +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;
fn global_warn(&self, luau_globals: &Table) -> lResult<()>; const LIB_NAME: &str;
fn global_version(&self, luau_globals: &Table) -> lResult<()>; fn vm_glob_warn(&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 CONV_ERROR: &str = "<SHELL CONVERSION ERROR>"; const CONV_ERROR: &str = "<SHELL CONVERSION ERROR>";
fn global_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()))
@ -46,34 +47,31 @@ impl Globals for LuauVm {
})?) })?)
} }
fn global_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}, liblambdashell {}", 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 set_shell_globals(&self) -> lResult<()> {
let luau_globals = self.vm.globals();
self.global_shell(&luau_globals)?;
self.global_terminal(&luau_globals)?;
self.global_warn(&luau_globals)?;
self.global_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.set_shell_globals().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, 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,17 +19,18 @@ 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, (tindex, tvalue): (String, String)| -> lResult<()> { methods.add_meta_method_mut(MetaMethod::NewIndex, |_, this, (t_index, t_value): (String, String)| -> lResult<()> {
if tindex == "PROMPT" { if t_index == "PROMPT" {
this.0.borrow_mut().modify(tvalue); let mut prompt = this.0.borrow_mut();
*prompt = t_value;
} }
Ok(()) Ok(())
}); });
@ -37,11 +38,10 @@ impl UserData for Shell {
} }
pub trait ShellGlobal { pub trait ShellGlobal {
fn global_shell(&self, luau_globals: &Table) -> lResult<()>; fn vm_glob_shell(&self, luau_globals: &Table) -> lResult<()>;
} }
impl ShellGlobal for LuauVm { impl ShellGlobal for Pse {
fn global_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 global_terminal(&self, luau_globals: &Table) -> lResult<()>; fn vm_glob_terminal(&self, luau_globals: &Table) -> lResult<()>;
} }
impl TerminalGlobal for LuauVm { impl TerminalGlobal for Pse {
fn global_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)
} }
} }