cl-interpret: Builtins! builtins(), chars(str), and panic(msg)

This commit is contained in:
John 2025-05-18 11:42:33 -04:00
parent 08b5937fc2
commit 124bb2f680
2 changed files with 28 additions and 13 deletions

View File

@ -5,7 +5,7 @@ use crate::{
env::Environment,
error::{Error, IResult},
};
use std::io::{stdout, Write};
use std::io::{Write, stdout};
/// A function built into the interpreter.
#[derive(Clone, Copy)]
@ -98,10 +98,10 @@ pub macro builtins($(
[$(builtin!($(#[$($meta)*])* fn $name ($($args)*) $(@$env)? $body)),*]
}
/// Creates an [Error::BuiltinDebug] using interpolation of runtime expressions.
/// Creates an [Error::BuiltinError] using interpolation of runtime expressions.
/// See [std::format].
pub macro error_format ($($t:tt)*) {
$crate::error::Error::BuiltinDebug(format!($($t)*))
$crate::error::Error::BuiltinError(format!($($t)*))
}
pub const Builtins: &[Builtin] = &builtins![
@ -143,18 +143,23 @@ pub const Builtins: &[Builtin] = &builtins![
Ok(())
}
fn panic(message) {
Err(error_format!("Panic: {message}"))?;
Ok(())
}
/// Dumps the environment
fn dump() @env {
println!("{env}");
Ok(())
}
// fn builtins() @env {
// for builtin in env.builtins().values().flatten() {
// println!("{builtin}");
// }
// Ok(())
// }
fn builtins() @env {
for builtin in env.globals().values().flatten().filter(|v| matches!(v, ConValue::Builtin(_))) {
println!("{builtin}")
}
Ok(())
}
/// Returns the length of the input list as a [ConValue::Int]
fn len(list) @env {
@ -170,6 +175,16 @@ pub const Builtins: &[Builtin] = &builtins![
})
}
fn chars(string) @env {
Ok(match string {
ConValue::String(s) => ConValue::Array(s.chars().map(Into::into).collect()),
ConValue::Ref(r) => {
return chars(env, &[env.get_id(*r).ok_or(Error::StackOverflow(*r))?.clone()])
}
_ => Err(Error::TypeError())?,
})
}
fn dump_symbols() {
println!("{}", cl_structures::intern::string_interner::StringInterner::global());
Ok(ConValue::Empty)

View File

@ -99,8 +99,8 @@ impl Error {
Self { kind: ErrorKind::MatchNonexhaustive, span: None }
}
/// Error produced by a Builtin
pub fn BuiltinDebug(msg: String) -> Self {
Self { kind: ErrorKind::BuiltinDebug(msg), span: None }
pub fn BuiltinError(msg: String) -> Self {
Self { kind: ErrorKind::BuiltinError(msg), span: None }
}
}
@ -156,7 +156,7 @@ pub enum ErrorKind {
/// Fell through a non-exhaustive match
MatchNonexhaustive,
/// Error produced by a Builtin
BuiltinDebug(String),
BuiltinError(String),
}
impl std::error::Error for ErrorKind {}
@ -205,7 +205,7 @@ impl std::fmt::Display for ErrorKind {
ErrorKind::MatchNonexhaustive => {
write!(f, "Fell through a non-exhaustive match expression!")
}
ErrorKind::BuiltinDebug(s) => write!(f, "DEBUG: {s}"),
ErrorKind::BuiltinError(s) => write!(f, "{s}"),
}
}
}