1 Commits

Author SHA1 Message Date
15a2dcb3d5 experimenting 2025-01-14 16:38:04 -05:00
12 changed files with 323 additions and 411 deletions

152
Cargo.lock generated
View File

@ -10,9 +10,9 @@ checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26"
[[package]] [[package]]
name = "bitflags" name = "bitflags"
version = "2.8.0" version = "2.7.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36" checksum = "1be3f42a67d6d345ecd59f675f3f012d6974981560836e938c22b424b85ce1be"
[[package]] [[package]]
name = "bstr" name = "bstr"
@ -26,15 +26,15 @@ dependencies = [
[[package]] [[package]]
name = "bumpalo" name = "bumpalo"
version = "3.17.0" version = "3.16.0"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1628fb46dfa0b37568d12e5edd512553eccf6a22a78e8bde00bb4aed84d5bdbf" checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.2.10" version = "1.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13208fcbb66eaeffe09b99fffbe1af420f00a7b35aa99ad683dfc1aa76145229" checksum = "c8293772165d9345bdaaa39b45b2109591e63fe5e6fbc23c6ff930a048aa310b"
dependencies = [ dependencies = [
"shlex", "shlex",
] ]
@ -45,6 +45,12 @@ 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"
@ -112,18 +118,22 @@ 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"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0" checksum = "60b1af1c220855b6ceac025d3f6ecdd2b7c4894bfe9cd9bda4fbb4bc7c0d4cf0"
[[package]]
name = "env_home"
version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c7f84e12ccf0a7ddc17a6c41c93326024c42920d7ee630d04950e6926645c0fe"
[[package]] [[package]]
name = "errno" name = "errno"
version = "0.3.10" version = "0.3.10"
@ -134,6 +144,31 @@ 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"
@ -174,6 +209,21 @@ 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"
@ -184,20 +234,6 @@ 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"
@ -231,9 +267,9 @@ dependencies = [
[[package]] [[package]]
name = "luajit-src" name = "luajit-src"
version = "210.5.12+a4f56a4" version = "210.5.11+97813fb"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3a8e7962a5368d5f264d045a5a255e90f9aa3fc1941ae15a8d2940d42cac671" checksum = "3015551c284515db7c30c559fc1080f9cb9ee990d1f6fca315451a107c7540bb"
dependencies = [ dependencies = [
"cc", "cc",
"which", "which",
@ -241,9 +277,9 @@ dependencies = [
[[package]] [[package]]
name = "luau0-src" name = "luau0-src"
version = "0.12.0+luau657" version = "0.11.2+luau653"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3a4b4c16b82ddf60e0fa93ca5a6afc504a6db22310cc82ecec629cd2e405b2ca" checksum = "02313a53daf1fae25e82f7e7ca56180b72d1f08c514426672877cd957298201c"
dependencies = [ dependencies = [
"cc", "cc",
] ]
@ -274,12 +310,13 @@ dependencies = [
[[package]] [[package]]
name = "mlua" name = "mlua"
version = "0.10.3" version = "0.10.2"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d3f763c1041eff92ffb5d7169968a327e1ed2ebfe425dac0ee5a35f29082534b" checksum = "9ea43c3ffac2d0798bd7128815212dd78c98316b299b7a902dabef13dc7b6b8d"
dependencies = [ dependencies = [
"bstr", "bstr",
"either", "either",
"futures-util",
"libloading", "libloading",
"mlua-sys", "mlua-sys",
"num-traits", "num-traits",
@ -289,9 +326,9 @@ dependencies = [
[[package]] [[package]]
name = "mlua-sys" name = "mlua-sys"
version = "0.6.7" version = "0.6.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1901c1a635a22fe9250ffcc4fcc937c16b47c2e9e71adba8784af8bca1f69594" checksum = "63a11d485edf0f3f04a508615d36c7d50d299cf61a7ee6d3e2530651e0a31771"
dependencies = [ dependencies = [
"cc", "cc",
"cfg-if", "cfg-if",
@ -301,6 +338,18 @@ 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"
@ -349,6 +398,18 @@ 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"
@ -390,9 +451,9 @@ checksum = "c7fb8039b3032c191086b10f11f319a6e99e1e82889c5cc6046f515c9db1d497"
[[package]] [[package]]
name = "rustix" name = "rustix"
version = "0.38.44" version = "0.38.43"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" checksum = "a78891ee6bf2340288408954ac787aa063d8e8817e9f53abb37c695c6d834ef6"
dependencies = [ dependencies = [
"bitflags", "bitflags",
"errno", "errno",
@ -463,6 +524,15 @@ 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"
@ -502,9 +572,9 @@ dependencies = [
[[package]] [[package]]
name = "unicode-ident" name = "unicode-ident"
version = "1.0.16" version = "1.0.14"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a210d160f08b701c8721ba1c726c11662f877ea6b7094007e1ca9a1041945034" checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83"
[[package]] [[package]]
name = "unicode-xid" name = "unicode-xid"
@ -603,12 +673,12 @@ dependencies = [
[[package]] [[package]]
name = "which" name = "which"
version = "7.0.1" version = "6.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fb4a9e33648339dc1642b0e36e21b3385e6148e289226f657c809dee59df5028" checksum = "b4ee928febd44d98f2f459a4a79bd4d928591333a494a10a868418ac1b39cf1f"
dependencies = [ dependencies = [
"either", "either",
"env_home", "home",
"rustix", "rustix",
"winsafe", "winsafe",
] ]

View File

@ -1,5 +1,5 @@
[package] [package]
name = "libpse" name = "liblambdashell"
version = "0.1.0" version = "0.1.0"
edition = "2021" edition = "2021"
@ -7,8 +7,9 @@ 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"] } mlua = { version = "0.10.0", features = ["luau-jit", "vendored", "async", "send"] }
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

@ -1,7 +1,7 @@
use std::{env, path::{Path, PathBuf}, process, str::SplitWhitespace}; use std::{io, process, str::SplitWhitespace, path::{Path, PathBuf}};
use uzers::User; use uzers::User;
use crate::{session::{MapDisplay, Pse}, valid_pbuf::IsValid}; use crate::{history::History, session::MapDisplay, valid_pbuf::IsValid};
trait PathBufIsValid { trait PathBufIsValid {
fn is_valid_or_home(&self) -> Option<PathBuf>; fn is_valid_or_home(&self) -> Option<PathBuf>;
@ -12,34 +12,34 @@ impl PathBufIsValid for PathBuf {
} }
} }
struct ChangeDirectory(Option<PathBuf>); trait ChangeDirectory {
impl ChangeDirectory { fn change_directory(&self, args: SplitWhitespace) -> Option<PathBuf>;
fn set_dir(&mut self, new_path: &Path) -> Option<PathBuf> { fn set_current_dir(&self, new_path: &Path) -> Option<PathBuf>;
let past_dir = env::current_dir().ok(); fn specific_user_dir(&self, user: String) -> Option<PathBuf>;
env::set_current_dir(new_path).map_or_display_none(|()| { fn cd_args(&self, vec_args: Vec<String>) -> Option<PathBuf>;
self.0 = past_dir; fn previous_dir(&self) -> Option<PathBuf>;
Some(new_path.to_path_buf()) fn home_dir(&self) -> Option<PathBuf>;
}) }
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()))
} }
fn home_dir(&mut self) -> Option<PathBuf> { fn home_dir(&self) -> Option<PathBuf> {
home::home_dir().map_or(self.set_dir(Path::new("/")), |home_pathbuf| self.set_dir(&home_pathbuf)) home::home_dir().map_or(self.set_current_dir(Path::new("/")), |home_pathbuf| self.set_current_dir(&home_pathbuf))
} }
fn previous_dir(&mut self) -> Option<PathBuf> { fn previous_dir(&self) -> Option<PathBuf> {
match self.0.as_ref() { unimplemented!()
Some(p_buf) => self.set_dir(&p_buf.to_path_buf()),
None => None
}
} }
fn specific_user_dir(&self, requested_user: String) -> Option<PathBuf> { fn specific_user_dir(&self, requested_user: String) -> Option<PathBuf> {
match requested_user.as_str() { match requested_user.as_str() {
"root" => PathBuf::from("/root").is_valid_or_home(), "root" => PathBuf::from("/root").is_valid_or_home(),
u => { _ => {
for user in unsafe { uzers::all_users().collect::<Vec<User>>() } { for user in unsafe { uzers::all_users().collect::<Vec<User>>() } {
let user_name = user.name(); let user_name = user.name();
if *u == *user_name { if *requested_user == *user_name {
let mut user_dir = PathBuf::from("/home"); let mut user_dir = PathBuf::from("/home");
user_dir.push(user_name); user_dir.push(user_name);
return user_dir.is_valid_or_home(); return user_dir.is_valid_or_home();
@ -50,11 +50,11 @@ impl ChangeDirectory {
} }
} }
fn cd_args(&mut self, vec_args: Vec<String>) -> Option<PathBuf> { fn cd_args(&self, vec_args: Vec<String>) -> Option<PathBuf> {
let string_path = vec_args.concat(); let string_path = vec_args.concat();
let new_path = Path::new(string_path.as_str()); let new_path = Path::new(string_path.as_str());
match new_path.is_dir() { match new_path.is_dir() {
true => self.set_dir(new_path), true => self.set_current_dir(new_path),
false => { false => {
match new_path.file_name() { match new_path.file_name() {
Some(file_name) => println!("cd: {:?} is not a directory.", file_name), Some(file_name) => println!("cd: {:?} is not a directory.", file_name),
@ -65,15 +65,15 @@ impl ChangeDirectory {
} }
} }
fn change_directory(&mut self, args: SplitWhitespace) -> Option<PathBuf> { fn change_directory(&self, args: SplitWhitespace) -> Option<PathBuf> {
let vec_args: Vec<String> = args.map(|arg| arg.to_owned()).collect(); let vec_args: Vec<String> = args.map(|arg| arg.to_owned()).collect();
match vec_args.first() { match vec_args.first() {
None => self.home_dir(), None => self.home_dir(),
Some(arg) => match arg.as_str() { Some(arg) => match arg.as_str() {
"/" => self.set_dir(Path::new("/")), "/" => self.set_current_dir(Path::new("/")),
"-" => self.previous_dir(), "-" => self.previous_dir(),
arg_str => { _ => {
let mut arg_chars = arg_str.chars(); let mut arg_chars = arg.chars();
match arg_chars.next() { match arg_chars.next() {
Some(char) => match char == '~' { Some(char) => match char == '~' {
true => self.specific_user_dir(arg_chars.collect::<String>()), true => self.specific_user_dir(arg_chars.collect::<String>()),
@ -87,23 +87,27 @@ impl ChangeDirectory {
} }
} }
pub trait Command { pub struct Command(String);
fn spawn_sys_cmd(&mut self); impl Command {
} pub const fn new(input: String) -> Self {
impl Command for Pse { Self(input)
fn spawn_sys_cmd(&mut self) { }
let mut args = self.rt.input.literal.split_whitespace();
pub fn spawn_sys_cmd(&mut self, history: &mut History, command_process: io::Result<process::Child>) {
if let Ok(mut child) = command_process {
history.add(self.0.as_str());
child.wait().ok();
} else {
println!("lambdashell: Unknown command: {}", self.0)
}
}
pub fn exec(&mut self, history: &mut History) {
let mut args = self.0.split_whitespace();
if let Some(command) = args.next() { if let Some(command) = args.next() {
match command { match command {
"cd" => if ChangeDirectory(None).change_directory(args).is_some() { "cd" => if self.change_directory(args).is_some() { history.add(self.0.as_str()) },
self.rt.history.add(self.rt.input.literal.as_str()) command => { self.spawn_sys_cmd(history, process::Command::new(command).args(args).spawn()); }
},
command => if let Ok(mut child) = process::Command::new(command).args(args).spawn() {
self.rt.history.add(self.rt.input.literal.as_str());
child.wait().ok();
} else {
println!("pse: Unknown command: {}", self.rt.input.literal)
}
} }
} }
} }

View File

@ -4,39 +4,38 @@ use crate::{rc::{self}, session::{self, MapDisplay}, valid_pbuf::IsValid};
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct History { pub struct History {
pub history: Vec<String>, fs_history: Option<Vec<String>>,
pub index: isize, history: Vec<String>,
file: Option<PathBuf>, file: Option<PathBuf>,
} }
impl History { impl History {
pub fn init() -> Self { pub fn init() -> Self {
let mut history = Vec::new();
let file = rc::config_dir().map(|mut config_dir| { let file = rc::config_dir().map(|mut config_dir| {
config_dir.push(".history"); config_dir.push(".history");
config_dir.is_valid_file_or_create(b""); config_dir.is_valid_file_or_create(b"");
config_dir config_dir
}); });
file.as_ref().and_then(|file| { let fs_history = file.as_ref().and_then(|file| {
File::open(file).map_or_display_none(|file| { File::open(file).map_or_display_none(|file| {
let mut fs_history_vec = BufReader::new(file).lines().map_while(Result::ok).collect::<Vec<String>>(); Some(BufReader::new(file).lines().map_while(Result::ok).collect::<Vec<String>>())
fs_history_vec.dedup();
fs_history_vec.reverse();
Some(fs_history_vec)
}) })
}).inspect(|fs_history_vec| history = fs_history_vec.clone()); });
Self {
Self { history, file, index: -1 } history: Vec::new(),
fs_history,
file,
}
} }
pub fn write_to_file_fallible(&mut self) { pub fn write_to_file_fallible(&mut self) {
if self.history.is_empty() { return; } if self.history.is_empty() { return; }
if let Some(history_file) = &self.file { if let (Some(history_file), Some(fs_history)) = (&self.file, &self.fs_history) {
OpenOptions::new() OpenOptions::new()
.append(true) .append(true)
.open(history_file.as_path()) .open(history_file.as_path())
.map_or_display(|mut file| { .map_or_display(|mut file| {
let newline_maybe = if self.history.is_empty() { "" } else { "\n" }; let newline_maybe = if fs_history.is_empty() { "" } else { "\n" };
let formatted = format!("{newline_maybe}{}", self.history.join("\n")); let formatted = format!("{newline_maybe}{}", self.history.join("\n"));
file.write_all(formatted.as_bytes()).unwrap_or_else(session::shell_error) file.write_all(formatted.as_bytes()).unwrap_or_else(session::shell_error)
}); });

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 terminal; pub mod ps;
pub mod rc; pub mod rc;
pub mod vm; pub mod vm;

28
src/ps.rs Normal file
View 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(),
}
}))
}
}

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("pse"); config.push("lambdashell");
config.is_valid_dir_or_create() config.is_valid_dir_or_create()
} }

View File

@ -1,10 +1,13 @@
use mlua::Lua as Luau; use std::{fs, io::{self}, sync::{Arc, Mutex}, thread};
use std::{cell::RefCell, fs, rc::Rc};
use core::fmt; use core::fmt;
use color_print::ceprintln;
use crate::{ use crate::{commands, history::History, ps::{self, Ps}, rc::{self}, vm::{self, LuauVm}};
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);
@ -23,62 +26,86 @@ impl<T, E: fmt::Display> MapDisplay<T, E> for Result<T, E> {
} }
} }
pub fn shell_error<E: fmt::Display>(err: E) { trait Errors {
color_print::ceprintln!("<bold,r>[!]:</> {err}") fn error<E: fmt::Display>(&mut self, err: E);
} }
pub fn shell_error_none<T, E: fmt::Display>(err: E) -> Option<T> { impl Errors for LambdaShell {
shell_error(err); fn error<E: fmt::Display>(&mut self, err: E) {
None shell_error(err);
self.terminate = true;
}
} }
#[derive(Debug, Clone)] trait Signals {
pub struct VmConfig { fn sigterm_event(&mut self);
pub sandbox: bool, fn input(&mut self);
pub jit: bool,
} }
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)] #[derive(Debug, Clone)]
pub struct Config { pub struct Config {
pub norc: bool, pub norc: bool
pub vm: VmConfig,
} }
#[derive(Debug, Clone)] pub struct LambdaShell {
pub struct Input { terminate: bool,
pub literal: String, history: History,
pub cursor: u16, config: Config,
vm: LuauVm,
ps: Arc<Mutex<Ps>>,
} }
pub struct Rt { impl LambdaShell {
pub input: Input,
pub ps: Rc<RefCell<String>>,
pub vm: Luau,
pub history: History,
}
pub struct Pse {
pub config: Config,
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 rt = Rt { let ps = Arc::new(Mutex::new(Ps::set(ps::DEFAULT_PS.to_owned())));
ps: Rc::new(RefCell::new(Self::DEFAULT_PS.to_owned())), Self {
vm: Luau::new(), ps: Arc::clone(&ps),
vm: vm::LuauVm::new(ps),
history: History::init(), history: History::init(),
input: Input { terminate: false,
literal: String::new(), config,
cursor: u16::MIN, }
},
};
Self { rt, 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 !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.term_input_processor().map_or_display(|()| self.rt.history.write_to_file_fallible()) self.ps.borrow().display();
self.sigterm_event();
self.input();
} }
} }

View File

@ -1,218 +0,0 @@
use crossterm::{cursor, event::{self, Event, KeyCode, KeyEvent, KeyModifiers}, execute, terminal};
use core::fmt;
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("Sigint")]
Sigint,
#[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>;
#[allow(dead_code)]
fn debug<S: fmt::Display>(s: S) {
terminal::disable_raw_mode().unwrap();
println!("{s}");
terminal::enable_raw_mode().unwrap()
}
trait SpecificKeybinds {
const EXIT_ID_1: &str;
const KEY_SPACE: char;
fn key_literal(&mut self, keycode: KeyCode) -> InputResult<()>;
fn key_ctrl(&mut self, input_key: KeyEvent, keycode: KeyCode) -> InputResult<()>;
fn key_enter(&mut self) -> InputResult<()>;
fn key_backspace(&mut self) -> InputResult<()>;
fn key_arrow_right(&mut self) -> InputResult<()>;
fn key_arrow_left(&mut self) -> InputResult<()>;
fn key_arrow_up(&mut self) -> InputResult<()>;
fn key_arrow_down(&mut self) -> InputResult<()>;
}
impl SpecificKeybinds for Pse {
const EXIT_ID_1: &str = "exit";
const KEY_SPACE: char = ' ';
fn key_literal(&mut self, keycode: KeyCode) -> InputResult<()> {
match keycode {
KeyCode::Char(Self::KEY_SPACE) => self.term_render(Self::KEY_SPACE.to_string()),
keycode => self.term_render(keycode.to_string())
}
}
fn key_ctrl(&mut self, input_key: KeyEvent, keycode: KeyCode) -> InputResult<()> {
match input_key.modifiers.contains(KeyModifiers::CONTROL) {
true => match keycode {
KeyCode::Char('c') => Err(InputHandleError::Sigint),
KeyCode::Char('r') => unimplemented!(),
_ => Ok(())
},
false => self.key_literal(keycode)
}
}
fn key_enter(&mut self) -> InputResult<()> {
if self.rt.input.literal == Self::EXIT_ID_1 { return Err(InputHandleError::UserExit) };
terminal::disable_raw_mode().map_err(InputHandleError::DisableRaw)?;
println!();
self.spawn_sys_cmd();
self.rt.input.literal.clear();
self.rt.input.cursor = u16::MIN;
self.term_render_ps()
}
fn key_backspace(&mut self) -> InputResult<()> {
if self.rt.input.literal.pop().is_some() {
execute!(
io::stdout(),
cursor::MoveLeft(1),
terminal::Clear(terminal::ClearType::UntilNewLine)
).map_err(InputHandleError::Flush)?;
self.rt.input.cursor-=1;
}
Ok(())
}
fn key_arrow_right(&mut self) -> InputResult<()> {
match self.term_input_cursor_move_right() {
Some(()) => execute!(io::stdout(), cursor::MoveRight(1)).map_err(InputHandleError::Flush),
None => Ok(())
}
}
fn key_arrow_left(&mut self) -> InputResult<()> {
match self.term_input_cursor_move_left() {
Some(()) => execute!(io::stdout(), cursor::MoveLeft(1)).map_err(InputHandleError::Flush),
None => Ok(())
}
}
fn key_arrow_up(&mut self) -> InputResult<()> {
self.rt.history.index += 1;
if self.rt.history.index != self.rt.history.history.len() as isize {
self.term_render_reset()?;
self.term_render(self.rt.history.history[self.rt.history.index as usize].clone())?;
}
Ok(())
}
fn key_arrow_down(&mut self) -> InputResult<()> {
self.rt.history.index -= 1;
if self.rt.history.index != -1 {
self.term_render_reset()?;
self.term_render(self.rt.history.history[self.rt.history.index as usize].clone())?;
}
Ok(())
}
}
pub trait TermInputCursor {
fn term_input_cursor_move_left(&mut self) -> Option<()>;
fn term_input_cursor_move_right(&mut self) -> Option<()>;
}
impl TermInputCursor for Pse {
fn term_input_cursor_move_left(&mut self) -> Option<()> {
if self.rt.input.cursor == u16::MIN { None } else {
match self.rt.input.cursor>u16::MIN {
true => { self.rt.input.cursor-=1; Some(()) }
false => None
}
}
}
fn term_input_cursor_move_right(&mut self) -> Option<()> {
if self.rt.input.cursor == u16::MAX { None } else {
match self.rt.input.cursor<self.rt.input.literal.chars().count() as u16 {
true => { self.rt.input.cursor+=1; Some(()) },
false => None
}
}
}
}
pub trait TermProcessor {
fn term_render(&mut self, def_string: String) -> InputResult<()>;
fn term_render_ps(&self) -> InputResult<()>;
fn term_render_reset(&mut self) -> 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, text: String) -> InputResult<()> {
self.rt.input.literal.insert_str(self.rt.input.cursor.into(), &text);
let input_literal_size = self.rt.input.literal.chars().count() as u16;
self.rt.input.cursor = input_literal_size;
if self.rt.input.cursor != input_literal_size {
execute!(io::stdout(), terminal::Clear(terminal::ClearType::UntilNewLine)).map_err(InputHandleError::Flush)?;
let slice = &self.rt.input.literal[(self.rt.input.cursor as usize)..];
write!(io::stdout(), "{text}{slice}").map_err(InputHandleError::Write)?;
} else {
write!(io::stdout(), "{text}").map_err(InputHandleError::Write)?;
}
io::stdout().flush().map_err(InputHandleError::Flush)
}
fn term_render_ps(&self) -> InputResult<()> {
print!("{}", self.rt.ps.borrow());
io::stdout().flush().map_err(InputHandleError::Flush)
}
fn term_render_reset(&mut self) -> InputResult<()> {
execute!(io::stdout(), cursor::MoveLeft(self.rt.input.cursor)).map_err(InputHandleError::Flush)?;
self.rt.input.cursor = u16::MIN;
self.rt.input.literal.clear();
execute!(io::stdout(), terminal::Clear(terminal::ClearType::UntilNewLine)).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 => self.key_arrow_right(),
KeyCode::Left => self.key_arrow_left(),
KeyCode::Up => self.key_arrow_up(),
KeyCode::Down => self.key_arrow_down(),
keycode => self.key_ctrl(input_key, keycode)
};
input_handle.map_or_else(|inp_err| match inp_err {
InputHandleError::UserExit => None,
InputHandleError::Sigint => self.term_render("^C".to_owned()).ok(),
input_err => session::shell_error_none(input_err)
}, Some)
}
fn term_input_mainthread(&mut self) -> io::Result<()> {
execute!(io::stdout(), event::EnableBracketedPaste)?;
self.term_render_ps().map_or_else(|_| Ok(()), |()| {
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()?;
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 std::{cell::RefCell, rc::Rc};
use core::fmt; use core::fmt;
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,25 @@ 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; fn global_warn(&self, luau_globals: &Table) -> lResult<()>;
fn vm_glob_warn(&self, luau_globals: &Table) -> lResult<()>; fn global_version(&self, luau_globals: &Table) -> lResult<()>;
fn vm_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 CONV_ERROR: &str = "<SHELL CONVERSION ERROR>"; 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")?; 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 +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")?; 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 { pub struct LuauVm {
fn vm_setglobs(&self) -> lResult<()>; vm: Luau,
fn vm_exec(&self, source: String); ps: Rc<RefCell<Ps>>
} }
impl LuauVm for Pse { impl LuauVm {
fn vm_setglobs(&self) -> lResult<()> { pub(crate) fn new(ps: Rc<RefCell<Ps>>) -> Self {
let luau_globals = self.rt.vm.globals(); Self { vm: Luau::new(), ps }
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.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.set_shell_globals().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, vm::LuauVm};
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,18 +19,17 @@ 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, (tindex, tvalue): (String, String)| -> lResult<()> {
if t_index == "PROMPT" { if tindex == "PROMPT" {
let mut prompt = this.0.borrow_mut(); this.0.borrow_mut().modify(tvalue);
*prompt = t_value;
} }
Ok(()) Ok(())
}); });
@ -38,10 +37,11 @@ impl UserData for Shell {
} }
pub trait ShellGlobal { pub trait ShellGlobal {
fn vm_glob_shell(&self, luau_globals: &Table) -> lResult<()>; fn global_shell(&self, luau_globals: &Table) -> lResult<()>;
} }
impl ShellGlobal for Pse { impl ShellGlobal for LuauVm {
fn vm_glob_shell(&self, luau_globals: &Table) -> lResult<()> { fn global_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)+) => {
@ -39,7 +39,6 @@ fn text_styles_funcs(luau: &Luau) -> lResult<(Table, Table)> {
underline_grey underline_black underline_green underline_yellow underline_grey underline_black underline_green underline_yellow
underline_blue underline_magenta underline_cyan underline_white underline_blue underline_magenta underline_cyan underline_white
bold bold
crossed_out
); );
background_styles_luau!(luau, background_table, background_styles_luau!(luau, background_table,
on_dark_grey on_dark_red on_dark_green on_dark_cyan on_dark_grey on_dark_red on_dark_green on_dark_cyan
@ -85,10 +84,10 @@ impl UserData for Terminal {
} }
pub trait TerminalGlobal { pub trait TerminalGlobal {
fn vm_glob_terminal(&self, luau_globals: &Table) -> lResult<()>; fn global_terminal(&self, luau_globals: &Table) -> lResult<()>;
} }
impl TerminalGlobal for Pse { impl TerminalGlobal for LuauVm {
fn vm_glob_terminal(&self, luau_globals: &Table) -> lResult<()> { fn global_terminal(&self, luau_globals: &Table) -> lResult<()> {
luau_globals.raw_set("TERMINAL", Terminal) luau_globals.raw_set("TERMINAL", Terminal)
} }
} }