10 Commits

15 changed files with 416 additions and 273 deletions

67
Cargo.lock generated
View File

@ -16,9 +16,9 @@ checksum = "b048fb63fd8b5923fc5aa7b340d8e156aec7ec02f0c78fa8a6ddc2613f6f71de"
[[package]] [[package]]
name = "bstr" name = "bstr"
version = "1.11.1" version = "1.11.3"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "786a307d683a5bf92e6fd5fd69a7eb613751668d1d8d67d802846dfe367c62c8" checksum = "531a9155a481e2ee699d4f98f43c0ca4ff8ee1bfd55c31e9e98fb29d2b176fe0"
dependencies = [ dependencies = [
"memchr", "memchr",
"serde", "serde",
@ -32,9 +32,9 @@ checksum = "79296716171880943b8470b5f8d03aa55eb2e645a4874bdbb28adb49162e012c"
[[package]] [[package]]
name = "cc" name = "cc"
version = "1.2.6" version = "1.2.7"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "8d6dbb628b8f8555f86d0323c2eb39e3ec81901f4b83e091db8a6a76d316a333" checksum = "a012a0df96dd6d06ba9a1b29d6402d1a5d77c6befd2566afdc26e10603dc93d7"
dependencies = [ dependencies = [
"shlex", "shlex",
] ]
@ -73,6 +73,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "126f97965c8ad46d6d9163268ff28432e8f6a1196a55578867832e3049df63dd" checksum = "126f97965c8ad46d6d9163268ff28432e8f6a1196a55578867832e3049df63dd"
dependencies = [ dependencies = [
"const_format_proc_macros", "const_format_proc_macros",
"konst",
] ]
[[package]] [[package]]
@ -146,6 +147,21 @@ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "konst"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "330f0e13e6483b8c34885f7e6c9f19b1a7bd449c673fbb948a51c99d66ef74f4"
dependencies = [
"konst_macro_rules",
]
[[package]]
name = "konst_macro_rules"
version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a4933f3f57a8e9d9da04db23fb153356ecaf00cbd14aee46279c33dc80925c37"
[[package]] [[package]]
name = "libc" name = "libc"
version = "0.2.169" version = "0.2.169"
@ -198,6 +214,25 @@ version = "0.4.22"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24" checksum = "a7a70ba024b9dc04c27ea2f0c0548feb474ec5c54bba33a7f72f873a39d07b24"
[[package]]
name = "lua-src"
version = "547.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1edaf29e3517b49b8b746701e5648ccb5785cde1c119062cbabbc5d5cd115e42"
dependencies = [
"cc",
]
[[package]]
name = "luajit-src"
version = "210.5.11+97813fb"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3015551c284515db7c30c559fc1080f9cb9ee990d1f6fca315451a107c7540bb"
dependencies = [
"cc",
"which",
]
[[package]] [[package]]
name = "luau0-src" name = "luau0-src"
version = "0.11.2+luau653" version = "0.11.2+luau653"
@ -254,6 +289,8 @@ checksum = "63a11d485edf0f3f04a508615d36c7d50d299cf61a7ee6d3e2530651e0a31771"
dependencies = [ dependencies = [
"cc", "cc",
"cfg-if", "cfg-if",
"lua-src",
"luajit-src",
"luau0-src", "luau0-src",
"pkg-config", "pkg-config",
] ]
@ -428,9 +465,9 @@ checksum = "3c5e1a9a646d36c3599cd173a41282daf47c44583ad367b8e6837255952e5c67"
[[package]] [[package]]
name = "syn" name = "syn"
version = "2.0.94" version = "2.0.95"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "987bc0be1cdea8b10216bd06e2ca407d40b9543468fafd3ddfb02f36e77f71f3" checksum = "46f71c0377baf4ef1cc3e3402ded576dccc315800fbc62dfc7fe04b009773b4a"
dependencies = [ dependencies = [
"proc-macro2", "proc-macro2",
"quote", "quote",
@ -555,6 +592,18 @@ dependencies = [
"wasm-bindgen", "wasm-bindgen",
] ]
[[package]]
name = "which"
version = "6.0.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b4ee928febd44d98f2f459a4a79bd4d928591333a494a10a868418ac1b39cf1f"
dependencies = [
"either",
"home",
"rustix",
"winsafe",
]
[[package]] [[package]]
name = "whoami" name = "whoami"
version = "1.5.2" version = "1.5.2"
@ -669,3 +718,9 @@ name = "windows_x86_64_msvc"
version = "0.52.6" version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index" source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
[[package]]
name = "winsafe"
version = "0.0.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d135d17ab770252ad95e9a872d365cf3090e3be864a34ab46f48555993efc904"

View File

@ -5,10 +5,10 @@ edition = "2021"
[dependencies] [dependencies]
color-print = "0.3.7" color-print = "0.3.7"
const_format = "0.2.33" const_format = { version = "0.2.34", features = ["rust_1_64"] }
crossterm = "0.28.1" crossterm = "0.28.1"
home = "0.5.9" home = "0.5.9"
mlua = { version = "0.10.0", features = ["luau-jit"] } 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"

21
LICENSE Normal file
View File

@ -0,0 +1,21 @@
MIT License
Copyright (c) 2025 rhpidfyre
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@ -6,16 +6,13 @@ use std::{
path::{Path, PathBuf}, path::{Path, PathBuf},
}; };
use crate::MapDisplay;
enum ValidStatus { enum ValidStatus {
NoRootFolder, NoRootFolder,
TryExists(io::Error) TryExists(io::Error)
} }
fn display_none<T>(e: io::Error) -> Option<T> {
println!("{e}");
None
}
trait PathBufIsValid { trait PathBufIsValid {
fn is_valid(&self) -> Result<PathBuf, ValidStatus>; fn is_valid(&self) -> Result<PathBuf, ValidStatus>;
fn is_valid_or_home(&self) -> Option<PathBuf>; fn is_valid_or_home(&self) -> Option<PathBuf>;
@ -55,7 +52,7 @@ impl PathBufIsValid for PathBuf {
impl ChangeDirectory for Command { impl ChangeDirectory for Command {
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_else(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()))
} }
fn home_dir(&self) -> Option<PathBuf> { fn home_dir(&self) -> Option<PathBuf> {
@ -127,7 +124,7 @@ impl Command {
} }
pub fn spawn(&self, command_process: io::Result<process::Child>) { pub fn spawn(&self, command_process: io::Result<process::Child>) {
command_process.map_or_else(display_none, |mut child| Some(child.wait())); command_process.map_or_display_none(|mut child| Some(child.wait()));
} }
pub fn exec(&self) { pub fn exec(&self) {

View File

@ -1,15 +1,22 @@
pub const VERSION: &str = env!("CARGO_PKG_VERSION"); pub mod session;
pub mod commands;
pub mod ps;
pub mod rc;
pub mod vm;
pub mod shell; pub trait MapDisplay<T, E: std::fmt::Display> {
mod commands; fn map_or_display<F: FnOnce(T)>(self, f: F);
mod ps; fn map_or_display_none<R, F: FnOnce(T) -> Option<R>>(self, f: F) -> Option<R>;
mod rc; }
impl<T, E: std::fmt::Display> MapDisplay<T, E> for Result<T, E> {
#[path = "./luau/vm.rs"] ///Map and display an error
mod vm; #[inline]
#[path = "./luau/alias.rs"] fn map_or_display<F: FnOnce(T)>(self, f: F) {
mod alias; self.map_or_else(|e| color_print::ceprintln!("<bold,r>[!]:</> {e}"), f)
#[path = "./luau/terminal.rs"] }
mod terminal; ///Map and display an error but return `None`
#[path = "./luau/system.rs"] #[inline]
mod sytem; fn map_or_display_none<R, F: FnOnce(T) -> Option<R>>(self, f: F) -> Option<R> {
self.map_or_else(|e| { color_print::ceprintln!("<bold,r>[!]:</> {e}"); None }, f)
}
}

View File

@ -1,31 +0,0 @@
use mlua::{Result as lResult, Table};
use whoami::fallible;
use crate::vm::Vm;
const DEFAULT_HOSTNAME: &str = "hostname";
pub trait System {
fn details(&self, shell: &Table) -> lResult<()>;
fn global_shell(&self) -> lResult<()>;
}
impl System for Vm {
fn details(&self, shell: &Table) -> lResult<()> {
let system = self.0.create_table()?;
system.set("DESKTOP_ENV", whoami::desktop_env().to_string())?;
system.set("DEVICENAME", whoami::devicename().to_string())?;
system.set("USERNAME", whoami::username().to_string())?;
system.set("REALNAME", whoami::realname().to_string())?;
system.set("PLATFORM", whoami::platform().to_string())?;
system.set("DISTRO", whoami::distro().to_string())?;
system.set("HOSTNAME", fallible::hostname().unwrap_or(DEFAULT_HOSTNAME.to_owned()))?;
shell.set("SYSTEM", system)?;
Ok(())
}
fn global_shell(&self) -> lResult<()> {
let shell = self.0.create_table()?;
self.details(&shell)?;
self.0.globals().set("SHELL", shell)?;
Ok(())
}
}

View File

@ -1,80 +0,0 @@
use mlua::{Result as lResult, Table};
use crossterm::style::Stylize;
use crate::vm::Vm;
macro_rules! foreground_styles_luau {
($self:expr, $style_table:expr, $($color:ident)+) => {
$(
$style_table.set(stringify!($color).to_ascii_uppercase(), $self.0.create_function(|_, text: String| -> lResult<String> {
Ok(text.$color().to_string())
})?)?;
)+
};
}
macro_rules! background_styles_luau {
($self:expr, $style_table:expr, $($color:ident)+) => {
$(
match stringify!($color).split_once("_") {
Some((_, color_name)) => $style_table.set(color_name.to_ascii_uppercase(), $self.0.create_function(|_, text: String| -> lResult<String> {
Ok(text.$color().to_string())
})?)?,
None => panic!("Luau set error: {:?}. There was nothing to split from delimiter: \"_\"", stringify!($color)),
}
)+
};
}
pub trait TerminalColors {
fn background(&self, style_table: &Table) -> lResult<()>;
fn foreground(&self, style_table: &Table) -> lResult<()>;
fn styling(&self) -> lResult<Table>;
fn terminal(&self) -> lResult<()>;
}
impl TerminalColors for Vm {
fn background(&self, style_table: &Table) -> lResult<()> {
let foreground_table = self.0.create_table()?;
foreground_styles_luau!(self, foreground_table,
dark_grey dark_red dark_green dark_cyan
dark_yellow dark_magenta dark_blue
red grey black green yellow
blue magenta cyan white
underlined
underline_dark_grey underline_dark_red underline_dark_green underline_dark_cyan
underline_dark_yellow underline_dark_magenta underline_dark_blue underline_red
underline_grey underline_black underline_green underline_yellow
underline_blue underline_magenta underline_cyan underline_white
bold
);
style_table.set("FOREGROUND", foreground_table)?;
Ok(())
}
fn foreground(&self, style_table: &Table) -> lResult<()> {
let background_table = self.0.create_table()?;
background_styles_luau!(self, background_table,
on_dark_grey on_dark_red on_dark_green on_dark_cyan
on_dark_yellow on_dark_magenta on_dark_blue
on_red on_grey on_black
on_green on_yellow
on_blue on_magenta
on_cyan on_white
);
style_table.set("BACKGROUND", background_table)?;
Ok(())
}
fn styling(&self) -> lResult<Table> {
let style_table = self.0.create_table()?;
self.foreground(&style_table)?;
self.background(&style_table)?;
Ok(style_table)
}
fn terminal(&self) -> lResult<()> {
let term_table = self.0.create_table()?;
term_table.set("OUT", self.styling()?)?;
self.0.globals().set("TERMINAL", &term_table)?;
Ok(())
}
}

View File

@ -1,52 +0,0 @@
use mlua::{
Lua as Luau,
Result as lResult
};
use crate::VERSION;
use crate::terminal::TerminalColors;
use crate::sytem::System;
use core::fmt;
use color_print::cprintln;
fn display_none<T, E: fmt::Display>(err: E) -> Option<T> {
println!("{err}");
None
}
fn luau_error<T>(err: mlua::Error) -> Option<T> {
cprintln!("<bold>====</>\n<r><bold>[!]</> {err}</>\n<bold>====</>");
None
}
trait Globals {
fn version(&self) -> lResult<()>;
}
impl Globals for Vm {
fn version(&self) -> lResult<()> {
let luau_info = self.0.globals().get::<String>("_VERSION")?;
self.0.globals().set("_VERSION", format!("{}, liblambdashell {}", luau_info, VERSION))
}
}
pub struct Vm(pub Luau);
impl Vm {
pub fn new() -> Self {
Self(Luau::new())
}
fn set_shell_globals(&self) -> mlua::Result<()> {
self.version()?;
self.terminal()?;
self.global_shell()?;
self.0.globals().set("getfenv", mlua::Nil)?;
self.0.globals().set("setfenv", mlua::Nil)?;
self.0.sandbox(true)?;
Ok(())
}
pub fn exec(&self, source: String) {
self.set_shell_globals().map_or_else(display_none, |()| {
self.0.load(source).exec().map_or_else(luau_error, Some)
});
}
}

View File

@ -1,9 +1,12 @@
use const_format::formatcp; pub const DEFAULT_PS: &str = concat!("lambdashell-", env!("CARGO_PKG_VERSION"));
use color_print::{cformat, cprint};
pub const DEFAULT_PS: &str = formatcp!("lambdashell-{}", env!("CARGO_PKG_VERSION")); pub struct Ps(String);
impl Ps {
pub fn set(prompt: String) -> Self {
Self(prompt)
}
pub fn working_dir_name() -> String { pub fn working_dir_name(&self) -> String {
std::env::current_dir().map_or("?".to_owned(), |path| { std::env::current_dir().map_or("?".to_owned(), |path| {
path.file_name().map_or("?".to_owned(), |name| { path.file_name().map_or("?".to_owned(), |name| {
let name_os_string = name.to_os_string(); let name_os_string = name.to_os_string();
@ -15,7 +18,7 @@ pub fn working_dir_name() -> String {
}) })
} }
pub fn display(ps1: &String) { pub fn display(&self) {
let working_dir_name = cformat!(" <bold>{}</> ", working_dir_name()); print!("{}", self.0);
cprint!("{}{}λ ", ps1, working_dir_name); }
} }

View File

@ -1,9 +1,13 @@
use std::{fs::{self, File}, io::{self, Write}, path::PathBuf}; use std::{path::PathBuf, fs::{self, File}, io::{self, Write}};
use thiserror::Error; use thiserror::Error;
use crate::MapDisplay;
pub const DEFAULT_CONFIG_CONTENT: &str = r#"--!strict pub const DEFAULT_CONFIG_CONTENT: &str = r#"--!strict
local username = SHELL.SYSTEM.USERNAME local cyan = TERMINAL.OUT.FOREGROUND.CYAN
local username = cyan(SHELL.SYSTEM.USERNAME)
local hostname = SHELL.SYSTEM.HOSTNAME local hostname = SHELL.SYSTEM.HOSTNAME
SHELL.PROMPT = `{username}@{hostname} λ `"#; SHELL.PROMPT = `{username}@{hostname} λ `"#;
@ -25,11 +29,6 @@ enum CreateErr {
Passable Passable
} }
fn display_none<T>(e: io::Error) -> Option<T> {
println!("{e}");
None
}
#[allow(dead_code)] #[allow(dead_code)]
trait IsValid { trait IsValid {
fn is_valid(&self, is_dir_or_file: bool) -> Result<PathBuf, IsValidDirErr>; fn is_valid(&self, is_dir_or_file: bool) -> Result<PathBuf, IsValidDirErr>;
@ -43,10 +42,7 @@ trait IsValid {
impl IsValid for PathBuf { impl IsValid for PathBuf {
fn is_valid(&self, is_content: bool) -> Result<PathBuf, IsValidDirErr> { fn is_valid(&self, is_content: bool) -> Result<PathBuf, IsValidDirErr> {
match self.try_exists() { match self.try_exists() {
Ok(true) => match is_content { Ok(true) => if is_content { Ok(self.to_path_buf()) } else { Err(IsValidDirErr::NotAnEntry) },
true => Ok(self.to_path_buf()),
false => Err(IsValidDirErr::NotAnEntry)
},
Ok(false) => Err(IsValidDirErr::Missing), Ok(false) => Err(IsValidDirErr::Missing),
Err(try_e) => Err(IsValidDirErr::TryExists(try_e)) Err(try_e) => Err(IsValidDirErr::TryExists(try_e))
} }
@ -56,37 +52,24 @@ impl IsValid for PathBuf {
where where
F: FnOnce() -> Option<PathBuf> F: FnOnce() -> Option<PathBuf>
{ {
let possible_content = self.is_valid(is_content).map_err(|e| match e { self.is_valid(is_content).map_err(|e| match e {
IsValidDirErr::TryExists(try_e) => CreateErr::TryExists(try_e), IsValidDirErr::TryExists(try_e) => CreateErr::TryExists(try_e),
IsValidDirErr::NotAnEntry | IsValidDirErr::Missing => CreateErr::Passable IsValidDirErr::NotAnEntry | IsValidDirErr::Missing => CreateErr::Passable
}); }).map_or_else(|e| match e {
match possible_content {
Ok(p) => Some(p),
Err(e) => match e {
CreateErr::TryExists(_) => None, CreateErr::TryExists(_) => None,
CreateErr::Passable => f() CreateErr::Passable => f()
}, }, Some)
}
} }
fn is_valid_dir_or_create(&self) -> Option<PathBuf> { fn is_valid_dir_or_create(&self) -> Option<PathBuf> {
self.is_valid_or(self.is_dir(), || { self.is_valid_or(self.is_dir(), || fs::create_dir(self).map_or_display_none(|()| Some(self.to_path_buf())))
match fs::create_dir(self) {
Ok(()) => Some(self.to_path_buf()),
Err(create_e) => display_none(create_e),
}
})
} }
fn is_valid_file_or_create(&self, default_file_bytes: &[u8]) -> Option<PathBuf> { fn is_valid_file_or_create(&self, default_file_bytes: &[u8]) -> Option<PathBuf> {
self.is_valid_or(self.is_file(), || { self.is_valid_or(self.is_file(), || {
match File::create(self) { File::create(self).map_or_display_none(|mut file| {
Ok(mut file) => match file.write_all(default_file_bytes) { file.write_all(default_file_bytes).map_or_display_none(|()| Some(self.to_path_buf()))
Ok(()) => Some(self.to_path_buf()), })
Err(write_e) => display_none(write_e),
},
Err(create_e) => display_none(create_e)
}
}) })
} }
@ -98,14 +81,14 @@ impl IsValid for PathBuf {
pub fn config_dir() -> Option<PathBuf> { 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_option(config.is_dir())?; config.is_valid_dir_or_create()?;
config.push("lambdashell"); config.push("lambdashell");
config.is_valid_dir_or_create() config.is_valid_dir_or_create()
} }
pub fn config_file() -> Option<PathBuf> { pub fn config_file() -> Option<PathBuf> {
let mut config_file = config_dir()?; let mut config_file = config_dir()?;
config_file.push("config.luau"); config_file.push("init.luau");
config_file.is_valid_file_or_create(DEFAULT_CONFIG_CONTENT.as_bytes()) config_file.is_valid_file_or_create(DEFAULT_CONFIG_CONTENT.as_bytes())
} }

View File

@ -1,20 +1,19 @@
use crate::{ps, commands, rc, vm};
use std::{fs, io::{self}}; use std::{fs, io::{self}};
use crate::{
vm::{LuauVm, self},
commands,
ps,
rc,
MapDisplay,
};
pub struct Config { pub struct Config {
pub norc: bool pub norc: bool
} }
trait ShellLuauVm {
fn shell_vm_exec(&self, source: String);
}
impl ShellLuauVm for LambdaShell {
fn shell_vm_exec(&self, source: String) {
vm::Vm::new().exec(source);
}
}
pub struct LambdaShell { pub struct LambdaShell {
vm: LuauVm,
ps1: String, ps1: String,
config: Config, config: Config,
terminating: bool, terminating: bool,
@ -22,6 +21,7 @@ pub struct LambdaShell {
impl LambdaShell { impl LambdaShell {
pub fn create(config: Config) -> Self { pub fn create(config: Config) -> Self {
Self { Self {
vm: vm::LuauVm::new(),
ps1: ps::DEFAULT_PS.to_owned(), ps1: ps::DEFAULT_PS.to_owned(),
terminating: false, terminating: false,
config, config,
@ -31,7 +31,7 @@ impl LambdaShell {
pub fn wait(&mut self) -> Result<(), io::Error> { pub fn wait(&mut self) -> Result<(), io::Error> {
io::Write::flush(&mut io::stdout()).map(|()| { io::Write::flush(&mut io::stdout()).map(|()| {
let mut input = String::new(); let mut input = String::new();
io::stdin().read_line(&mut input).map_or_else(|read_error| println!("{read_error}"), |_size| { io::stdin().read_line(&mut input).map_or_display(|_size| {
match input.trim() { match input.trim() {
//special casey //special casey
"exit" => self.terminating = true, "exit" => self.terminating = true,
@ -41,31 +41,28 @@ impl LambdaShell {
}) })
} }
fn rc_parse(&self) { pub fn vm_exec(&self, source: String) {
if !self.config.norc { self.vm.exec(source);
if let Some(conf_file) = rc::config_file() {
match fs::read_to_string(conf_file) {
Ok(luau_conf) => self.shell_vm_exec(luau_conf),
Err(read_err) => println!("{read_err}"),
}
}
}
} }
pub fn start(&mut self) { pub fn start(&mut self) {
self.rc_parse(); if !self.config.norc {
if let Some(conf_file) = rc::config_file() {
ps::display(&self.ps1); fs::read_to_string(conf_file).map_or_display(|luau_conf| self.vm_exec(luau_conf));
}
}
loop { loop {
match self.terminating { match self.terminating {
true => break, true => break,
false => match self.wait() { false => {
Ok(()) => ps::display(&self.ps1),
match self.wait() {
Ok(()) => {},
Err(flush_error) => { Err(flush_error) => {
println!("{flush_error}"); println!("{flush_error}");
break; break;
} }
}
}, },
} }
} }

74
src/vm/mod.rs Normal file
View File

@ -0,0 +1,74 @@
use mlua::{Function, Lua as Luau, MultiValue, Result as lResult, Table, Value};
use color_print::{cformat, ceprintln};
use core::fmt;
use shell::Shell;
use crate::{vm::terminal::Terminal, MapDisplay};
mod shell;
mod terminal;
mod alias;
trait LuauRuntimeErr<T> {
fn map_or_luau_rt_err<R, F: FnOnce(T) -> Option<R>>(self, f: F) -> Option<R>;
}
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| {
ceprintln!("<bold>====</>\n<r><bold>[!]:</> {luau_rt_err}</>\n<bold>====</>");
None
}, f)
}
}
trait Globals {
const LIB_VERSION: &str;
fn global_warn(&self, luau_globals: &Table) -> lResult<()>;
fn global_version(&self, luau_globals: &Table) -> lResult<()>;
}
impl Globals for LuauVm {
const LIB_VERSION: &str = env!("CARGO_PKG_VERSION");
fn global_warn(&self, luau_globals: &Table) -> lResult<()> {
let luau_print = luau_globals.get::<Function>("print")?;
luau_globals.set("warn", self.0.create_function(move |this, args: MultiValue| -> lResult<()> {
let luau_multi_values = args.into_iter()
.map(|value| cformat!("<bold,y>{}</>", value.to_string().unwrap_or("<SHELL CONVERSION ERROR>".to_owned())))
.map(|arg_v| Value::String(this.create_string(arg_v).unwrap()))
.collect::<MultiValue>();
luau_print.call::<()>(luau_multi_values).unwrap();
Ok(())
})?)
}
fn global_version(&self, luau_globals: &Table) -> lResult<()> {
let luau_info = luau_globals.get::<String>("_VERSION")?;
luau_globals.set("_VERSION", format!("{luau_info}, liblambdashell {}", Self::LIB_VERSION))
}
}
pub struct LuauVm(pub Luau);
impl LuauVm {
pub(crate) fn new() -> Self {
Self(Luau::new())
}
fn set_shell_globals(&self) -> lResult<()> {
let luau_globals = self.0.globals();
self.global_warn(&luau_globals)?;
self.global_version(&luau_globals)?;
self.global_terminal(&luau_globals)?;
self.global_shell(&luau_globals)?;
luau_globals.set("getfenv", mlua::Nil)?;
luau_globals.set("setfenv", mlua::Nil)?;
self.0.sandbox(true)?;
Ok(())
}
pub fn exec(&self, source: String) {
self.set_shell_globals().map_or_display_none(|()| {
self.0.load(source).exec().map_or_luau_rt_err(Some)
});
}
}

57
src/vm/shell.rs Normal file
View File

@ -0,0 +1,57 @@
use mlua::{Result as lResult, Table, Value};
use whoami::fallible;
use crate::vm::LuauVm;
const DEFAULT_HOSTNAME: &str = "hostname";
trait PsPrompt {
fn ps_prompt(&self) -> lResult<Table>;
}
impl PsPrompt for LuauVm {
fn ps_prompt(&self) -> lResult<Table> {
let prompt_table = self.0.create_table()?;
let prompt_metatable = self.0.create_table()?;
prompt_metatable.set("__index", self.0.create_function(|_, (table, index): (Table, Value)| -> lResult<String> {
table.raw_get::<String>(index)
})?)?;
prompt_metatable.set("__newindex", self.0.create_function(|_, _: String| -> lResult<String> {
Ok("placeholder".to_owned())
})?)?;
prompt_table.set("__metatable", mlua::Nil)?;
prompt_table.set_metatable(Some(prompt_metatable));
prompt_table.set_readonly(false);
Ok(prompt_table)
}
}
trait System {
fn sys_details(&self) -> lResult<Table>;
}
impl System for LuauVm {
fn sys_details(&self) -> lResult<Table> {
let system = self.0.create_table()?;
system.set("DESKTOP_ENV", whoami::desktop_env().to_string())?;
system.set("DEVICENAME", whoami::devicename().to_string())?;
system.set("USERNAME", whoami::username().to_string())?;
system.set("REALNAME", whoami::realname().to_string())?;
system.set("PLATFORM", whoami::platform().to_string())?;
system.set("DISTRO", whoami::distro().to_string())?;
system.set("HOSTNAME", fallible::hostname().unwrap_or(DEFAULT_HOSTNAME.to_owned()))?;
Ok(system)
}
}
pub trait Shell {
fn global_shell(&self, luau_globals: &Table) -> lResult<()>;
}
impl Shell for LuauVm {
fn global_shell(&self, luau_globals: &Table) -> lResult<()> {
let shell = self.0.create_table()?;
let ps_prompt = self.ps_prompt()?;
shell.set("SYSTEM", self.sys_details()?)?;
shell.set("PROMPT", ps_prompt)?;
luau_globals.set("SHELL", shell)?;
Ok(())
}
}

112
src/vm/terminal.rs Normal file
View File

@ -0,0 +1,112 @@
use mlua::{Function, Result as lResult, Table};
use const_format::str_split;
use crossterm::style::Stylize;
use crate::vm::LuauVm;
macro_rules! foreground_styles_luau {
($self:expr, $style_table:expr, $($color:ident)+) => {
$(
$style_table.set(stringify!($color).to_ascii_uppercase(), $self.0.create_function(|_, text: String| -> lResult<String> {
Ok(text.$color().to_string())
})?)?;
)+
};
}
macro_rules! background_styles_luau {
($self:expr, $style_table:expr, $($color:ident)+) => {
$(
$style_table.set(
str_split!(stringify!($color), "_")[1..].join("_").to_ascii_uppercase(),
$self.0.create_function(|_, text: String| -> lResult<String> {
Ok(text.$color().to_string())
})?)?;
)+
};
}
trait Colors {
fn background(&self, term_out_table: &Table) -> lResult<()>;
fn foreground(&self, term_out_table: &Table) -> lResult<()>;
}
impl Colors for LuauVm {
fn background(&self, term_out_table: &Table) -> lResult<()> {
let foreground_table = self.0.create_table()?;
foreground_styles_luau!(self, foreground_table,
dark_grey dark_red dark_green dark_cyan
dark_yellow dark_magenta dark_blue
red grey black green yellow
blue magenta cyan white
underlined
underline_dark_grey underline_dark_red underline_dark_green underline_dark_cyan
underline_dark_yellow underline_dark_magenta underline_dark_blue underline_red
underline_grey underline_black underline_green underline_yellow
underline_blue underline_magenta underline_cyan underline_white
bold
);
term_out_table.set("FOREGROUND", foreground_table)
}
fn foreground(&self, term_out_table: &Table) -> lResult<()> {
let background_table = self.0.create_table()?;
background_styles_luau!(self, background_table,
on_dark_grey on_dark_red on_dark_green on_dark_cyan
on_dark_yellow on_dark_magenta on_dark_blue
on_red on_grey on_black
on_green on_yellow
on_blue on_magenta
on_cyan on_white
);
term_out_table.set("BACKGROUND", background_table)
}
}
trait Write {
fn write(&self) -> lResult<Function>;
fn write_error(&self) -> lResult<Function>;
fn write_error_ln(&self) -> lResult<Function>;
}
impl Write for LuauVm {
fn write(&self) -> lResult<Function> {
self.0.create_function(|_, s: String| -> lResult<()> {
print!("{s}");
Ok(())
})
}
fn write_error(&self) -> lResult<Function> {
self.0.create_function(|_, s: String| -> lResult<()> {
eprint!("{s}");
Ok(())
})
}
fn write_error_ln(&self) -> lResult<Function> {
self.0.create_function(|_, s: String| -> lResult<()> {
eprintln!("{s}");
Ok(())
})
}
}
pub trait Terminal {
fn out(&self) -> lResult<Table>;
fn global_terminal(&self, luau_globals: &Table) -> lResult<()>;
}
impl Terminal for LuauVm {
fn out(&self) -> lResult<Table> {
let term_out_table = self.0.create_table()?;
self.background(&term_out_table)?;
self.foreground(&term_out_table)?;
Ok(term_out_table)
}
fn global_terminal(&self, luau_globals: &Table) -> lResult<()> {
let term_table = self.0.create_table()?;
term_table.set("OUT", self.out()?)?;
term_table.set("WRITE", self.write()?)?;
term_table.set("WRITE_ERROR", self.write_error()?)?;
term_table.set("WRITE_ERROR_LN", self.write_error_ln()?)?;
luau_globals.set("TERMINAL", term_table)
}
}