Big project dir refactor

* split into multi member workspace in preparation for a no_std core
* env and posix stuff neatly crammed into a seperate shell project
* some pokes at interactive-devel.f
* updated ci
* removed 'l' shortcut for 'load' and update docs
* remove out of date readme content
* updated tests
* more sensible cond implementation and extra tests
* substr stdlib function with tests

Signed-off-by: Ava Affine <ava@sunnypup.io>
This commit is contained in:
Ava Apples Affine 2024-07-10 13:22:28 -07:00
parent aa56570d7d
commit 6d2925984f
44 changed files with 967 additions and 779 deletions

26
shell/Cargo.toml Normal file
View file

@ -0,0 +1,26 @@
[package]
name = "flesh-shell"
version = "0.4.0"
authors = ["Ava Affine <ava@sunnypup.io>"]
edition = "2021"
[[bin]]
name = "flesh"
path = "src/main.rs"
[dependencies]
# used in config (src/run.rs)
dirs = "3.0"
# these two are used in src/bin/relish.rs to manage a prompt
nu-ansi-term = "0.47.0"
reedline = "0.17.0"
# used by main shell to update console dimensions
termion = "2.0.1"
# these two used in posix shell layer (src/stl/posix.rs)
nix = { version = "0.26.2", optional = true }
libc = { version = "0.2.144", optional = true }
flesh-core = { path = "../core", features = ["implicit-load"]}
[features]
default = ["posix"]
posix = ["dep:nix", "dep:libc"]

548
shell/src/main.rs Normal file
View file

