base: with-parsed-body, different interface.
[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 #:unsigned-fixnum
32 #:compile-time-defun
33 #:show
34 #:stringify #:mappend #:listify #:fix-pair #:pairify
35 #:parse-body #:with-parsed-body
36 #:whitespace-char-p
37 #:slot-uninitialized
38 #:nlet #:while #:until #:case2 #:ecase2 #:setf-default
39 #:with-gensyms #:let*/gensyms #:with-places
40 #:locp #:locf #:ref #:with-locatives
41 #:update-place #:update-place-after
42 #:incf-after #:decf-after
43 #:fixnump)
44 #+cmu (:import-from #:extensions #:fixnump))
45
46 (in-package #:mdw.base)
47
48 ;;;--------------------------------------------------------------------------
49 ;;; Useful types.
50
51 (deftype unsigned-fixnum ()
52 "Unsigned fixnums; useful as array indices and suchlike."
53 `(mod ,most-positive-fixnum))
54
55 ;;;--------------------------------------------------------------------------
56 ;;; Some simple macros to get things going.
57
58 (defmacro compile-time-defun (name args &body body)
59 "Define a function which can be used by macros during the compilation
60 process."
61 `(eval-when (:compile-toplevel :load-toplevel :execute)
62 (defun ,name ,args ,@body)))
63
64 (defmacro show (x)
65 "Debugging tool: print the expression X and its values."
66 (let ((tmp (gensym)))
67 `(let ((,tmp (multiple-value-list ,x)))
68 (format t "~&")
69 (pprint-logical-block (*standard-output* nil :per-line-prefix ";; ")
70 (format t
71 "~S = ~@_~:I~:[#<no values>~;~:*~{~S~^ ~_~}~]"
72 ',x
73 ,tmp))
74 (terpri)
75 (values-list ,tmp))))
76
77 (defun stringify (str)
78 "Return a string representation of STR. Strings are returned unchanged;
79 symbols are converted to their names (unqualified!). Other objects are
80 converted to their print representations."
81 (typecase str
82 (string str)
83 (symbol (symbol-name str))
84 (t (with-output-to-string (s)
85 (princ str s)))))
86
87 (defun mappend (function list &rest more-lists)
88 "Apply FUNCTION to corresponding elements of LIST and MORE-LISTS, yielding
89 a list. Return the concatenation of all the resulting lists. Like
90 mapcan, but nondestructive."
91 (apply #'append (apply #'mapcar function list more-lists)))
92
93 (compile-time-defun listify (x)
94 "If X is a (possibly empty) list, return X; otherwise return (list X)."
95 (if (listp x) x (list x)))
96
97 (compile-time-defun do-fix-pair (x y defaultp)
98 "Helper function for fix-pair and pairify."
99 (flet ((singleton (x) (values x (if defaultp y x))))
100 (cond ((atom x) (singleton x))
101 ((null (cdr x)) (singleton (car x)))
102 ((atom (cdr x)) (values (car x) (cdr x)))
103 ((cddr x) (error "Too many elements for a pair."))
104 (t (values (car x) (cadr x))))))
105
106 (compile-time-defun fix-pair (x &optional (y nil defaultp))
107 "Return two values extracted from X. It works as follows:
108 (A) -> A, Y
109 (A B) -> A, B
110 (A B . C) -> error
111 (A . B) -> A, B
112 A -> A, Y
113 where Y defaults to A if not specified."
114 (do-fix-pair x y defaultp))
115
116 (compile-time-defun pairify (x &optional (y nil defaultp))
117 "As for fix-pair, but returns a list instead of two values."
118 (multiple-value-call #'list (do-fix-pair x y defaultp)))
119
120 (defun whitespace-char-p (ch)
121 "Return whether CH is a whitespace character or not."
122 (case ch
123 ((#\space #\tab #\newline #\return #\vt
124 #+cmu #\formfeed
125 #+clisp #\page) t)
126 (t nil)))
127
128 (declaim (ftype (function nil ()) slot-unitialized))
129 (defun slot-uninitialized ()
130 "A function which signals an error. Can be used as an initializer form in
131 structure definitions without doom ensuing."
132 (error "No initializer for slot."))
133
134 (compile-time-defun parse-body (body &key (allow-docstring-p t))
135 "Given a BODY (a list of forms), parses it into three sections: a
136 docstring, a list of declarations (forms beginning with the symbol
137 `declare') and the body forms. The result is returned as three lists
138 (even the docstring), suitable for interpolation into a backquoted list
139 using `@,'. If ALLOW-DOCSTRING-P is nil, docstrings aren't allowed at
140 all."
141 (let ((doc nil) (decls nil))
142 (do ((forms body (cdr forms))) (nil)
143 (let ((form (and forms (car forms))))
144 (cond ((and allow-docstring-p (not doc) (stringp form) (cdr forms))
145 (setf doc form))
146 ((and (consp form)
147 (eq (car form) 'declare))
148 (setf decls (append decls (cdr form))))
149 (t (return (values (and doc (list doc))
150 (and decls (list (cons 'declare decls)))
151 forms))))))))
152
153 (defmacro with-parsed-body
154 ((bodyvar declvar &optional (docvar (gensym) docp)) form &body body)
155 "Parse FORM into a body, declarations and (maybe) a docstring; bind BODYVAR
156 to the body, DECLVAR to the declarations, and DOCVAR to (a list
157 containing) the docstring, and evaluate BODY."
158 `(multiple-value-bind
159 (,docvar ,declvar ,bodyvar)
160 (parse-body ,form :allow-docstring-p ,docp)
161 ,@(if docp nil `((declare (ignore ,docvar))))
162 ,@body))
163
164 #-cmu
165 (progn
166 (declaim (inline fixnump))
167 (defun fixnump (object)
168 "Answer non-nil if OBJECT is a fixnum, or nil if it isn't."
169 (typep object 'fixnum)))
170
171 ;;;--------------------------------------------------------------------------
172 ;;; Generating symbols.
173
174 (defmacro with-gensyms (syms &body body)
175 "Everyone's favourite macro helper."
176 `(let (,@(mapcar (lambda (sym) `(,sym (gensym ,(symbol-name sym))))
177 (listify syms)))
178 ,@body))
179
180 (defmacro let*/gensyms (binds &body body)
181 "A macro helper. BINDS is a list of binding pairs (VAR VALUE), where VALUE
182 defaults to VAR. The result is that BODY is evaluated in a context where
183 each VAR is bound to a gensym, and in the final expansion, each of those
184 gensyms will be bound to the corresponding VALUE."
185 (labels ((more (binds)
186 (let ((tmp (gensym "TMP")) (bind (car binds)))
187 `((let ((,tmp ,(cadr bind))
188 (,(car bind) (gensym ,(symbol-name (car bind)))))
189 `(let ((,,(car bind) ,,tmp))
190 ,,@(if (cdr binds)
191 (more (cdr binds))
192 body)))))))
193 (if (null binds)
194 `(progn ,@body)
195 (car (more (mapcar #'pairify (listify binds)))))))
196
197 ;;;--------------------------------------------------------------------------
198 ;;; Some simple yet useful control structures.
199
200 (defmacro nlet (name binds &body body)
201 "Scheme's named let."
202 (multiple-value-bind (vars vals)
203 (loop for bind in binds
204 for (var val) = (pairify bind nil)
205 collect var into vars
206 collect val into vals
207 finally (return (values vars vals)))
208 `(labels ((,name ,vars
209 ,@body))
210 (,name ,@vals))))
211
212 (defmacro while (cond &body body)
213 "If COND is false, evaluate to nil; otherwise evaluate BODY and try again."
214 `(loop (unless ,cond (return)) (progn ,@body)))
215
216 (defmacro until (cond &body body)
217 "If COND is true, evaluate to nil; otherwise evaluate BODY and try again."
218 `(loop (when ,cond (return)) (progn ,@body)))
219
220 (compile-time-defun do-case2-like (kind vform clauses)
221 "Helper function for `case2' and `ecase2'."
222 (with-gensyms (scrutinee argument)
223 `(multiple-value-bind (,scrutinee ,argument) ,vform
224 (declare (ignorable ,argument))
225 (,kind ,scrutinee
226 ,@(mapcar (lambda (clause)
227 (destructuring-bind
228 (cases (&optional varx vary) &rest forms)
229 clause
230 `(,cases
231 ,@(if varx
232 (list `(let ((,(or vary varx) ,argument)
233 ,@(and vary
234 `((,varx ,scrutinee))))
235 ,@forms))
236 forms))))
237 clauses)))))
238
239 (defmacro case2 (vform &body clauses)
240 "VFORM is a form which evaluates to two values, SCRUTINEE and ARGUMENT.
241 The CLAUSES have the form (CASES ([[SCRUVAR] ARGVAR]) FORMS...), where a
242 standard `case' clause has the form (CASES FORMS...). The `case2' form
243 evaluates the VFORM, and compares the SCRUTINEE to the various CASES, in
244 order, just like `case'. If there is a match, then the corresponding
245 FORMs are evaluated with ARGVAR bound to the ARGUMENT and SCRUVAR bound to
246 the SCRUTINEE (where specified). Note the bizarre defaulting behaviour:
247 ARGVAR is less optional than SCRUVAR."
248 (do-case2-like 'case vform clauses))
249
250 (defmacro ecase2 (vform &body clauses)
251 "Like `case2', but signals an error if no clause matches the SCRUTINEE."
252 (do-case2-like 'ecase vform clauses))
253
254 (defmacro setf-default (&rest specs &environment env)
255 "Like setf, but only sets places which are currently nil.
256
257 The arguments are an alternating list of PLACEs and DEFAULTs. If a PLACE
258 is nil, the DEFAULT is evaluated and stored in the PLACE; otherwise the
259 default is /not/ stored. The result is the (new) value of the last
260 PLACE."
261 (labels ((doit (specs)
262 (cond ((null specs) nil)
263 ((null (cdr specs))
264 (error "Odd number of arguments for SETF-DEFAULT."))
265 (t
266 (let ((place (car specs))
267 (default (cadr specs))
268 (rest (cddr specs)))
269 (multiple-value-bind
270 (vars vals store-vals writer reader)
271 (get-setf-expansion place env)
272 `(let* ,(mapcar #'list vars vals)
273 (or ,reader
274 (multiple-value-bind ,store-vals ,default
275 ,writer))
276 ,@(and rest (list (doit rest))))))))))
277 (doit specs)))
278
279 ;;;--------------------------------------------------------------------------
280 ;;; with-places
281
282 (defmacro %place-ref (getform setform newtmp)
283 "Grim helper macro for with-places."
284 (declare (ignore setform newtmp))
285 getform)
286
287 (define-setf-expander %place-ref (getform setform newtmp)
288 "Grim helper macro for with-places."
289 (values nil nil newtmp setform getform))
290
291 (defmacro with-places ((&key environment) places &body body)
292 "A hairy helper, for writing setf-like macros. PLACES is a list of binding
293 pairs (VAR PLACE), where PLACE defaults to VAR. The result is that BODY
294 is evaluated in a context where each VAR is bound to a gensym, and in the
295 final expansion, each of those gensyms will be bound to a symbol-macro
296 capable of reading or setting the value of the corresponding PLACE."
297 (if (null places)
298 `(progn ,@body)
299 (let*/gensyms (environment)
300 (labels
301 ((more (places)
302 (let ((place (car places)))
303 (with-gensyms (tmp valtmps valforms
304 newtmps setform getform)
305 `((let ((,tmp ,(cadr place))
306 (,(car place)
307 (gensym ,(symbol-name (car place)))))
308 (multiple-value-bind
309 (,valtmps ,valforms
310 ,newtmps ,setform ,getform)
311 (get-setf-expansion ,tmp
312 ,environment)
313 (list 'let*
314 (mapcar #'list ,valtmps ,valforms)
315 `(symbol-macrolet ((,,(car place)
316 (%place-ref ,,getform
317 ,,setform
318 ,,newtmps)))
319 ,,@(if (cdr places)
320 (more (cdr places))
321 body))))))))))
322 (car (more (mapcar #'pairify (listify places))))))))
323
324 ;;;--------------------------------------------------------------------------
325 ;;; Update-in-place macros built using with-places.
326
327 (defmacro update-place (op place arg &environment env)
328 "Update PLACE with the value of OP PLACE ARG, returning the new value."
329 (with-places (:environment env) (place)
330 `(setf ,place (,op ,place ,arg))))
331
332 (defmacro update-place-after (op place arg &environment env)
333 "Update PLACE with the value of OP PLACE ARG, returning the old value."
334 (with-places (:environment env) (place)
335 (with-gensyms (x)
336 `(let ((,x ,place))
337 (setf ,place (,op ,x ,arg))
338 ,x))))
339
340 (defmacro incf-after (place &optional (by 1))
341 "Increment PLACE by BY, returning the old value."
342 `(update-place-after + ,place ,by))
343
344 (defmacro decf-after (place &optional (by 1))
345 "Decrement PLACE by BY, returning the old value."
346 `(update-place-after - ,place ,by))
347
348 ;;;--------------------------------------------------------------------------
349 ;;; Locatives.
350
351 (defstruct (loc (:predicate locp) (:constructor make-loc (reader writer)))
352 "Locative data type. See `locf' and `ref'."
353 (reader (slot-uninitialized) :type function)
354 (writer (slot-uninitialized) :type function))
355
356 (defmacro locf (place &environment env)
357 "Slightly cheesy locatives. (locf PLACE) returns an object which, using
358 the `ref' function, can be used to read or set the value of PLACE. It's
359 cheesy because it uses closures rather than actually taking the address of
360 something. Also, unlike Zetalisp, we don't overload `car' to do our dirty
361 work."
362 (multiple-value-bind
363 (valtmps valforms newtmps setform getform)
364 (get-setf-expansion place env)
365 `(let* (,@(mapcar #'list valtmps valforms))
366 (make-loc (lambda () ,getform)
367 (lambda (,@newtmps) ,setform)))))
368
369 (declaim (inline loc (setf loc)))
370
371 (defun ref (loc)
372 "Fetch the value referred to by a locative."
373 (funcall (loc-reader loc)))
374
375 (defun (setf ref) (new loc)
376 "Store a new value in the place referred to by a locative."
377 (funcall (loc-writer loc) new))
378
379 (defmacro with-locatives (locs &body body)
380 "LOCS is a list of items of the form (SYM [LOC-EXPR]), where SYM is a
381 symbol and LOC-EXPR evaluates to a locative. If LOC-EXPR is omitted, it
382 defaults to SYM. As an abbreviation for a common case, LOCS may be a
383 symbol instead of a list. The BODY is evaluated in an environment where
384 each SYM is a symbol macro which expands to (ref LOC-EXPR) -- or, in fact,
385 something similar which doesn't break if LOC-EXPR has side-effects. Thus,
386 references, including `setf' forms, fetch or modify the thing referred to
387 by the LOC-EXPR. Useful for covering over where something uses a
388 locative."
389 (setf locs (mapcar #'pairify (listify locs)))
390 (let ((tt (mapcar (lambda (l) (declare (ignore l)) (gensym)) locs))
391 (ll (mapcar #'cadr locs))
392 (ss (mapcar #'car locs)))
393 `(let (,@(mapcar (lambda (tmp loc) `(,tmp ,loc)) tt ll))
394 (symbol-macrolet (,@(mapcar (lambda (sym tmp)
395 `(,sym (ref ,tmp))) ss tt))
396 ,@body))))
397
398 ;;;----- That's all, folks --------------------------------------------------