blob: a81b26dc6fa5e0c6748c645cbd7af4bff0783a43 (
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 =DEFVALIDATOR= 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: baslically just a wrapper around =ASSERT=.
The real "magic" happens when validation functions are defined in terms of other validation functions. In that case, error messages are nested to produce high-specific locations 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.
(defvalidator (pt point)
(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 gthe
;; VALID-POLY-P validator.
(defvalidator (p polygon :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 =DEFVALIDATOR= for use details.
|