diff options
| -rw-r--r-- | docs/primitives.md | 60 | ||||
| -rw-r--r-- | src/primitives.c | 5 |
2 files changed, 64 insertions, 1 deletions
diff --git a/docs/primitives.md b/docs/primitives.md index fc2d0e4..749b6c0 100644 --- a/docs/primitives.md +++ b/docs/primitives.md @@ -1,5 +1,22 @@ # Primitives +**(assert *expression*)** + +Evaluates *expression*. If *expression* evaluates to a non-false, +non-control-flow value, `assert` returns `#t`. Otherwise, it signals an error +indicating that the assertion failed, including the string representation of +the original *expression*. + +```lisp +(assert (= 1 1)) +;; -> #t + +(assert (> 1 2)) +;; -> Error +``` + +--- + **(assert-exception *form*)** Evaluates *form*. If *form* evaluates to an exception signal, @@ -107,3 +124,46 @@ This primitive immediately exits the innermost enclosing loop or iteration const ;; 5 ;; -> () ``` + +--- + +**(eval *expression*)** + +Evaluates *expression* and returns its result. This primitive is typically used to evaluate code that is constructed or obtained at runtime. + +```lisp +(eval '(+ 1 2)) +;; -> 3 + +(eval '(* 3 4)) +;; -> 12 + +(defvar my-expression '(+ 10 20)) +(eval my-expression) +;; -> 30 +``` + +--- + +**(unwind-protect *protected-form* *cleanup-form* \&rest *more-cleanup-forms*)** + +Evaluates *protected-form*. After *protected-form* is evaluated, whether it completes normally or exits via a non-local exit (like an error or a `return`), each *cleanup-form* is evaluated sequentially. The return value of `unwind-protect` is the result of *protected-form*. This primitive is crucial for ensuring that cleanup actions (like closing files or releasing resources) always occur. + +```lisp +(unwind-protect + (progn (print "Doing something...") + (/ 10 2)) + (print "Cleaning up!")) +;; "Doing something..." +;; "Cleaning up!" +;; -> 5 + +(unwind-protect + (progn (print "About to error...") + (error "error!")) + (print "Still cleaning up!")) +;; "About to error..." +;; "Still cleaning up!" +;; -> Error +``` + diff --git a/src/primitives.c b/src/primitives.c index 73812b8..e5e65e3 100644 --- a/src/primitives.c +++ b/src/primitives.c @@ -106,8 +106,11 @@ SExpRef primitive_assert(Interp *interp, SExpRef args, bool istail) { } SExpRef primitive_eval(Interp *interp, SExpRef args, bool istail) { + if (LENGTH(args) != 1) { + return new_error(interp, "eval: syntax error."); + } args = lisp_eval_args(interp, args); - return lisp_eval(interp, args, istail); + return lisp_eval(interp, CAR(args), istail); } SExpRef primitive_unwind_protect(Interp *interp, SExpRef args, bool istail) { |
