General tidying and prettifying.
[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
34 #:whitespace-char-p
35 #:slot-uninitialized
36 #:with-gensyms #:let*/gensyms #:with-places
37 #:locp #:locf #:ref #:with-locatives
38 #:update-place #:update-place-after
39 #:incf-after #:decf-after))
40 (in-package #:mdw.base)
41
42 ;;;--------------------------------------------------------------------------
43 ;;; Some simple macros to get things going.
44
45 (defmacro compile-time-defun (name args &body body)
46 "Define a function which can be used by macros during the compilation
47 process."
48 `(eval-when (:compile-toplevel :load-toplevel)
49 (defun ,name ,args ,@body)))
50
51 (defmacro show (x)
52 "Debugging tool: print the expression X and its value."
53 (let ((tmp (gensym)))
54 `(let ((,tmp ,x))
55 (format t "~&~S: ~S~%" ',x ,tmp)
56 ,tmp)))
57
58 (defun stringify (str)
59 "Return a string representation of STR. Strings are returned unchanged;
60 symbols are converted to their names (unqualified!). Other objects are
61 converted to their print representations."
62 (typecase str
63 (string str)
64 (symbol (symbol-name str))
65 (t (with-output-to-string (s)
66 (princ str s)))))
67
68 (compile-time-defun listify (x)
69 "If X is a (possibly empty) list, return X; otherwise return (list X)."
70 (if (listp x) x (list x)))
71
72 (compile-time-defun do-fix-pair (x y defaultp)
73 "Helper function for fix-pair and pairify."
74 (flet ((singleton (x) (values x (if defaultp y x))))
75 (cond ((atom x) (singleton x))
76 ((null (cdr x)) (singleton (car x)))
77 ((atom (cdr x)) (values (car x) (cdr x)))
78 ((cddr x) (error "Too many elements for a pair."))
79 (t (values (car x) (cadr x))))))
80
81 (compile-time-defun fix-pair (x &optional (y nil defaultp))
82 "Return two values extracted from X. It works as follows:
83 (A) -> A, Y
84 (A B) -> A, B
85 (A B . C) -> error
86 (A . B) -> A, B
87 A -> A, Y
88 where Y defaults to A if not specified."
89 (do-fix-pair x y defaultp))
90
91 (compile-time-defun pairify (x &optional (y nil defaultp))
92 "As for fix-pair, but returns a list instead of two values."
93 (multiple-value-call #'list (do-fix-pair x y defaultp)))
94
95 (defun whitespace-char-p (ch)
96 "Return whether CH is a whitespace character or not."
97 (case ch
98 ((#\space #\tab #\newline #\return #\vt #\formfeed) t)
99 (t nil)))
100
101 (defmacro nlet (name binds &body body)
102 "Scheme's named let."
103 (multiple-value-bind (vars vals)
104 (loop for bind in binds
105 for (var val) = (pairify bind nil)
106 collect var into vars
107 collect val into vals
108 finally (return (values vars vals)))
109 `(labels ((,name ,vars
110 ,@body))
111 (,name ,@vals))))
112
113 (defmacro while (cond &body body)
114 "If COND is false, evaluate to nil; otherwise evaluate BODY and try again."
115 `(loop
116 (unless `cond (return))
117 ,@body))
118
119 (declaim (ftype (function nil ()) slot-unitialized))
120 (defun slot-uninitialized ()
121 "A function which signals an error. Can be used as an initializer form in
122 structure definitions without doom ensuing."
123 (error "No initializer for slot."))
124
125 ;;;--------------------------------------------------------------------------
126 ;;; Generating symbols.
127
128 (defmacro with-gensyms (syms &body body)
129 "Everyone's favourite macro helper."
130 `(let (,@(mapcar (lambda (sym) `(,sym (gensym ,(symbol-name sym))))
131 (listify syms)))
132 ,@body))
133
134 (defmacro let*/gensyms (binds &body body)
135 "A macro helper. BINDS is a list of binding pairs (VAR VALUE), where VALUE
136 defaults to VAR. The result is that BODY is evaluated in a context where
137 each VAR is bound to a gensym, and in the final expansion, each of those
138 gensyms will be bound to the corresponding VALUE."
139 (labels ((more (binds)
140 (let ((tmp (gensym "TMP")) (bind (car binds)))
141 `((let ((,tmp ,(cadr bind))
142 (,(car bind) (gensym ,(symbol-name (car bind)))))
143 `(let ((,,(car bind) ,,tmp))
144 ,,@(if (cdr binds)
145 (more (cdr binds))
146 body)))))))
147 (if (null binds)
148 `(progn ,@body)
149 (car (more (mapcar #'pairify (listify binds)))))))
150
151 ;;;--------------------------------------------------------------------------
152 ;;; with-places
153
154 (defmacro %place-ref (getform setform newtmp)
155 "Grim helper macro for with-places."
156 (declare (ignore setform newtmp))
157 getform)
158
159 (define-setf-expander %place-ref (getform setform newtmp)
160 "Grim helper macro for with-places."
161 (values nil nil newtmp setform getform))
162
163 (defmacro with-places ((&key environment) places &body body)
164 "A hairy helper, for writing setf-like macros. PLACES is a list of binding
165 pairs (VAR PLACE), where PLACE defaults to VAR. The result is that BODY is
166 evaluated in a context where each VAR is bound to a gensym, and in the final
167 expansion, each of those gensyms will be bound to a symbol-macro capable of
168 reading or setting the value of the corresponding PLACE."
169 (if (null places)
170 `(progn ,@body)
171 (let*/gensyms (environment)
172 (labels
173 ((more (places)
174 (let ((place (car places)))
175 (with-gensyms (tmp valtmps valforms
176 newtmps setform getform)
177 `((let ((,tmp ,(cadr place))
178 (,(car place)
179 (gensym ,(symbol-name (car place)))))
180 (multiple-value-bind
181 (,valtmps ,valforms
182 ,newtmps ,setform ,getform)
183 (get-setf-expansion ,tmp
184 ,environment)
185 (list 'let*
186 (mapcar #'list ,valtmps ,valforms)
187 `(symbol-macrolet ((,,(car place)
188 (%place-ref ,,getform
189 ,,setform
190 ,,newtmps)))
191 ,,@(if (cdr places)
192 (more (cdr places))
193 body))))))))))
194 (car (more (mapcar #'pairify (listify places))))))))
195
196 ;;;--------------------------------------------------------------------------
197 ;;; Update-in-place macros built using with-places.
198
199 (defmacro update-place (op place arg &environment env)
200 "Update PLACE with the value of OP PLACE ARG, returning the new value."
201 (with-places (:environment env) (place)
202 `(setf ,place (,op ,place ,arg))))
203
204 (defmacro update-place-after (op place arg &environment env)
205 "Update PLACE with the value of OP PLACE ARG, returning the old value."
206 (with-places (:environment env) (place)
207 (with-gensyms (x)
208 `(let ((,x ,place))
209 (setf ,place (,op ,x ,arg))
210 ,x))))
211
212 (defmacro incf-after (place &optional (by 1))
213 "Increment PLACE by BY, returning the old value."
214 `(update-place-after + ,place ,by))
215
216 (defmacro decf-after (place &optional (by 1))
217 "Decrement PLACE by BY, returning the old value."
218 `(update-place-after - ,place ,by))
219
220 ;;;--------------------------------------------------------------------------
221 ;;; Locatives.
222
223 (defstruct (loc (:predicate locp) (:constructor make-loc (reader writer)))
224 "Locative data type. See `locf' and `ref'."
225 (reader (slot-uninitialized) :type function)
226 (writer (slot-uninitialized) :type function))
227
228 (defmacro locf (place &environment env)
229 "Slightly cheesy locatives. (locf PLACE) returns an object which, using
230 the `ref' function, can be used to read or set the value of PLACE. It's
231 cheesy because it uses closures rather than actually taking the address of
232 something. Also, unlike Zetalisp, we don't overload `car' to do our dirty
233 work."
234 (multiple-value-bind
235 (valtmps valforms newtmps setform getform)
236 (get-setf-expansion place env)
237 `(let* (,@(mapcar #'list valtmps valforms))
238 (make-loc (lambda () ,getform)
239 (lambda (,@newtmps) ,setform)))))
240
241 (declaim (inline loc (setf loc)))
242
243 (defun ref (loc)
244 "Fetch the value referred to by a locative."
245 (funcall (loc-reader loc)))
246
247 (defun (setf ref) (new loc)
248 "Store a new value in the place referred to by a locative."
249 (funcall (loc-writer loc) new))
250
251 (defmacro with-locatives (locs &body body)
252 "LOCS is a list of items of the form (SYM [LOC-EXPR]), where SYM is a
253 symbol and LOC-EXPR evaluates to a locative. If LOC-EXPR is omitted, it
254 defaults to SYM. As an abbreviation for a common case, LOCS may be a symbol
255 instead of a list. The BODY is evaluated in an environment where each SYM is
256 a symbol macro which expands to (ref LOC-EXPR) -- or, in fact, something
257 similar which doesn't break if LOC-EXPR has side-effects. Thus, references,
258 including `setf' forms, fetch or modify the thing referred to by the
259 LOC-EXPR. Useful for covering over where something uses a locative."
260 (setf locs (mapcar #'pairify (listify locs)))
261 (let ((tt (mapcar (lambda (l) (declare (ignore l)) (gensym)) locs))
262 (ll (mapcar #'cadr locs))
263 (ss (mapcar #'car locs)))
264 `(let (,@(mapcar (lambda (tmp loc) `(,tmp ,loc)) tt ll))
265 (symbol-macrolet (,@(mapcar (lambda (sym tmp)
266 `(,sym (ref ,tmp))) ss tt))
267 ,@body))))
268
269 ;;;----- That's all, folks --------------------------------------------------