Table of Contents
1 TERRAFIRMA
Terrafirma is a small system for defining data type validators that produce nice error messages on invalid data.
Terrafirma's main export is the DEFINE-VALID
macro. This macro defines a validator function. The body of the validator function evalutes in a special context. Within this context, the symbol VALIDATE
is a macro that can be used to check predicates and singal a VALIDATION-ERROR
upon failure: basically just a wrapper around ASSERT
.
The real "magic" happens when validation functions are defined in terms of other validation functions. In that case, validation errors are nested to produce highly-specific messages for your validation error.
Here is an example:
(defpackage #:geom (:use #:cl #:terrafirma)) (in-package :geom) (defclass point () ((x :initarg :x) (y :initarg :y))) ;; defines a function called VALID-POINT-P. By default the name of the ;; type is used to create the validator function's name. (define-valid point (pt) (validate (and (slot-boundp pt 'x) (slot-boundp pt 'y)) "Both X and Y must be bound.") (with-slots (x y) pt (validate (numberp x) "X = ~s is not a number" x) (validate (numberp y) "Y = ~s is not a number" y))) (defclass polygon () ((verts :initarg :verts :type (cons point)))) ;; defines a function called VALID-POLY-P. Here we pass a specific ;; name in. We also define this validator in terms of the ;; VALID-POLY-P validator. (define-valid polygon (p :name valid-poly-p) (validate (slot-boundp p 'verts) "VERTS must be bound.") (let ((verts (slot-value p 'verts))) (validate (< 2 (length verts)) "VERTS must contain at least three points.") (validate (every #'valid-point-p verts) "VERTS contains an invalid point."))) (defun poly (&rest coords) (make-instance 'polygon :verts (loop :for (x y) :on coords :by #'cddr :collect (make-instance 'point :x x :y y))))
Now, call VALID-POLY-P
on a couple of bad polygons.
(valid-poly-p (poly 1 2 3 4)) ;; Error validating POLYGON: VERTS must contain at least three points. ;; [Condition of type VALIDATION-ERROR] (valid-poly-p (poly 1 2 "foo" 10 11 20)) ;; Error validating POLYGON: VERTS contains an invalid point. ;; More specifically: ;; Error validating POINT: X = "foo" is not a number ;; [Condition of type VALIDATION-ERROR]
See the docstring on DEFINE-VALID
for use details.
Created: 2023-11-30 Thu 21:03