@ -0,0 +1,548 @@
/* Flesh: Flexible Shell
* Copyright (C) 2021 Ava Affine
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
#[cfg(feature="posix")]
mod posix;
mod run;
mod stl;
use {
flesh::{
ast::{
eval, lex,
Ctr, Seg, SymTable, Symbol,
Traceback,
},
stdlib::CFG_FILE_VNAME,
},
crate::{
run::run,
stl::{
load_environment, static_stdlib_overwrites, load_defaults,
CONSOLE_XDIM_VNAME, CONSOLE_YDIM_VNAME,
L_PROMPT_VNAME, R_PROMPT_VNAME, PROMPT_DELIM_VNAME,
},
},
std::{
cell::RefCell,
rc::Rc,
borrow::Cow,
env,
env::current_dir,
path::{PathBuf, Path},
},
reedline::{
FileBackedHistory, DefaultHinter, Reedline, Signal,
Prompt, PromptEditMode, PromptHistorySearch,
PromptHistorySearchStatus, Completer, Suggestion, Span,
KeyModifiers, KeyCode, ReedlineEvent, Keybindings,
ColumnarMenu, Emacs, ReedlineMenu, Validator, ValidationResult,
default_emacs_keybindings,
},
nu_ansi_term::{Color, Style},
dirs::home_dir,
termion::terminal_size,
};
#[cfg(feature="posix")]
use crate::stl::dynamic_stdlib;
#[cfg(feature="posix")]
use posix::{ShellState, check_jobs};
#[cfg(feature="posix")]
use nix::unistd;
#[derive(Clone)]
pub struct CustomPrompt(String, String, String);
#[derive(Clone)]
pub struct CustomCompleter(Vec<String>);
pub struct CustomValidator;
impl Prompt for CustomPrompt {
fn render_prompt_left(&self) -> Cow<str> {
{
Cow::Owned(self.0.to_owned())
}
}
fn render_prompt_right(&self) -> Cow<str> {
{
Cow::Owned(self.1.to_owned())
}
}
fn render_prompt_indicator(&self, _edit_mode: PromptEditMode) -> Cow<str> {
Cow::Owned(self.2.to_owned())
}
fn render_prompt_multiline_indicator(&self) -> Cow<str> {
Cow::Borrowed("++++")
}
fn render_prompt_history_search_indicator(
&self,
history_search: PromptHistorySearch,
) -> Cow<str> {
let prefix = match history_search.status {
PromptHistorySearchStatus::Passing => "",
PromptHistorySearchStatus::Failing => "failing ",
};
Cow::Owned(format!(
"({}search: {}) ",
prefix, history_search.term
))
}
}
impl Completer for CustomCompleter {
fn complete(&mut self, line: &str, pos: usize) -> Vec<Suggestion> {
let current_dir_path = current_dir()
.expect("current dir bad?");
let (tok, is_str, start) = get_token_to_complete(line, pos);
let mut sugg = vec![];
if !is_str && !tok.contains('/') {
let mut offcenter_match = vec![];
for sym in &self.0 {
if sym.starts_with(tok.as_str()) {
sugg.push(Suggestion {
value: sym.clone(),
description: None,
extra: None,
append_whitespace: false,
span: Span {
start,
end: pos
}
});
continue;
}
if sym.contains(tok.as_str()) {
offcenter_match.push(sym.clone());
}
}
for i in offcenter_match {
sugg.push(Suggestion {
value: i.clone(),
description: None,
extra: None,
append_whitespace: false,
span: Span {
start,
end: pos
}
});
}
} else {
let mut path: PathBuf = Path::new(&tok).to_path_buf();
let rel = path.is_relative();
if rel {
path = current_dir_path.join(path);
}
if path.exists() && path.is_dir() {
if let Ok(entries) = path.read_dir() {
for entry in entries {
if let Ok(e) = entry {
let mut path = e.path();
if rel {
path = path.strip_prefix(current_dir_path.clone())
.unwrap()
.to_path_buf();
}
let d = path.is_dir();
let mut str_path = path.as_os_str()
.to_str()
.expect("inexplicable stringification error")
.to_owned();
if d {
str_path = str_path + "/";
}
sugg.push(Suggestion {
value: str_path,
description: None,
extra: None,
span: Span {
start,
end: pos
},
append_whitespace: false
});
}
}
}
} else {
// check parent to autocomplete path
if let Some(parent) = path.parent() {
if let Ok(entries) = parent.read_dir() {
for entry in entries {
if let Ok(e) = entry {
if e.file_name()
.to_string_lossy()
.starts_with(path.file_name()
.expect("bad file somehow?")
.to_string_lossy()
.to_mut()
.as_str()
) {
let mut path = e.path();
if rel {
path = path.strip_prefix(current_dir_path.clone())
.unwrap()
.to_path_buf();
}
sugg.push(Suggestion {
value: path
.as_os_str()
.to_str()
.expect("bad dir somehow?")
.to_owned(),
description: None,
extra: None,
append_whitespace: false,
span: Span {
start,
end: pos
}
});
}
}
}
}
}
}
}
sugg
}
}
impl Validator for CustomValidator {
fn validate(&self, line: &str) -> ValidationResult {
if incomplete_brackets(line) {
ValidationResult::Incomplete
} else {
ValidationResult::Complete
}
}
}
fn incomplete_brackets(line: &str) -> bool {
let mut balance: Vec<char> = Vec::new();
let mut within_string: Option<char> = None;
for c in line.chars() {
match c {
c if ['"', '`'].contains(&c) => {
match within_string {
Some(w) if c == w => {
balance.pop();
within_string = None
}
Some(_) => {},
None => {
balance.push(c);
within_string = Some(c)
},
}
},
'(' if within_string.is_none() => balance.push(')'),
')' => if let Some(last) = balance.last() {
if last == &c {
balance.pop();
}
},
_ => {}
}
}
!balance.is_empty()
}
fn add_menu_keybindings(keybindings: &mut Keybindings) {
keybindings.add_binding(
KeyModifiers::NONE,
KeyCode::Tab,
ReedlineEvent::UntilFound(vec![
ReedlineEvent::Menu("completion_menu".to_string()),
ReedlineEvent::MenuNext,
]),
);
}
fn main() {
const HIST_FILE: &str = "/.flesh_hist";
const CONFIG_FILE_DEFAULT: &str = "/.fleshrc";
const VERSION: &str = env!("CARGO_PKG_VERSION");
if env::args().count() > 1 &&
env::args()
.collect::<Vec<_>>()
.contains(&"--version".to_string()) {
println!("Flesh {}", VERSION);
return;
}
// default config file dirs
let home_dir = home_dir().unwrap().to_str().unwrap().to_owned();
let hist_file_name = home_dir.clone() + HIST_FILE;
let cfg_file_name = home_dir + CONFIG_FILE_DEFAULT;
// setup symtable
let mut syms = SymTable::new();
load_defaults(&mut syms);
load_environment(&mut syms);
static_stdlib_overwrites(&mut syms);
#[cfg(feature="posix")]
let prompt_ss: Rc<RefCell<ShellState>>;
#[cfg(feature="posix")]
{
let shell_state_bindings = Rc::new(RefCell::from(ShellState {
parent_pid: unistd::Pid::from_raw(0),
parent_sid: unistd::Pid::from_raw(0),
children: vec![],
last_exit_code: 0,
attr: None,
}));
prompt_ss = shell_state_bindings.clone();
dynamic_stdlib(&mut syms, Some(shell_state_bindings));
}
{
// scope the below borrow of syms
let cfg_file = env::var(CFG_FILE_VNAME).unwrap_or(cfg_file_name);
run(cfg_file.clone(), &mut syms)
.unwrap_or_else(|err: Traceback| eprintln!("failed to load script {}\n{}", cfg_file, err));
}
#[cfg(feature="posix")]
{
dynamic_stdlib(&mut syms, Some(prompt_ss.clone()));
}
// if there are args those are scripts, run them and exit
if env::args().count() > 1 {
let mut iter = env::args();
iter.next();
for i in iter {
if let Err(e) = run(i, &mut syms) {
eprintln!("{}", e)
}
}
return
}
// setup readline
let completion_menu = Box::new(ColumnarMenu::default().with_name("completion_menu"));
let mut keybindings = default_emacs_keybindings();
add_menu_keybindings(&mut keybindings);
let edit_mode = Box::new(Emacs::new(keybindings));
let mut rl = Reedline::create()
.with_menu(ReedlineMenu::EngineCompleter(completion_menu))
.with_edit_mode(edit_mode)
.with_quick_completions(true)
.with_partial_completions(true)
.with_ansi_colors(true);
let maybe_hist: Box<FileBackedHistory>;
if !hist_file_name.is_empty() {
maybe_hist = Box::new(
FileBackedHistory::with_file(5000, hist_file_name.into())
.expect("error reading history!")
);
rl = rl.with_history(maybe_hist);
}
rl = rl.with_hinter(Box::new(
DefaultHinter::default()
.with_style(Style::new().italic().fg(Color::LightGray)),
)).with_validator(Box::new(CustomValidator));
let mut xdimension: u16 = 0;
let mut ydimension: u16 = 0;
loop {
#[cfg(feature="posix")]
{
check_jobs(&mut prompt_ss.borrow_mut());
}
let readline_prompt = make_prompt(&mut syms);
let completer = make_completer(&mut syms);
// realloc with each loop because syms can change
rl = rl.with_completer(Box::new(completer));
let user_doc = rl.read_line(&readline_prompt).unwrap();
// doing this update here prevents needing to update twice before dimensions take effect
(xdimension, ydimension) =
check_and_update_console_dimensions(&mut syms, xdimension, ydimension);
match user_doc {
Signal::Success(line) => {
println!(""); // add a new line before output gets printed
let mut l = line.as_str().to_owned();
if !l.starts_with('(') {
l = "(".to_owned() + &l + ")";
}
match lex(&l) {
Ok(a) => match eval(&a, &mut syms) {
Ok(a) => println!("{}", a),
Err(s) => println!("{}", s),
},
Err(s) => println!("{}", s),
}
},
Signal::CtrlD => {
println!("EOF!");
return
},
Signal::CtrlC => {
println!("Interrupted!");
},
}
}
}
fn make_prompt(syms: &mut SymTable) -> CustomPrompt {
let l_ctr = *syms
.call_symbol(&L_PROMPT_VNAME.to_string(), &Seg::new(), true)
.unwrap_or_else(|err: Traceback| {
eprintln!("{}", err);
Box::new(Ctr::String("<prompt broken!>".to_string()))
});
let r_ctr = *syms
.call_symbol(&R_PROMPT_VNAME.to_string(), &Seg::new(), true)
.unwrap_or_else(|err: Traceback| {
eprintln!("{}", err);
Box::new(Ctr::String("<prompt broken!>".to_string()))
});
let d_ctr = *syms
.call_symbol(&PROMPT_DELIM_VNAME.to_string(), &Seg::new(), true)
.unwrap_or_else(|err: Traceback| {
eprintln!("{}", err);
Box::new(Ctr::String("<prompt broken!>".to_string()))
});
let l_str: String;
let r_str: String;
let d_str: String;
if let Ctr::String(s) = l_ctr {
l_str = s;
} else {
l_str = l_ctr.to_string();
}
if let Ctr::String(s) = r_ctr {
r_str = s;
} else {
r_str = r_ctr.to_string();
}
if let Ctr::String(s) = d_ctr {
d_str = s;
} else {
d_str = d_ctr.to_string();
}
CustomPrompt(l_str, r_str, d_str)
}
fn make_completer(syms: &mut SymTable) -> CustomCompleter {
let mut toks = vec![];
for i in syms.keys(){
toks.push(i.clone());
}
CustomCompleter(toks)
}
fn get_token_to_complete(line: &str, pos: usize) -> (String, bool, usize) {
let mut res = String::with_capacity(1);
let mut doc = line.chars().rev();
for _ in pos..line.len() {
doc.next();
}
let mut is_str = false;
let mut start_idx = pos;
for idx in (0..pos).rev() {
let iter = doc.next()
.expect(format!("AC: no idx {}", idx)
.as_str());
match iter {
' ' | '(' | '\n' => {
break
},
'\'' | '"' => {
is_str = true;
break
},
_ => {
start_idx = idx;
res.insert(0, iter);
}
}
}
return (res, is_str, start_idx)
}
/* It was considered that a SIGWINCH handler would be a more
* elegant solution to this. Such a solution would need to
* modify the current libc based approach to use a state-enclosing
* closure as a signal handler. As of May 2023 there is no clear
* way of doing such a thing.
*
* Luckily this data is only used within Flesh, so we can simply
* rely on it only being read during the evaluation phase of the REPL.
* This method will at least work for that. (ava)
*/
fn check_and_update_console_dimensions(
syms: &mut SymTable,
last_xdim: u16,
last_ydim: u16
) -> (u16, u16) {
let (xdim, ydim) = terminal_size().expect("Couldnt get console dimensions");
if xdim != last_xdim {
syms.insert(
String::from(CONSOLE_XDIM_VNAME),
Symbol::from_ast(
&String::from(CONSOLE_XDIM_VNAME),
&String::from("Length of current console"),
&Seg::from_mono(Box::new(Ctr::Integer(xdim.into()))),
None,
)
);
}
if ydim != last_ydim {
syms.insert(
String::from(CONSOLE_YDIM_VNAME),
Symbol::from_ast(
&String::from(CONSOLE_YDIM_VNAME),
&String::from("Height of current console"),
&Seg::from_mono(Box::new(Ctr::Integer(ydim.into()))),
None,
)
);
}
(xdim, ydim)
}

