3 Commits
maps ... ps

Author SHA1 Message Date
41899480c0 working ps 2025-01-07 21:03:31 -05:00
546dbc7db0 init.luau instead of config.luau 2025-01-07 16:23:48 -05:00
9f0a376d5e refactoring 2025-01-06 20:51:54 -05:00
8 changed files with 196 additions and 165 deletions

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

@ -4,5 +4,26 @@ pub mod session;
pub mod commands; pub mod commands;
pub mod ps; pub mod ps;
pub mod rc; pub mod rc;
pub mod vm; pub mod vm;
#[inline]
pub fn shell_error<E: core::fmt::Display>(err: E) {
color_print::ceprintln!("<bold,r>[!]:</> {err}")
}
pub trait MapDisplay<T, E: core::fmt::Display> {
fn map_or_display<F: FnOnce(T)>(self, f: F);
fn map_or_display_none<R, F: FnOnce(T) -> Option<R>>(self, f: F) -> Option<R>;
}
impl<T, E: core::fmt::Display> MapDisplay<T, E> for Result<T, E> {
///Map but display the error to stdout
#[inline]
fn map_or_display<F: FnOnce(T)>(self, f: F) {
self.map_or_else(|e| shell_error(e), f)
}
///Map but display the error to stdout and return `None`
#[inline]
fn map_or_display_none<R, F: FnOnce(T) -> Option<R>>(self, f: F) -> Option<R> {
self.map_or_else(|e| { shell_error(e); None }, f)
}
}

View File

@ -1,14 +1,19 @@
use const_format::formatcp; pub const DEFAULT_PS: &str = concat!("lambdashell-", env!("CARGO_PKG_VERSION"), " ");
pub const DEFAULT_PS: &str = formatcp!("lambdashell-{}", env!("CARGO_PKG_VERSION")); #[derive(Debug, Clone)]
pub struct Ps(String);
struct Ps(String);
impl Ps { impl Ps {
fn set(prompt: String) -> Self { pub fn set(prompt: String) -> Self {
Self(prompt) Self(prompt)
} }
pub fn get(self) -> String {
self.0
}
pub fn display(&self) {
print!("{}", self.0);
}
fn working_dir_name(&self) -> 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();
@ -19,8 +24,4 @@ impl Ps {
}) })
}) })
} }
fn display(&self) {
print!("{}", self.0);
}
} }

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,63 +1,66 @@
use crate::{commands, ps, rc, vm::{LuauVm, self}};
use std::{fs, io::{self}}; use std::{fs, io::{self}};
use core::fmt;
use crate::{
commands, ps::{self, Ps}, rc, shell_error, vm::{self, LuauVm}, MapDisplay
};
#[derive(Debug, Clone)]
pub struct Config { pub struct Config {
pub norc: bool pub norc: bool
} }
pub struct LambdaShell { pub struct LambdaShell {
vm: LuauVm, terminate: bool,
ps1: String,
config: Config, config: Config,
terminating: bool, vm: LuauVm,
ps: Ps,
} }
impl LambdaShell { impl LambdaShell {
pub fn create(config: Config) -> Self { pub fn create(config: Config) -> Self {
let ps = Ps::set(ps::DEFAULT_PS.to_owned());
Self { Self {
vm: vm::LuauVm::new(), vm: vm::LuauVm::new(ps.to_owned()),
ps1: ps::DEFAULT_PS.to_owned(), terminate: false,
terminating: false,
config, config,
ps
} }
} }
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() { "exit" => self.terminate = true,
//special casey
"exit" => self.terminating = true,
trim => commands::Command::new(trim.to_owned()).exec() trim => commands::Command::new(trim.to_owned()).exec()
};
}) })
}) })
} }
pub fn vm_exec(&self, source: String) { pub fn error<E: fmt::Display>(&mut self, err: E) {
self.vm.exec(source); shell_error(err);
self.terminate = true;
} }
pub fn start(&mut self) { pub 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_else(|e| println!("{e}"), |luau_conf| self.vm_exec(luau_conf)); fs::read_to_string(conf_file).map_or_display(|luau_conf| self.vm_exec(luau_conf));
} }
} }
loop { self.ps.display();
match self.terminating {
true => break,
false => {
loop {
if self.terminate { break } else {
match self.wait() { match self.wait() {
Ok(()) => {}, Ok(()) => self.ps.display(),
Err(flush_error) => { Err(flush_err) => self.error(flush_err),
println!("{flush_error}");
break;
} }
} }
},
} }
} }
pub fn vm_exec(&self, source: String) {
self.vm.exec(source);
} }
} }

View File

