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