1075
shell/src/posix.rs Normal file

File diff suppressed because it is too large Load diff

101
shell/src/run.rs Normal file
View file

@ -0,0 +1,101 @@
/* Flesh: Flexible Shell
* Copyright (C) 2021 Ava Affine
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use flesh::ast::{
eval, lex, start_trace,
Ctr, Seg, SymTable, Traceback,
};
use std::path::Path;
use std::fs;
use std::iter::FromIterator;
use std::env::{var, current_dir};
fn get_paths() -> Vec<String> {
Vec::from_iter(var("PATH")
.unwrap_or("".to_string())
.split(':')
.map(String::from))
}
pub fn find_on_path(filename: String) -> Option<String> {
let mut prefixes = get_paths();
if let Ok(s) = current_dir() {
prefixes.push(String::from(s.to_str().unwrap()));
}
prefixes.push(String::from("/"));
for prefix in prefixes {
let candidate = Path::new(&prefix.clone()).join(filename.clone());
if candidate.exists() {
return Some(String::from(candidate.to_str().unwrap()))
}
}
None
}
pub fn run(filename: String, syms: &mut SymTable) -> Result<(), Traceback> {
let script_read_res = fs::read_to_string(filename);
if script_read_res.is_err() {
Err(start_trace(
("<call script>", format!("Couldnt read script: {}", script_read_res.err().unwrap()))
.into()))
} else {
let script_read = script_read_res.unwrap() + ")";
let script = "(".to_string() + &script_read;
eval(&*lex(&script)?, syms)?;
Ok(())
}
}
pub const RUN_DOCSTRING: &str = "Takes one string argument.
Attempts to find argument in PATH and attempts to call argument";
pub fn run_callback(ast: &Seg, syms: &mut SymTable) -> Result<Ctr, Traceback> {
if let Ctr::String(ref filename) = *ast.car {
if filename.ends_with(".f") {
if let Some(filepath) = find_on_path(filename.to_string()) {
run(filepath, syms)
.and(Ok(Ctr::None))
} else {
let canonical_path_res = fs::canonicalize(filename);
if canonical_path_res.is_err() {
return Err(start_trace(
("<call script>", canonical_path_res
.err()
.unwrap()
.to_string())
.into()))
}
let canonical_path = canonical_path_res.ok().unwrap();
return run(
canonical_path
.to_string_lossy()
.to_string(),
syms
).and(Ok(Ctr::None))
}
} else {
Err(start_trace(
("<call script>", "expected a flesh script with a .f extension")
.into()))
}
} else {
Err(start_trace(
("<call script>", "impossible: not a string")
.into()))
}
}

230
shell/src/stl.rs Normal file
View file

@ -0,0 +1,230 @@
/* Flesh: Flexible Shell
* Copyright (C) 2021 Ava Affine
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use flesh::{
ast::{Ctr, Seg, Type, Args, SymTable, Symbol, ValueType, Traceback},
stdlib::{STORE_DOCSTRING, static_stdlib},
};
use crate::run::{run_callback, RUN_DOCSTRING};
use std::rc::Rc;
use std::cell::RefCell;
use std::env::vars;
#[cfg(feature = "posix")]
use crate::posix;
#[path = "window.rs"]
mod window;
#[path = "store.rs"]
mod store;
pub const CONSOLE_XDIM_VNAME: &str = "_FLESH_WIDTH";
pub const CONSOLE_YDIM_VNAME: &str = "_FLESH_HEIGHT";
pub const POSIX_CFG_VNAME: &str = "CFG_FLESH_POSIX";
pub const MODENV_CFG_VNAME: &str = "CFG_FLESH_ENV";
pub const L_PROMPT_VNAME: &str = "CFG_FLESH_L_PROMPT";
pub const R_PROMPT_VNAME: &str = "CFG_FLESH_R_PROMPT";
pub const PROMPT_DELIM_VNAME: &str = "CFG_FLESH_PROMPT_DELIMITER";
pub const FLESH_DEFAULT_CONS_HEIGHT: i16 = 24;
pub const FLESH_DEFAULT_CONS_WIDTH: i16 = 80;
fn l_prompt_default_callback(_: &Seg, _: &mut SymTable) -> Result<Ctr, Traceback> {
Ok(Ctr::String(">".to_string()))
}
fn r_prompt_default_callback(_: &Seg, _: &mut SymTable) -> Result<Ctr, Traceback> {
Ok(Ctr::String(String::new()))
}
fn prompt_delimiter_default_callback(_: &Seg, _: &mut SymTable) -> Result<Ctr, Traceback> {
Ok(Ctr::String("λ ".to_string()))
}
/// static_stdlib
/// inserts all stdlib functions that can be inserted without
/// any kind of further configuration data into a symtable
pub fn static_stdlib_overwrites(syms: &mut SymTable) {
static_stdlib(syms);
window::add_window_lib_funcs(syms);
syms.insert(
"call".to_string(),
Symbol {
name: String::from("call"),
args: Args::Strict(vec![Type::String]),
conditional_branches: false,
docs: RUN_DOCSTRING.to_string(),
value: ValueType::Internal(Rc::new(run_callback)),
..Default::default()
}
);
}
/// dynamic_stdlib
/// takes configuration data and uses it to insert dynamic
/// callbacks with configuration into a symtable
#[cfg(feature="posix")]
pub fn dynamic_stdlib(syms: &mut SymTable, shell: Option<Rc<RefCell<posix::ShellState>>>) {
let env_cfg_user_form = syms
.call_symbol(&MODENV_CFG_VNAME.to_string(), &Seg::new(), true)
.unwrap_or_else(|_: Traceback| Box::new(Ctr::None))
.to_string()
.eq("true");
if env_cfg_user_form {
syms.insert(
"def".to_string(),
Symbol {
name: String::from("define"),
args: Args::Infinite,
conditional_branches: true,
docs: STORE_DOCSTRING.to_string(),
value: ValueType::Internal(Rc::new(
store::store_callback_with_env_integration
)),
..Default::default()
}
);
}
if let Some(shell_state) = shell {
let posix_cfg_user_form = syms
.call_symbol(&POSIX_CFG_VNAME.to_string(), &Seg::new(), true)
.unwrap_or_else(|_: Traceback| Box::new(Ctr::None))
.to_string()
.eq("true");
if posix_cfg_user_form {
posix::load_posix_shell(syms, shell_state);
}
}
}
pub fn load_defaults(syms: &mut SymTable) {
syms.insert(
POSIX_CFG_VNAME.to_string(),
Symbol {
name: String::from(POSIX_CFG_VNAME),
args: Args::None,
conditional_branches: false,
docs: "variable holding whether or not POSIX job control functions are to be loaded.
checked at shell startup by configuration daemon. not used afterwards.
default value: true".to_string(),
value: ValueType::VarForm(Box::new(Ctr::Bool(true))),
..Default::default()
},
);
syms.insert(
MODENV_CFG_VNAME.to_string(),
Symbol {
name: String::from(MODENV_CFG_VNAME),
args: Args::None,
conditional_branches: false,
docs: "variable holding whether or not vars and other symbols should be linked to process environment variables.
If set/defined all calls to def will result in additions or subtractions from user environment variables.
checked at shell startup by configuration daemon. not used afterwards.
default value: 1 (set)
".to_string(),
value: ValueType::VarForm(Box::new(Ctr::Bool(true))),
..Default::default()
},
);
syms.insert(
L_PROMPT_VNAME.to_string(),
Symbol {
name: String::from(L_PROMPT_VNAME),
args: Args::None,
conditional_branches: false,
docs: "function called to output prompt on left hand. this function is called with no arguments."
.to_string(),
value: ValueType::Internal(Rc::new(l_prompt_default_callback)),
..Default::default()
},
);
syms.insert(
R_PROMPT_VNAME.to_string(),
Symbol {
name: String::from(R_PROMPT_VNAME),
args: Args::None,
conditional_branches: false,
docs: "function called to output prompt on right hand. this function is called with no arguments."
.to_string(),
value: ValueType::Internal(Rc::new(r_prompt_default_callback)),
..Default::default()
},
);
syms.insert(
PROMPT_DELIM_VNAME.to_string(),
Symbol {
name: String::from(PROMPT_DELIM_VNAME),
args: Args::None,
conditional_branches: false,
docs: "function called to output prompt delimiter. this function is called with no arguments."
.to_string(),
value: ValueType::Internal(Rc::new(prompt_delimiter_default_callback)),
..Default::default()
},
);
syms.insert(
String::from(CONSOLE_XDIM_VNAME),
Symbol::from_ast(
&String::from(CONSOLE_XDIM_VNAME),
&String::from("Length of current console"),
&Seg::from_mono(Box::new(
Ctr::Integer(FLESH_DEFAULT_CONS_WIDTH.into())
)),
None,
)
);
syms.insert(
String::from(CONSOLE_YDIM_VNAME),
Symbol::from_ast(
&String::from(CONSOLE_YDIM_VNAME),
&String::from("Height of current console"),
&Seg::from_mono(Box::new(
Ctr::Integer(FLESH_DEFAULT_CONS_HEIGHT.into())
)),
None,
)
);
}
pub fn load_environment(syms: &mut SymTable) {
for (key, value) in vars() {
syms.insert(
key.clone(),
Symbol{
name: key,
args: Args::None,
conditional_branches: false,
docs: String::from("from env vars at time of load"),
value: ValueType::VarForm(Box::new(Ctr::String(value))),
..Default::default()
}
);
}
}

53
shell/src/store.rs Normal file
View file

@ -0,0 +1,53 @@
/* Flesh: Flexible Shell
* Copyright (C) 2021 Ava Hahn
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use std::env;
use flesh::ast::{Ctr, Traceback, Seg, SymTable, Type, ValueType};
use flesh::stdlib::store_callback;
pub fn store_callback_with_env_integration(
ast: &Seg,
syms: &mut SymTable
) -> Result<Ctr, Traceback> {
let name = store_callback(ast, syms)?;
if let Ctr::String(n) = &name {
match ast.len() {
1 => {
env::remove_var(n);
},
3 if syms.contains_key(&n) => {
if let ValueType::VarForm(val) = &syms.get(&n).unwrap().value {
match val.to_type() {
Type::Lambda => {},
Type::Seg => {},
_ => {
let mut s = val.to_string();
// eat printed quotes on a string val
if let Ctr::String(tok) = &**val {
s = tok.to_string();
}
env::set_var(n.clone(), s);
}
}
}
},
_ => {}
}
}
Ok(name)
}

110
shell/src/window.rs Normal file
View file

@ -0,0 +1,110 @@
/* Flesh: Flexible Shell
* Copyright (C) 2021 Ava Hahn
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
use flesh::ast::{Traceback, Ctr, Symbol, Args, ValueType, Seg, SymTable, Type};
use crate::stl::{CONSOLE_XDIM_VNAME, FLESH_DEFAULT_CONS_WIDTH};
use std::rc::Rc;
pub fn add_window_lib_funcs(syms: &mut SymTable) {
syms.insert(
"env".to_string(),
Symbol {
name: String::from("env"),
args: Args::None,
conditional_branches: false,
docs: ENV_DOCSTRING.to_string(),
value: ValueType::Internal(Rc::new(env_callback)),
..Default::default()
},
);
}
const ENV_DOCSTRING: &str = "takes no arguments
prints out all available symbols and their associated values";
fn env_callback(_ast: &Seg, syms: &mut SymTable) -> Result<Ctr, Traceback> {
// get width of current output
let xdim: i128;
if let Ctr::Integer(dim) = *syms
.call_symbol(&CONSOLE_XDIM_VNAME.to_string(), &Seg::new(), true)
.unwrap_or_else(|_: Traceback| Box::new(Ctr::None)) {
xdim = dim;
} else {
println!("{} contains non integer value, defaulting to {}",
CONSOLE_XDIM_VNAME, FLESH_DEFAULT_CONS_WIDTH);
xdim = FLESH_DEFAULT_CONS_WIDTH as i128;
}
let mut v_col_len = 0;
let mut f_col_len = 0;
let mut functions = vec![];
let mut variables = vec![];
for (name, val) in syms.iter() {
if let ValueType::VarForm(l) = &val.value {
let token: String = match l.to_type() {
Type::Lambda => format!("{}: <lambda>", name),
Type::Seg => format!("{}: <form>", name),
_ => format!("{}: {}", name, val.value),
};
if token.len() > v_col_len && token.len() < xdim as usize {
v_col_len = token.len();
}
variables.push(token);
} else {
if f_col_len < name.len() && name.len() < xdim as usize {
f_col_len = name.len();
}
functions.push(name.clone());
}
}
let mut n_v_cols = xdim / v_col_len as i128;
// now decrement to make sure theres room for two spaces of padding
while n_v_cols > 1 && xdim % (v_col_len as i128) < (2 * n_v_cols) {
n_v_cols -= 1;
}
// again for functions
let mut n_f_cols = xdim / f_col_len as i128;
while n_f_cols > 1 && xdim & (f_col_len as i128) < (2 * n_f_cols) {
n_f_cols -= 1;
}
let mut col_iter = 0;
println!("VARIABLES:");
for var in variables {
print!("{:v_col_len$}", var);
col_iter += 1;
if col_iter % n_v_cols == 0 {
println!();
} else {
print!(" ");
}
}
println!("\nFUNCTIONS:");
col_iter = 0;
for func in functions {
print!("{:f_col_len$}", func);
col_iter += 1;
if col_iter % n_f_cols == 0 {
println!();
} else {
print!(" ");
}
}
Ok(Ctr::None)
}