aboutsummaryrefslogtreecommitdiff
path: root/README.org
blob: 690f0539d002afd0a87236494219c8772e26fbee (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
* 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:

#+begin_src lisp

(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))))

#+end_src

Now, call =VALID-POLY-P= on a couple of bad polygons.

#+begin_src lisp
(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]

#+end_src



See the docstring on =DEFINE-VALID= for use details.