@ -1,76 +1,77 @@
use mlua::{ use mlua::{Function, Lua as Luau, MultiValue, Result as lResult, Table, Value};
Function, Lua as Luau, MultiValue, Result as lResult, Table, Value use color_print::{cformat, ceprintln};
};
use crate::vm::{shell::System, terminal::Terminal};
use crate::VERSION;
use color_print::{cformat, cprintln};
use core::fmt; use core::fmt;
use shell::Shell;
use crate::{ps::Ps, vm::terminal::Terminal, MapDisplay};
mod shell; mod shell;
mod terminal; mod terminal;
mod alias; mod alias;
trait Helpers { trait LuauRuntimeErr<T> {
fn option_display_none<T, E: fmt::Display>(&self, err: E) -> Option<T>; fn map_or_luau_rt_err<R, F: FnOnce(T) -> Option<R>>(self, f: F) -> Option<R>;
fn luau_error<T>(&self, err: mlua::Error) -> Option<T>;
} }
impl Helpers for LuauVm { impl<T, E: fmt::Display> LuauRuntimeErr<T> for Result<T, E> {
fn option_display_none<T, E: fmt::Display>(&self, err: E) -> Option<T> { #[inline]
println!("{err}"); fn map_or_luau_rt_err<R, F: FnOnce(T) -> Option<R>>(self, f: F) -> Option<R> {
None self.map_or_else(|luau_rt_err| {
} ceprintln!("<bold>====</>\n<r><bold>[!]:</> {luau_rt_err}</>\n<bold>====</>");
fn luau_error<T>(&self, err: mlua::Error) -> Option<T> {
cprintln!("<bold>====</>\n<r><bold>[!]:</> {err}</>\n<bold>====</>");
None None
}, f)
} }
} }
trait Globals { trait Globals {
const LIB_VERSION: &str;
const CONV_ERROR: &str;
fn global_warn(&self, luau_globals: &Table) -> lResult<()>; fn global_warn(&self, luau_globals: &Table) -> lResult<()>;
fn global_version(&self, luau_globals: &Table) -> lResult<()>; fn global_version(&self, luau_globals: &Table) -> lResult<()>;
} }
impl Globals for LuauVm { impl Globals for LuauVm {
const LIB_VERSION: &str = env!("CARGO_PKG_VERSION");
const CONV_ERROR: &str = "<SHELL CONVERSION ERROR>";
fn global_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.set("warn", self.0.create_function(move |this, args: MultiValue| -> lResult<()> { luau_globals.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!("<y>{}</>", value.to_string().unwrap_or("<SHELL CONVERSION 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()))
.collect::<MultiValue>(); .collect::<MultiValue>();
luau_print.call::<()>(luau_multi_values).unwrap(); luau_print.call::<()>(luau_multi_values)?;
Ok(()) Ok(())
})?) })?)
} }
fn global_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.set("_VERSION", format!("{}, liblambdashell {}", luau_info, VERSION)) luau_globals.set("_VERSION", format!("{luau_info}, liblambdashell {}", Self::LIB_VERSION))
} }
} }
pub struct LuauVm(pub Luau); pub struct LuauVm {
vm: Luau,
ps: Ps,
}
impl LuauVm { impl LuauVm {
pub(crate) fn new() -> Self { pub(crate) fn new(ps: Ps) -> Self {
Self(Luau::new()) Self { vm: Luau::new(), ps }
} }
fn set_shell_globals(&self) -> lResult<()> { fn set_shell_globals(&self) -> lResult<()> {
let luau_globals = self.0.globals(); let luau_globals = self.vm.globals();
self.global_warn(&luau_globals)?; self.global_warn(&luau_globals)?;
self.global_version(&luau_globals)?; self.global_version(&luau_globals)?;
self.global_terminal(&luau_globals)?; self.global_terminal(&luau_globals)?;
self.shell_globals(&luau_globals)?; self.global_shell(&luau_globals)?;
luau_globals.set("getfenv", mlua::Nil)?; luau_globals.set("getfenv", mlua::Nil)?;
luau_globals.set("setfenv", mlua::Nil)?; luau_globals.set("setfenv", mlua::Nil)?;
self.0.sandbox(true)?; self.vm.sandbox(true)?;
Ok(()) Ok(())
} }
pub fn exec(&self, source: String) { pub fn exec(&self, source: String) {
match self.set_shell_globals() { self.set_shell_globals().map_or_display_none(|()| self.vm.load(source).exec().map_or_luau_rt_err(Some));
Ok(()) => self.0.load(source).exec().map_or_else(|exec_err| self.luau_error(exec_err), Some),
Err(globals_err) => self.option_display_none(globals_err),
};
} }
} }

View File

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

View File

