chiark / gitweb /
anaphora: Rename package to just `anaphora'.
[lisp] / mdw-base.lisp
1 ;;; -*-lisp-*-
2 ;;;
3 ;;; $Id$
4 ;;;
5 ;;; Basic definitions
6 ;;;
7 ;;; (c) 2005 Mark Wooding
8 ;;;
9
10 ;;;----- Licensing notice ---------------------------------------------------
11 ;;;
12 ;;; This program is free software; you can redistribute it and/or modify
13 ;;; it under the terms of the GNU General Public License as published by
14 ;;; the Free Software Foundation; either version 2 of the License, or
15 ;;; (at your option) any later version.
16 ;;; 
17 ;;; This program is distributed in the hope that it will be useful,
18 ;;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20 ;;; GNU General Public License for more details.
21 ;;; 
22 ;;; You should have received a copy of the GNU General Public License
23 ;;; along with this program; if not, write to the Free Software Foundation,
24 ;;; Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
25
26 ;;;--------------------------------------------------------------------------
27 ;;; Package things.
28
29 (defpackage #:mdw.base
30   (:use #:common-lisp)
31   (:export #:compile-time-defun
32            #:show
33            #:stringify #:listify #:fix-pair #:pairify #:parse-body
34            #:whitespace-char-p
35            #:slot-uninitialized
36            #:nlet #:while #:case2 #:ecase2
37            #:with-gensyms #:let*/gensyms #:with-places
38            #:locp #:locf #:ref #:with-locatives
39            #:update-place #:update-place-after
40            #:incf-after #:decf-after))
41 (in-package #:mdw.base)
42
43 ;;;--------------------------------------------------------------------------
44 ;;; Some simple macros to get things going.
45
46 (defmacro compile-time-defun (name args &body body)
47   "Define a function which can be used by macros during the compilation
48    process."
49   `(eval-when (:compile-toplevel :load-toplevel)
50      (defun ,name ,args ,@body)))
51
52 (defmacro show (x)
53   "Debugging tool: print the expression X and its value."
54   (let ((tmp (gensym)))
55     `(let ((,tmp ,x))
56        (format t "~&~S: ~S~%" ',x ,tmp)
57        ,tmp)))
58
59 (defun stringify (str)
60   "Return a string representation of STR.  Strings are returned unchanged;
61    symbols are converted to their names (unqualified!).  Other objects are
62    converted to their print representations."
63   (typecase str
64     (string str)
65     (symbol (symbol-name str))
66     (t (with-output-to-string (s)
67          (princ str s)))))
68
69 (compile-time-defun listify (x)
70   "If X is a (possibly empty) list, return X; otherwise return (list X)."
71   (if (listp x) x (list x)))
72
73 (compile-time-defun do-fix-pair (x y defaultp)
74   "Helper function for fix-pair and pairify."
75   (flet ((singleton (x) (values x (if defaultp y x))))
76     (cond ((atom x) (singleton x))
77           ((null (cdr x)) (singleton (car x)))
78           ((atom (cdr x)) (values (car x) (cdr x)))
79           ((cddr x) (error "Too many elements for a pair."))
80           (t (values (car x) (cadr x))))))
81
82 (compile-time-defun fix-pair (x &optional (y nil defaultp))
83   "Return two values extracted from X.  It works as follows:
84      (A) -> A, Y
85      (A B) -> A, B
86      (A B . C) -> error
87      (A . B) -> A, B
88      A -> A, Y
89    where Y defaults to A if not specified."
90   (do-fix-pair x y defaultp))
91
92 (compile-time-defun pairify (x &optional (y nil defaultp))
93   "As for fix-pair, but returns a list instead of two values."
94   (multiple-value-call #'list (do-fix-pair x y defaultp)))
95
96 (defun whitespace-char-p (ch)
97   "Return whether CH is a whitespace character or not."
98   (case ch
99     ((#\space #\tab #\newline #\return #\vt #\formfeed) t)
100     (t nil)))
101
102 (declaim (ftype (function nil ()) slot-unitialized))
103 (defun slot-uninitialized ()
104   "A function which signals an error.  Can be used as an initializer form in
105    structure definitions without doom ensuing."
106   (error "No initializer for slot."))
107
108 (compile-time-defun parse-body (body &key (allow-docstring-p t))
109   "Given a BODY (a list of forms), parses it into three sections: a
110    docstring, a list of declarations (forms beginning with the symbol
111    `declare') and the body forms.  The result is returned as three lists
112    (even the docstring), suitable for interpolation into a backquoted list
113    using `@,'.  If ALLOW-DOCSTRING-P is nil, docstrings aren't allowed at
114    all."
115   (let ((doc nil) (decls nil))
116     (do ((forms body (cdr forms))) (nil)
117       (let ((form (and forms (car forms))))
118         (cond ((and allow-docstring-p (not doc) (stringp form) (cdr forms))
119                (setf doc form))
120               ((and (consp form)
121                     (eq (car form) 'declare))
122                (setf decls (append decls (cdr form))))
123               (t (return (values (and doc (list doc))
124                                  (and decls (list (cons 'declare decls)))
125                                  forms))))))))
126
127 ;;;--------------------------------------------------------------------------
128 ;;; Generating symbols.
129
130 (defmacro with-gensyms (syms &body body)
131   "Everyone's favourite macro helper."
132   `(let (,@(mapcar (lambda (sym) `(,sym (gensym ,(symbol-name sym))))
133                    (listify syms)))
134      ,@body))
135
136 (defmacro let*/gensyms (binds &body body)
137   "A macro helper.  BINDS is a list of binding pairs (VAR VALUE), where VALUE
138    defaults to VAR.  The result is that BODY is evaluated in a context where
139    each VAR is bound to a gensym, and in the final expansion, each of those
140    gensyms will be bound to the corresponding VALUE."
141   (labels ((more (binds)
142              (let ((tmp (gensym "TMP")) (bind (car binds)))
143                `((let ((,tmp ,(cadr bind))
144                        (,(car bind) (gensym ,(symbol-name (car bind)))))
145                    `(let ((,,(car bind) ,,tmp))
146                       ,,@(if (cdr binds)
147                              (more (cdr binds))
148                              body)))))))
149     (if (null binds)
150         `(progn ,@body)
151         (car (more (mapcar #'pairify (listify binds)))))))
152
153 ;;;--------------------------------------------------------------------------
154 ;;; Some simple yet useful control structures.
155
156 (defmacro nlet (name binds &body body)
157   "Scheme's named let."
158   (multiple-value-bind (vars vals)
159       (loop for bind in binds
160             for (var val) = (pairify bind nil)
161             collect var into vars
162             collect val into vals
163             finally (return (values vars vals)))
164     `(labels ((,name ,vars
165                 ,@body))
166        (,name ,@vals))))
167
168 (defmacro while (cond &body body)
169   "If COND is false, evaluate to nil; otherwise evaluate BODY and try again."
170   `(loop
171      (unless ,cond (return))
172      ,@body))
173
174 (compile-time-defun do-case2-like (kind vform clauses)
175   "Helper function for `case2' and `ecase2'."
176   (with-gensyms (scrutinee argument)
177     `(multiple-value-bind (,scrutinee ,argument) ,vform
178        (declare (ignorable ,argument))
179        (,kind ,scrutinee
180          ,@(mapcar (lambda (clause)
181                      (destructuring-bind
182                          (cases (&optional varx vary) &rest forms)
183                          clause
184                        `(,cases
185                          ,@(if varx
186                                (list `(let ((,(or vary varx) ,argument)
187                                             ,@(and vary
188                                                    `((,varx ,scrutinee))))
189                                         ,@forms))
190                                forms))))
191                    clauses)))))
192
193 (defmacro case2 (vform &body clauses)
194   "VFORM is a form which evaluates to two values, SCRUTINEE and ARGUMENT.
195    The CLAUSES have the form (CASES ([[SCRUVAR] ARGVAR]) FORMS...), where a
196    standard `case' clause has the form (CASES FORMS...).  The `case2' form
197    evaluates the VFORM, and compares the SCRUTINEE to the various CASES, in
198    order, just like `case'.  If there is a match, then the corresponding
199    FORMs are evaluated with ARGVAR bound to the ARGUMENT and SCRUVAR bound to
200    the SCRUTINEE (where specified).  Note the bizarre defaulting behaviour:
201    ARGVAR is less optional than SCRUVAR."
202   (do-case2-like 'case vform clauses))
203
204 (defmacro ecase2 (vform &body clauses)
205   "Like `case2', but signals an error if no clause matches the SCRUTINEE."
206   (do-case2-like 'ecase vform clauses))
207
208 ;;;--------------------------------------------------------------------------
209 ;;; with-places
210
211 (defmacro %place-ref (getform setform newtmp)
212   "Grim helper macro for with-places."
213   (declare (ignore setform newtmp))
214   getform)
215
216 (define-setf-expander %place-ref (getform setform newtmp)
217   "Grim helper macro for with-places."
218   (values nil nil newtmp setform getform))
219
220 (defmacro with-places ((&key environment) places &body body)
221   "A hairy helper, for writing setf-like macros.  PLACES is a list of binding
222    pairs (VAR PLACE), where PLACE defaults to VAR.  The result is that BODY
223    is evaluated in a context where each VAR is bound to a gensym, and in the
224    final expansion, each of those gensyms will be bound to a symbol-macro
225    capable of reading or setting the value of the corresponding PLACE."
226   (if (null places)
227       `(progn ,@body)
228       (let*/gensyms (environment)
229         (labels
230             ((more (places)
231                (let ((place (car places)))
232                  (with-gensyms (tmp valtmps valforms
233                                     newtmps setform getform)
234                    `((let ((,tmp ,(cadr place))
235                            (,(car place)
236                             (gensym ,(symbol-name (car place)))))
237                        (multiple-value-bind
238                            (,valtmps ,valforms
239                             ,newtmps ,setform ,getform)
240                            (get-setf-expansion ,tmp
241                                                ,environment)
242                          (list 'let*
243                                (mapcar #'list ,valtmps ,valforms)
244                                `(symbol-macrolet ((,,(car place)
245                                                    (%place-ref ,,getform
246                                                                ,,setform
247                                                                ,,newtmps)))
248                                   ,,@(if (cdr places)
249                                          (more (cdr places))
250                                          body))))))))))
251           (car (more (mapcar #'pairify (listify places))))))))
252
253 ;;;--------------------------------------------------------------------------
254 ;;; Update-in-place macros built using with-places.
255
256 (defmacro update-place (op place arg &environment env)
257   "Update PLACE with the value of OP PLACE ARG, returning the new value."
258   (with-places (:environment env) (place)
259     `(setf ,place (,op ,place ,arg))))
260
261 (defmacro update-place-after (op place arg &environment env)
262   "Update PLACE with the value of OP PLACE ARG, returning the old value."
263   (with-places (:environment env) (place)
264     (with-gensyms (x)
265       `(let ((,x ,place))
266          (setf ,place (,op ,x ,arg))
267          ,x))))
268
269 (defmacro incf-after (place &optional (by 1))
270   "Increment PLACE by BY, returning the old value."
271   `(update-place-after + ,place ,by))
272
273 (defmacro decf-after (place &optional (by 1))
274   "Decrement PLACE by BY, returning the old value."
275   `(update-place-after - ,place ,by))
276
277 ;;;--------------------------------------------------------------------------
278 ;;; Locatives.
279
280 (defstruct (loc (:predicate locp) (:constructor make-loc (reader writer)))
281   "Locative data type.  See `locf' and `ref'."
282   (reader (slot-uninitialized) :type function)
283   (writer (slot-uninitialized) :type function))
284
285 (defmacro locf (place &environment env)
286   "Slightly cheesy locatives.  (locf PLACE) returns an object which, using
287    the `ref' function, can be used to read or set the value of PLACE.  It's
288    cheesy because it uses closures rather than actually taking the address of
289    something.  Also, unlike Zetalisp, we don't overload `car' to do our dirty
290    work."
291   (multiple-value-bind
292       (valtmps valforms newtmps setform getform)
293       (get-setf-expansion place env)
294     `(let* (,@(mapcar #'list valtmps valforms))
295        (make-loc (lambda () ,getform)
296                  (lambda (,@newtmps) ,setform)))))
297
298 (declaim (inline loc (setf loc)))
299
300 (defun ref (loc)
301   "Fetch the value referred to by a locative."
302   (funcall (loc-reader loc)))
303
304 (defun (setf ref) (new loc)
305   "Store a new value in the place referred to by a locative."
306   (funcall (loc-writer loc) new))
307
308 (defmacro with-locatives (locs &body body)
309   "LOCS is a list of items of the form (SYM [LOC-EXPR]), where SYM is a
310    symbol and LOC-EXPR evaluates to a locative.  If LOC-EXPR is omitted, it
311    defaults to SYM.  As an abbreviation for a common case, LOCS may be a
312    symbol instead of a list.  The BODY is evaluated in an environment where
313    each SYM is a symbol macro which expands to (ref LOC-EXPR) -- or, in fact,
314    something similar which doesn't break if LOC-EXPR has side-effects.  Thus,
315    references, including `setf' forms, fetch or modify the thing referred to
316    by the LOC-EXPR.  Useful for covering over where something uses a
317    locative."
318   (setf locs (mapcar #'pairify (listify locs)))
319   (let ((tt (mapcar (lambda (l) (declare (ignore l)) (gensym)) locs))
320         (ll (mapcar #'cadr locs))
321         (ss (mapcar #'car locs)))
322     `(let (,@(mapcar (lambda (tmp loc) `(,tmp ,loc)) tt ll))
323        (symbol-macrolet (,@(mapcar (lambda (sym tmp)
324                                      `(,sym (ref ,tmp))) ss tt))
325          ,@body))))
326
327 ;;;----- That's all, folks --------------------------------------------------