Compare commits
1 Commits
restructur
...
multithrea
Author | SHA1 | Date | |
---|---|---|---|
15a2dcb3d5 |
112
Cargo.lock
generated
112
Cargo.lock
generated
@ -10,9 +10,9 @@ checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
|
||||
|
||||
[[package]]
|
||||
name = "bitflags"
|
||||
version = "2.8.0"
|
||||
version = "2.7.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36"
|
||||
checksum = "1be3f42a67d6d345ecd59f675f3f012d6974981560836e938c22b424b85ce1be"
|
||||
|
||||
[[package]]
|
||||
name = "bstr"
|
||||
@ -32,9 +32,9 @@ checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
|
||||
|
||||
[[package]]
|
||||
name = "cc"
|
||||
version = "1.2.10"
|
||||
version = "1.2.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "13208fcbb66eaeffe09b99fffbe1af420f00a7b35aa99ad683dfc1aa76145229"
|
||||
checksum = "c8293772165d9345bdaaa39b45b2109591e63fe5e6fbc23c6ff930a048aa310b"
|
||||
dependencies = [
|
||||
"shlex",
|
||||
]
|
||||
@ -45,6 +45,12 @@ version = "1.0.0"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
|
||||
|
||||
[[package]]
|
||||
name = "cfg_aliases"
|
||||
version = "0.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
|
||||
|
||||
[[package]]
|
||||
name = "color-print"
|
||||
version = "0.3.7"
|
||||
@ -112,6 +118,16 @@ dependencies = [
|
||||
"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]]
|
||||
name = "either"
|
||||
version = "1.13.0"
|
||||
@ -128,6 +144,31 @@ dependencies = [
|
||||
"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]]
|
||||
name = "home"
|
||||
version = "0.5.11"
|
||||
@ -168,6 +209,21 @@ version = "0.2.169"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "b5aba8db14291edd000dfcc4d620c7ebfb122c613afb886ca8803fa4e128a20a"
|
||||
|
||||
[[package]]
|
||||
name = "liblambdashell"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"color-print",
|
||||
"const_format",
|
||||
"crossterm",
|
||||
"ctrlc",
|
||||
"home",
|
||||
"mlua",
|
||||
"thiserror",
|
||||
"uzers",
|
||||
"whoami",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libloading"
|
||||
version = "0.8.6"
|
||||
@ -178,20 +234,6 @@ dependencies = [
|
||||
"windows-targets",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libpse"
|
||||
version = "0.1.0"
|
||||
dependencies = [
|
||||
"color-print",
|
||||
"const_format",
|
||||
"crossterm",
|
||||
"home",
|
||||
"mlua",
|
||||
"thiserror",
|
||||
"uzers",
|
||||
"whoami",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "linux-raw-sys"
|
||||
version = "0.4.15"
|
||||
@ -274,6 +316,7 @@ checksum = "9ea43c3ffac2d0798bd7128815212dd78c98316b299b7a902dabef13dc7b6b8d"
|
||||
dependencies = [
|
||||
"bstr",
|
||||
"either",
|
||||
"futures-util",
|
||||
"libloading",
|
||||
"mlua-sys",
|
||||
"num-traits",
|
||||
@ -295,6 +338,18 @@ dependencies = [
|
||||
"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]]
|
||||
name = "nom"
|
||||
version = "7.1.3"
|
||||
@ -343,6 +398,18 @@ dependencies = [
|
||||
"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]]
|
||||
name = "pkg-config"
|
||||
version = "0.3.31"
|
||||
@ -457,6 +524,15 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "slab"
|
||||
version = "0.4.9"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "8f92a496fb766b417c996b9c5e57daf2f7ad3b0bebe1ccfca4856390e3d3bb67"
|
||||
dependencies = [
|
||||
"autocfg",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "smallvec"
|
||||
version = "1.13.2"
|
||||
|
@ -1,5 +1,5 @@
|
||||
[package]
|
||||
name = "libpse"
|
||||
name = "liblambdashell"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
@ -7,8 +7,9 @@ edition = "2021"
|
||||
color-print = "0.3.7"
|
||||
const_format = { version = "0.2.34", features = ["rust_1_64"] }
|
||||
crossterm = "0.28.1"
|
||||
ctrlc = "3.4.5"
|
||||
home = "0.5.9"
|
||||
mlua = { version = "0.10.0", features = ["luau-jit", "vendored"] }
|
||||
mlua = { version = "0.10.0", features = ["luau-jit", "vendored", "async", "send"] }
|
||||
thiserror = "2.0.9"
|
||||
uzers = "0.12.1"
|
||||
whoami = "1.5.2"
|
||||
whoami = "1.5.2"
|
||||
|
@ -12,7 +12,7 @@ impl PathBufIsValid for PathBuf {
|
||||
}
|
||||
}
|
||||
|
||||
trait ChangeDirectory<'a> {
|
||||
trait ChangeDirectory {
|
||||
fn change_directory(&self, args: SplitWhitespace) -> Option<PathBuf>;
|
||||
fn set_current_dir(&self, new_path: &Path) -> Option<PathBuf>;
|
||||
fn specific_user_dir(&self, user: String) -> Option<PathBuf>;
|
||||
@ -20,7 +20,7 @@ trait ChangeDirectory<'a> {
|
||||
fn previous_dir(&self) -> Option<PathBuf>;
|
||||
fn home_dir(&self) -> Option<PathBuf>;
|
||||
}
|
||||
impl<'a> ChangeDirectory<'a> for Command<'a> {
|
||||
impl ChangeDirectory for Command {
|
||||
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()))
|
||||
}
|
||||
@ -87,19 +87,18 @@ impl<'a> ChangeDirectory<'a> for Command<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
pub struct Command<'a>(&'a String);
|
||||
impl<'a> Command<'a> {
|
||||
pub const fn new(input: &'a String) -> Self {
|
||||
pub struct Command(String);
|
||||
impl Command {
|
||||
pub const fn new(input: String) -> Self {
|
||||
Self(input)
|
||||
}
|
||||
|
||||
pub fn spawn_sys_cmd(&mut self, history: &mut History, command_process: io::Result<process::Child>) {
|
||||
match command_process {
|
||||
Ok(mut child) => {
|
||||
history.add(self.0.as_str());
|
||||
child.wait().ok();
|
||||
},
|
||||
Err(_) => println!("pse: Unknown command: {}", self.0),
|
||||
if let Ok(mut child) = command_process {
|
||||
history.add(self.0.as_str());
|
||||
child.wait().ok();
|
||||
} else {
|
||||
println!("lambdashell: Unknown command: {}", self.0)
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -3,7 +3,7 @@ pub const VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
pub mod session;
|
||||
pub mod commands;
|
||||
pub mod history;
|
||||
pub mod terminal;
|
||||
pub mod ps;
|
||||
pub mod rc;
|
||||
pub mod vm;
|
||||
|
||||
|
28
src/ps.rs
Normal file
28
src/ps.rs
Normal file
@ -0,0 +1,28 @@
|
||||
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(),
|
||||
}
|
||||
}))
|
||||
}
|
||||
}
|
@ -18,7 +18,7 @@ pub fn config_dir() -> Option<PathBuf> {
|
||||
let mut config = home::home_dir()?;
|
||||
config.push(".config");
|
||||
config.is_valid_dir_or_create()?;
|
||||
config.push("pse");
|
||||
config.push("lambdashell");
|
||||
config.is_valid_dir_or_create()
|
||||
}
|
||||
|
||||
|
108
src/session.rs
108
src/session.rs
@ -1,10 +1,13 @@
|
||||
use mlua::Lua as Luau;
|
||||
use std::{cell::RefCell, fs, rc::Rc};
|
||||
use std::{fs, io::{self}, sync::{Arc, Mutex}, thread};
|
||||
use core::fmt;
|
||||
use color_print::ceprintln;
|
||||
|
||||
use crate::{
|
||||
history::History, rc::{self}, terminal::TermProcessor, vm::LuauVm
|
||||
};
|
||||
use crate::{commands, history::History, ps::{self, Ps}, rc::{self}, vm::{self, LuauVm}};
|
||||
|
||||
#[inline]
|
||||
pub fn shell_error<E: fmt::Display>(err: E) {
|
||||
ceprintln!("<bold,r>[!]:</> {err}")
|
||||
}
|
||||
|
||||
pub trait MapDisplay<T, E: fmt::Display> {
|
||||
fn map_or_display<F: FnOnce(T)>(self, f: F);
|
||||
@ -23,55 +26,86 @@ impl<T, E: fmt::Display> MapDisplay<T, E> for Result<T, E> {
|
||||
}
|
||||
}
|
||||
|
||||
pub fn shell_error<E: fmt::Display>(err: E) {
|
||||
color_print::ceprintln!("<bold,r>[!]:</> {err}")
|
||||
trait Errors {
|
||||
fn error<E: fmt::Display>(&mut self, err: E);
|
||||
}
|
||||
pub fn shell_error_none<T, E: fmt::Display>(err: E) -> Option<T> {
|
||||
shell_error(err);
|
||||
None
|
||||
impl Errors for LambdaShell {
|
||||
fn error<E: fmt::Display>(&mut self, err: E) {
|
||||
shell_error(err);
|
||||
self.terminate = true;
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct VmConfig {
|
||||
pub sandbox: bool,
|
||||
pub jit: bool,
|
||||
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 Config {
|
||||
pub norc: bool,
|
||||
pub vm: VmConfig,
|
||||
pub norc: bool
|
||||
}
|
||||
pub struct Rt {
|
||||
pub ps: Rc<RefCell<String>>,
|
||||
pub input: String,
|
||||
pub vm: Luau,
|
||||
pub struct LambdaShell {
|
||||
terminate: bool,
|
||||
history: History,
|
||||
config: Config,
|
||||
vm: LuauVm,
|
||||
ps: Arc<Mutex<Ps>>,
|
||||
}
|
||||
pub struct Pse {
|
||||
pub config: Config,
|
||||
pub history: History,
|
||||
pub rt: Rt
|
||||
}
|
||||
impl Pse {
|
||||
const DEFAULT_PS: &str = concat!("pse-", env!("CARGO_PKG_VERSION"), "$ ");
|
||||
|
||||
impl LambdaShell {
|
||||
pub fn create(config: Config) -> Self {
|
||||
let ps = Arc::new(Mutex::new(Ps::set(ps::DEFAULT_PS.to_owned())));
|
||||
Self {
|
||||
rt: Rt {
|
||||
ps: Rc::new(RefCell::new(Self::DEFAULT_PS.to_owned())),
|
||||
input: String::new(),
|
||||
vm: Luau::new(),
|
||||
},
|
||||
ps: Arc::clone(&ps),
|
||||
vm: vm::LuauVm::new(ps),
|
||||
history: History::init(),
|
||||
terminate: false,
|
||||
config,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn start(&mut self) {
|
||||
fn wait(&mut self) -> Result<(), io::Error> {
|
||||
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 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())
|
||||
self.ps.borrow().display();
|
||||
self.sigterm_event();
|
||||
self.input();
|
||||
}
|
||||
}
|
||||
}
|
119
src/terminal.rs
119
src/terminal.rs
@ -1,119 +0,0 @@
|
||||
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)
|
||||
}
|
||||
}
|
@ -1,10 +1,11 @@
|
||||
use mlua::{Function, MultiValue, Result as lResult, Table, Value};
|
||||
use color_print::cformat;
|
||||
use shell::ShellGlobal;
|
||||
use mlua::{Function, Lua as Luau, MultiValue, Result as lResult, Table, Value};
|
||||
use color_print::{cformat, ceprintln};
|
||||
use terminal::TerminalGlobal;
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
use core::fmt;
|
||||
use shell::ShellGlobal;
|
||||
|
||||
use crate::session::{Pse, MapDisplay};
|
||||
use crate::{ps::Ps, session::MapDisplay};
|
||||
|
||||
mod shell;
|
||||
mod terminal;
|
||||
@ -17,27 +18,25 @@ impl<T, E: fmt::Display> LuauRuntimeErr<T> for Result<T, E> {
|
||||
#[inline]
|
||||
fn map_or_luau_rt_err<R, F: FnOnce(T) -> Option<R>>(self, f: F) -> Option<R> {
|
||||
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
|
||||
}, f)
|
||||
}
|
||||
}
|
||||
|
||||
trait VmGlobals {
|
||||
trait Globals {
|
||||
const LIB_VERSION: &str;
|
||||
const CONV_ERROR: &str;
|
||||
const LIB_NAME: &str;
|
||||
fn vm_glob_warn(&self, luau_globals: &Table) -> lResult<()>;
|
||||
fn vm_glob_version(&self, luau_globals: &Table) -> lResult<()>;
|
||||
fn global_warn(&self, luau_globals: &Table) -> lResult<()>;
|
||||
fn global_version(&self, luau_globals: &Table) -> lResult<()>;
|
||||
}
|
||||
impl VmGlobals for Pse {
|
||||
impl Globals for LuauVm {
|
||||
const LIB_VERSION: &str = env!("CARGO_PKG_VERSION");
|
||||
const LIB_NAME: &str = env!("CARGO_PKG_NAME");
|
||||
const CONV_ERROR: &str = "<SHELL CONVERSION ERROR>";
|
||||
|
||||
fn vm_glob_warn(&self, luau_globals: &Table) -> lResult<()> {
|
||||
fn global_warn(&self, luau_globals: &Table) -> lResult<()> {
|
||||
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()
|
||||
.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()))
|
||||
@ -47,31 +46,34 @@ impl VmGlobals for Pse {
|
||||
})?)
|
||||
}
|
||||
|
||||
fn vm_glob_version(&self, luau_globals: &Table) -> lResult<()> {
|
||||
fn global_version(&self, luau_globals: &Table) -> lResult<()> {
|
||||
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}, liblambdashell {}", Self::LIB_VERSION))
|
||||
}
|
||||
}
|
||||
|
||||
pub trait LuauVm {
|
||||
fn vm_setglobs(&self) -> lResult<()>;
|
||||
fn vm_exec(&self, source: String);
|
||||
pub struct LuauVm {
|
||||
vm: Luau,
|
||||
ps: Rc<RefCell<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)?;
|
||||
impl LuauVm {
|
||||
pub(crate) fn new(ps: Rc<RefCell<Ps>>) -> Self {
|
||||
Self { vm: Luau::new(), ps }
|
||||
}
|
||||
|
||||
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("setfenv", mlua::Nil)?;
|
||||
self.rt.vm.enable_jit(self.config.vm.jit);
|
||||
self.rt.vm.sandbox(true)
|
||||
self.vm.sandbox(true)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn vm_exec(&self, source: String) {
|
||||
self.vm_setglobs().map_or_display_none(|()| self.rt.vm.load(source).exec().map_or_luau_rt_err(Some));
|
||||
pub fn exec(&self, source: String) {
|
||||
self.set_shell_globals().map_or_display_none(|()| self.vm.load(source).exec().map_or_luau_rt_err(Some));
|
||||
}
|
||||
}
|
@ -2,11 +2,11 @@ use mlua::{Lua as Luau, MetaMethod, Result as lResult, Table, UserData, UserData
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
use whoami::fallible;
|
||||
|
||||
use crate::session::Pse;
|
||||
use crate::{ps::Ps, vm::LuauVm};
|
||||
|
||||
const DEFAULT_HOSTNAME: &str = "hostname";
|
||||
|
||||
fn luau_sys_details(luau: &Luau) -> lResult<Table> {
|
||||
const DEFAULT_HOSTNAME: &str = "hostname";
|
||||
|
||||
let system = luau.create_table()?;
|
||||
system.raw_set("DESKTOP_ENV", whoami::desktop_env().to_string())?;
|
||||
system.raw_set("DEVICENAME", whoami::devicename().to_string())?;
|
||||
@ -19,18 +19,17 @@ fn luau_sys_details(luau: &Luau) -> lResult<Table> {
|
||||
Ok(system)
|
||||
}
|
||||
|
||||
struct Shell(Rc<RefCell<String>>);
|
||||
struct Shell(Rc<RefCell<Ps>>);
|
||||
impl UserData for Shell {
|
||||
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));
|
||||
}
|
||||
|
||||
fn add_methods<M: UserDataMethods<Self>>(methods: &mut M) {
|
||||
methods.add_meta_method_mut(MetaMethod::NewIndex, |_, this, (t_index, t_value): (String, String)| -> lResult<()> {
|
||||
if t_index == "PROMPT" {
|
||||
let mut prompt = this.0.borrow_mut();
|
||||
*prompt = t_value;
|
||||
methods.add_meta_method_mut(MetaMethod::NewIndex, |_, this, (tindex, tvalue): (String, String)| -> lResult<()> {
|
||||
if tindex == "PROMPT" {
|
||||
this.0.borrow_mut().modify(tvalue);
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
@ -38,10 +37,11 @@ impl UserData for Shell {
|
||||
}
|
||||
|
||||
pub trait ShellGlobal {
|
||||
fn vm_glob_shell(&self, luau_globals: &Table) -> lResult<()>;
|
||||
fn global_shell(&self, luau_globals: &Table) -> lResult<()>;
|
||||
}
|
||||
impl ShellGlobal for Pse {
|
||||
fn vm_glob_shell(&self, luau_globals: &Table) -> lResult<()> {
|
||||
luau_globals.raw_set("SHELL", Shell(Rc::clone(&self.rt.ps)))
|
||||
impl ShellGlobal for LuauVm {
|
||||
fn global_shell(&self, luau_globals: &Table) -> lResult<()> {
|
||||
luau_globals.raw_set("SHELL", Shell(Rc::clone(&self.ps)))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
@ -2,7 +2,7 @@ use mlua::{UserDataFields, Lua as Luau, Result as lResult, Table, UserData};
|
||||
use const_format::str_split;
|
||||
use crossterm::style::Stylize;
|
||||
|
||||
use crate::session::Pse;
|
||||
use crate::vm::LuauVm;
|
||||
|
||||
macro_rules! foreground_styles_luau {
|
||||
($luau:expr, $style_table:expr, $($color:ident)+) => {
|
||||
@ -84,10 +84,10 @@ impl UserData for Terminal {
|
||||
}
|
||||
|
||||
pub trait TerminalGlobal {
|
||||
fn vm_glob_terminal(&self, luau_globals: &Table) -> lResult<()>;
|
||||
fn global_terminal(&self, luau_globals: &Table) -> lResult<()>;
|
||||
}
|
||||
impl TerminalGlobal for Pse {
|
||||
fn vm_glob_terminal(&self, luau_globals: &Table) -> lResult<()> {
|
||||
impl TerminalGlobal for LuauVm {
|
||||
fn global_terminal(&self, luau_globals: &Table) -> lResult<()> {
|
||||
luau_globals.raw_set("TERMINAL", Terminal)
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user