@ -1,12 +1,13 @@
use const_format::str_split;
use mlua::{Function, Result as lResult, Table}; use mlua::{Function, Result as lResult, Table};
use const_format::str_split;
use crossterm::style::Stylize; use crossterm::style::Stylize;
use crate::vm::LuauVm; use crate::vm::LuauVm;
macro_rules! foreground_styles_luau { macro_rules! foreground_styles_luau {
($self:expr, $style_table:expr, $($color:ident)+) => { ($self:expr, $style_table:expr, $($color:ident)+) => {
$( $(
$style_table.set(stringify!($color).to_ascii_uppercase(), $self.0.create_function(|_, text: String| -> lResult<String> { $style_table.set(stringify!($color).to_ascii_uppercase(), $self.vm.create_function(|_, text: String| -> lResult<String> {
Ok(text.$color().to_string()) Ok(text.$color().to_string())
})?)?; })?)?;
)+ )+
@ -15,22 +16,22 @@ macro_rules! foreground_styles_luau {
macro_rules! background_styles_luau { macro_rules! background_styles_luau {
($self:expr, $style_table:expr, $($color:ident)+) => { ($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> { $style_table.set(
str_split!(stringify!($color), "_")[1..].join("_").to_ascii_uppercase(),
$self.vm.create_function(|_, text: String| -> lResult<String> {
Ok(text.$color().to_string()) Ok(text.$color().to_string())
})?)?; })?)?;
)+ )+
}; };
} }
#[allow(dead_code)]
trait Colors { trait Colors {
fn background(&self, style_table: &Table) -> lResult<()>; fn background(&self, term_out_table: &Table) -> lResult<()>;
fn foreground(&self, style_table: &Table) -> lResult<()>; fn foreground(&self, term_out_table: &Table) -> lResult<()>;
fn styling(&self, term_out_table: &Table) -> lResult<()>;
} }
impl Colors for LuauVm { impl Colors for LuauVm {
fn background(&self, style_table: &Table) -> lResult<()> { fn background(&self, term_out_table: &Table) -> lResult<()> {
let foreground_table = self.0.create_table()?; let foreground_table = self.vm.create_table()?;
foreground_styles_luau!(self, foreground_table, foreground_styles_luau!(self, foreground_table,
dark_grey dark_red dark_green dark_cyan dark_grey dark_red dark_green dark_cyan
dark_yellow dark_magenta dark_blue dark_yellow dark_magenta dark_blue
@ -43,11 +44,11 @@ impl Colors for LuauVm {
underline_blue underline_magenta underline_cyan underline_white underline_blue underline_magenta underline_cyan underline_white
bold bold
); );
style_table.set("FOREGROUND", foreground_table) term_out_table.set("FOREGROUND", foreground_table)
} }
fn foreground(&self, style_table: &Table) -> lResult<()> { fn foreground(&self, term_out_table: &Table) -> lResult<()> {
let background_table = self.0.create_table()?; let background_table = self.vm.create_table()?;
background_styles_luau!(self, background_table, background_styles_luau!(self, 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
on_dark_yellow on_dark_magenta on_dark_blue on_dark_yellow on_dark_magenta on_dark_blue
@ -56,38 +57,56 @@ impl Colors for LuauVm {
on_blue on_magenta on_blue on_magenta
on_cyan on_white on_cyan on_white
); );
style_table.set("BACKGROUND", background_table) term_out_table.set("BACKGROUND", background_table)
}
fn styling(&self, term_out_table: &Table) -> lResult<()> {
let style_table = self.0.create_table()?;
self.foreground(&style_table)?;
self.background(&style_table)?;
term_out_table.set("STYLE", style_table)
} }
} }
#[allow(dead_code)]
trait Write { trait Write {
fn write(&self, term_out_table: &Table) -> lResult<()>; fn write(&self) -> lResult<Function>;
fn write_error(&self) -> lResult<Function>;
fn write_error_ln(&self) -> lResult<Function>;
} }
impl Write for LuauVm { impl Write for LuauVm {
fn write(&self, term_out_table: &Table) -> lResult<()> { fn write(&self) -> lResult<Function> {
term_out_table.set("WRITE", self.0.create_function(|_, s: String| -> lResult<()> { self.vm.create_function(|_, s: String| -> lResult<()> {
print!("{s}"); print!("{s}");
Ok(()) Ok(())
})?) })
}
fn write_error(&self) -> lResult<Function> {
self.vm.create_function(|_, s: String| -> lResult<()> {
eprint!("{s}");
Ok(())
})
}
fn write_error_ln(&self) -> lResult<Function> {
self.vm.create_function(|_, s: String| -> lResult<()> {
eprintln!("{s}");
Ok(())
})
} }
} }
pub trait Terminal { pub trait Terminal {
fn out(&self) -> lResult<Table>;
fn global_terminal(&self, luau_globals: &Table) -> lResult<()>; fn global_terminal(&self, luau_globals: &Table) -> lResult<()>;
} }
impl Terminal for LuauVm { impl Terminal for LuauVm {
fn out(&self) -> lResult<Table> {
let term_out_table = self.vm.create_table()?;
self.background(&term_out_table)?;
self.foreground(&term_out_table)?;
Ok(term_out_table)
}
fn global_terminal(&self, luau_globals: &Table) -> lResult<()> { fn global_terminal(&self, luau_globals: &Table) -> lResult<()> {
let term_table = self.0.create_table()?; let term_table = self.vm.create_table()?;
let term_out_table = self.0.create_table()?; term_table.set("OUT", self.out()?)?;
term_table.set("OUT", term_out_table)?; term_table.set("WRITE", self.write()?)?;
luau_globals.set("TERMINAL", &term_table) term_table.set("WRITE_ERROR", self.write_error()?)?;
term_table.set("WRITE_ERROR_LN", self.write_error_ln()?)?;
luau_globals.set("TERMINAL", term_table)
} }
} }