How does one write assertions in Emacs Lisp? I know that cl-macs.el has cl-assert and cl-check-type, but I'm wondering if there's a native Emacs way to perform something that basic.

  • 2
    cl-lib is written in Emacs Lisp, how is that not "native"? – npostavs May 5 '16 at 18:20
  • cl-lib is a Common Lisp compatibility library. In many areas, elisp has features that are better or simply different from their Common Lisp counterparts (gv comes to mind). – jch May 5 '16 at 18:49
  • 2
    There isn't. Don't expect something to exist, just because you think it should. Emacs Lisp is pretty minimal after all, so you're much better off either writing it yourself or finding something already written for you. – wasamasa May 5 '16 at 18:57
  • 2
    Besides, assert is not really a “basic” thing. – lunaryorn May 5 '16 at 21:43

Here's an assert macro in elisp based on an expert's advice on emacs mailing list:

(defmacro assert (test-form)
  `(when (not ,test-form)
     (error "Assertion failed: %s" (format "%s" ',test-form))))

(assert (equal t nil))
  • How is that more useful than cl-assert? – jch May 5 '16 at 18:47
  • 7
    You didn't ask for more useful. You asked "how does one write.." Rephrase your question. – Emacs User May 5 '16 at 19:00

I've looked through the Lisp code bundled with Emacs, and I've found that:

  • most files use cl-assert after doing (eval-when-compile (require 'cl-lib));
  • some files use assert after doing (eval-when-compile (require 'cl));
  • there are a small number of specialised assertion macros in the Emacs library, notably check-face and check-coding-system, but they don't seem to be used much;
  • only a very few packages define their own specialised assertion macros, e.g. ibuffer-assert-ibuffer-mode or tramp-check-proper-method-and-host.

One thing that wasn't obvious to me is that cl-assert only requires cl-lib at compile time — in Emacs 25 it expands into a call to cl--assertion-failed which is preloaded, while in Emacs 24 it expands into calls to error and signal.

My conclusion is therefore that one should depend on cl-lib at compile time and use cl-assert, or write specialised macros that expand into cl-assert.

  • 3
    A note for readers on older Emacs: cl--assertion-failed (and cl-preloaded.el) are new in Emacs 25. – npostavs May 8 '16 at 19:03
  • Right, added more information. – jch May 8 '16 at 19:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.