Lines
100 %
Functions
Branches
//! Standard-library loading: the essential CL macros `WHEN`, `UNLESS`, plus
//! the `UPCASE` utility wrapper.
use std::collections::HashSet;
use crate::ast::{Expr, LambdaParams, Number};
use crate::error::{Error, Result};
use super::entry::{Symbol, SymbolKind};
use super::table::SymbolTable;
impl SymbolTable {
/// The table every script starts from, before the prelude.
pub(super) fn without_prelude() -> Self {
let mut table = Self::new();
table.register_builtins();
table.load_standard_library();
table.register_compiler_natives();
table
}
/// Every name defined before the prelude: the one source of "built-in".
pub(crate) fn builtin_names() -> HashSet<String> {
Self::without_prelude().symbols.into_keys().collect()
pub(super) fn load_standard_library(&mut self) {
self.load_essential_macros();
fn load_essential_macros(&mut self) {
let when_params = LambdaParams {
required: vec!["test".to_string()],
optional: Vec::new(),
rest: Some("body".to_string()),
key: Vec::new(),
aux: Vec::new(),
};
let when_body = Expr::Quasiquote(Box::new(Expr::List(vec![
Expr::symbol("IF"),
Expr::Unquote(Box::new(Expr::Symbol("test".to_string()))),
Expr::List(vec![
Expr::symbol("PROGN"),
Expr::UnquoteSplicing(Box::new(Expr::Symbol("body".to_string()))),
]),
Expr::Nil,
])));
let when_lambda = Expr::Lambda(when_params, Box::new(when_body));
self.define(Symbol::new("WHEN", SymbolKind::Macro).with_function(when_lambda));
let unless_params = LambdaParams {
let unless_body = Expr::Quasiquote(Box::new(Expr::List(vec![
let unless_lambda = Expr::Lambda(unless_params, Box::new(unless_body));
self.define(Symbol::new("UNLESS", SymbolKind::Macro).with_function(unless_lambda));
let return_params = LambdaParams {
required: Vec::new(),
rest: Some("value".to_string()),
let return_body = Expr::Quasiquote(Box::new(Expr::List(vec![
Expr::symbol("RETURN-FROM"),
Expr::UnquoteSplicing(Box::new(Expr::Symbol("value".to_string()))),
let return_lambda = Expr::Lambda(return_params, Box::new(return_body));
self.define(Symbol::new("RETURN", SymbolKind::Macro).with_function(return_lambda));
self.define(Symbol::new("DOTIMES", SymbolKind::Macro).with_function(dotimes_lambda()));
self.add_utility_functions();
fn add_utility_functions(&mut self) {
let upcase_params = LambdaParams::simple(vec!["string".to_string()]);
let upcase_body = Expr::List(vec![
Expr::symbol("UPCASE-STRING"),
Expr::Symbol("string".to_string()),
]);
let upcase_lambda = Expr::Lambda(upcase_params, Box::new(upcase_body));
self.define(Symbol::new("UPCASE", SymbolKind::Function).with_function(upcase_lambda));
/// Loads the universal nomiscript prelude (ADR-0029) — reusable helpers
/// authored IN nomiscript and shared by every table. Called last in
/// `with_builtins*` so the prelude's DEFUNs see the builtins + accessors.
/// The source is DEFUN-only and references only universally-present
/// symbols, so it loads identically on the eval/host and pure-wasm paths
/// (a DEFUN stores its lambda body without resolving it). Host-fn-dependent
/// helpers are loaded separately on the rpc Session path.
///
/// # Errors
/// The baked prelude source fails to load.
pub(super) fn load_prelude(&mut self) -> Result<()> {
self.load_nomiscript_defuns(include_str!("prelude.nms"))
/// Parses a DEFUN-only nomiscript source and registers each `defun` into
/// this table via the eval special-form path. Shared by the universal
/// prelude here and the rpc host prelude.
/// The source does not parse, a top-level form is not a DEFUN, or a DEFUN
/// is refused.
pub fn load_nomiscript_defuns(&mut self, source: &str) -> Result<()> {
let program = crate::reader::Reader::parse(source)?;
for form in &program.exprs {
match form.as_list().and_then(<[Expr]>::split_first) {
Some((Expr::Symbol(head), tail)) if head == "DEFUN" => {
crate::compiler::special::call(self, "DEFUN", tail)?;
_ => {
return Err(Error::Compile(
"only top-level DEFUN forms are allowed".to_string(),
));
Ok(())
/// Both the hidden count variable of DOTIMES and the type word of the THE
/// that checks it; no program can spell it.
pub(crate) const DOTIMES_COUNT: &str = "DOTIMES COUNT";
/// `(dotimes (var count result…) body…)` as a DO over `var` from 0 and a hidden
/// variable holding `count`, evaluated once.
fn dotimes_lambda() -> Expr {
let params = LambdaParams {
required: vec!["spec".to_string()],
let call = |name: &str, args: Vec<Expr>| {
Expr::List(std::iter::once(Expr::symbol(name)).chain(args).collect())
let unquote = |form: Expr| Expr::Unquote(Box::new(form));
let spec = || Expr::Symbol("spec".to_string());
let var = || unquote(call("CAR", vec![spec()]));
let count = Expr::Symbol(DOTIMES_COUNT.to_string());
let step = call("+", vec![var(), Expr::Number(Number::Index(1))]);
let bindings = Expr::List(vec![
Expr::List(vec![var(), Expr::Number(Number::Index(0)), step]),
count.clone(),
call(
"THE",
vec![
Expr::symbol(DOTIMES_COUNT),
unquote(call("CAR", vec![call("CDR", vec![spec()])])),
],
),
let results = call("CDR", vec![call("CDR", vec![spec()])]);
let end = Expr::List(vec![
call(">=", vec![var(), count]),
Expr::UnquoteSplicing(Box::new(results)),
let expansion = Expr::Quasiquote(Box::new(Expr::List(vec![
Expr::symbol("DO"),
bindings,
end,
let extra_result = call("CDR", vec![call("CDR", vec![call("CDR", vec![spec()])])]);
let refuse = call(
"ERROR",
Expr::Quote(Box::new(Expr::symbol("DOTIMES"))),
Expr::String("DOTIMES takes at most one result form".to_string()),
);
let body = call(
"PROGN",
vec![call("IF", vec![extra_result, refuse]), expansion],
Expr::Lambda(params, Box::new(body))