use crate::{Environment, eval::apply::eval_apply, value::Value};
pub(crate) fn builtin(args: &[Value], env: Environment) -> Result<Value, std::sync::Arc<str>> {
if let [val] = args {
match eval_apply(val, env)? {
Value::String(s) => println!("{s}"),
o => println!("{o}"),
}
Ok(Value::Unit)
} else if let [val, end] = args {
match (eval_apply(val, env.clone())?, eval_apply(end, env)?) {
(v, Value::String(p)) => {
match v {
Value::String(s) => print!("{s}"),
o => print!("{o}"),
}
print!(
"{}",
unescaper::unescape(p.as_ref()).map_err(|e| {
std::sync::Arc::from(format!(
"Error[ksl::builtin::Print]: Failed to unescape `{p}` with `{e}`"
))
})?
);
console::Term::stdout().flush().map_err(|e| {
std::sync::Arc::from(format!(
"Error[ksl::builtin::Print]: Failed to flush stdout with `{e}`"
))
})?;
}
(_, e) => {
return Err(std::sync::Arc::from(format!(
"Error[ksl::builtin::Print]: Expected a string as print ending, but got `{e}`."
)));
}
}
Ok(Value::Unit)
} else {
Err(std::sync::Arc::from(format!(
concat!(
"Error[ksl::builtin::Print]: ",
"Expected 1 parameter, but {} were passed."
),
args.len()
)))
}
}