ombre: Implement `env` function for lisp

28f47f401da3ddce846ec14429f15460c41a8422
Alexis Sellier committed ago 1 parent 2040ff04
ombre/src/lisp/evaluator.rs +20 -2
324 324
            Expr::Str(s) => write!(f, "\"{}\"", s.escape_debug()),
325 325
            Expr::Float(n) => write!(f, "{n}"),
326 326
            Expr::Integer(n) => write!(f, "{n}"),
327 327
            Expr::Char(c) => write!(f, "`{c}`"),
328 328
            Expr::Color(c) => write!(f, "#{:02x}{:02x}{:02x}{:02x}", c.r, c.g, c.b, c.a),
329 -
            Expr::Function(e) => write!(f, "<function {:p}>", e.as_ptr()),
329 +
            Expr::Function(e) => write!(f, "<fn {:p}>", e.as_ptr()),
330 330
            Expr::Ref(r) => write!(f, "<ref {}>", r.borrow()),
331 -
            Expr::Dynamic(d) => write!(f, "<dynamic {:p}>", d.as_ptr()),
331 +
            Expr::Dynamic(d) => write!(f, "<dyn {:p}>", d.as_ptr()),
332 332
        }
333 333
    }
334 334
}
335 335
336 336
impl fmt::Display for Key {
633 633
            local: HashMap::default(),
634 634
            docs: HashMap::default(),
635 635
            parent: None,
636 636
            exports: HashSet::default(),
637 637
        };
638 +
        env.intrinsic(
639 +
            "env",
640 +
            "Return the current environment as a dictionary",
641 +
            intrinsic::env,
642 +
        );
638 643
        env.intrinsic("+", "Add two or more numbers", intrinsic::add);
639 644
        env.intrinsic(
640 645
            "-",
641 646
            "Subtract numbers or negate a single number",
642 647
            intrinsic::sub,
1115 1120
            actual: arity,
1116 1121
        })?;
1117 1122
        Err(Error::User(err))
1118 1123
    }
1119 1124
1125 +
    /// Return the program environment.
1126 +
    pub fn env(args: Vec<Expr>, env: &Env<'_>) -> Result<Expr> {
1127 +
        if !args.is_empty() {
1128 +
            return Err(Error::WrongArgumentCount {
1129 +
                expected: 0,
1130 +
                actual: args.len(),
1131 +
            });
1132 +
        }
1133 +
        let dict = env.flatten().into_iter().map(|(k, v)| (Key::Atom(k), v)).collect();
1134 +
1135 +
        Ok(Expr::Dict(dict))
1136 +
    }
1137 +
1120 1138
    /// Get the first item of a list.
1121 1139
    pub fn first(args: Vec<Expr>, _env: &Env<'_>) -> Result<Expr> {
1122 1140
        let arity = args.len();
1123 1141
        let Ok([expr]) = <[_; 1]>::try_from(args) else {
1124 1142
            return Err(Error::WrongArgumentCount {