base: Export `nlet' and `while'.
[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 #:nlet #:while
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 (defmacro nlet (name binds &body body)
103 "Scheme's named let."
104 (multiple-value-bind (vars vals)
105 (loop for bind in binds
106 for (var val) = (pairify bind nil)
107 collect var into vars
108 collect val into vals
109 finally (return (values vars vals)))
110 `(labels ((,name ,vars
111 ,@body))
112 (,name ,@vals))))
113
114 (defmacro while (cond &body body)
115 "If COND is false, evaluate to nil; otherwise evaluate BODY and try again."
116 `(loop
117 (unless `cond (return))
118 ,@body))
119
120 (declaim (ftype (function nil ()) slot-unitialized))
121 (defun slot-uninitialized ()
122 "A function which signals an error. Can be used as an initializer form in
123 structure definitions without doom ensuing."
124 (error "No initializer for slot."))
125
126 ;;;--------------------------------------------------------------------------
127 ;;; Generating symbols.
128
129 (defmacro with-gensyms (syms &body body)
130 "Everyone's favourite macro helper."
131 `(let (,@(mapcar (lambda (sym) `(,sym (gensym ,(symbol-name sym))))
132 (listify syms)))
133 ,@body))
134
135 (defmacro let*/gensyms (binds &body body)
136 "A macro helper. BINDS is a list of binding pairs (VAR VALUE), where VALUE
137 defaults to VAR. The result is that BODY is evaluated in a context where
138 each VAR is bound to a gensym, and in the final expansion, each of those
139 gensyms will be bound to the corresponding VALUE."
140 (labels ((more (binds)
141 (let ((tmp (gensym "TMP")) (bind (car binds)))
142 `((let ((,tmp ,(cadr bind))
143 (,(car bind) (gensym ,(symbol-name (car bind)))))
144 `(let ((,,(car bind) ,,tmp))
145 ,,@(if (cdr binds)
146 (more (cdr binds))
147 body)))))))
148 (if (null binds)
149 `(progn ,@body)
150 (car (more (mapcar #'pairify (listify binds)))))))
151
152 ;;;--------------------------------------------------------------------------
153 ;;; with-places
154
155 (defmacro %place-ref (getform setform newtmp)
156 "Grim helper macro for with-places."
157 (declare (ignore setform newtmp))
158 getform)
159
160 (define-setf-expander %place-ref (getform setform newtmp)
161 "Grim helper macro for with-places."
162 (values nil nil newtmp setform getform))
163
164 (defmacro with-places ((&key environment) places &body body)
165 "A hairy helper, for writing setf-like macros. PLACES is a list of binding
166 pairs (VAR PLACE), where PLACE defaults to VAR. The result is that BODY is
167 evaluated in a context where each VAR is bound to a gensym, and in the final
168 expansion, each of those gensyms will be bound to a symbol-macro capable of
169 reading or setting the value of the corresponding PLACE."
170 (if (null places)
171 `(progn ,@body)
172 (let*/gensyms (environment)
173 (labels
174 ((more (places)
175 (let ((place (car places)))
176 (with-gensyms (tmp valtmps valforms
177 newtmps setform getform)
178 `((let ((,tmp ,(cadr place))
179 (,(car place)
180 (gensym ,(symbol-name (car place)))))
181 (multiple-value-bind
182 (,valtmps ,valforms
183 ,newtmps ,setform ,getform)
184 (get-setf-expansion ,tmp
185 ,environment)
186 (list 'let*
187 (mapcar #'list ,valtmps ,valforms)
188 `(symbol-macrolet ((,,(car place)
189 (%place-ref ,,getform
190 ,,setform
191 ,,newtmps)))
192 ,,@(if (cdr places)
193 (more (cdr places))
194 body))))))))))
195 (car (more (mapcar #'pairify (listify places))))))))
196
197 ;;;--------------------------------------------------------------------------
198 ;;; Update-in-place macros built using with-places.
199
200 (defmacro update-place (op place arg &environment env)
201 "Update PLACE with the value of OP PLACE ARG, returning the new value."
202 (with-places (:environment env) (place)
203 `(setf ,place (,op ,place ,arg))))
204
205 (defmacro update-place-after (op place arg &environment env)
206 "Update PLACE with the value of OP PLACE ARG, returning the old value."
207 (with-places (:environment env) (place)
208 (with-gensyms (x)
209 `(let ((,x ,place))
210 (setf ,place (,op ,x ,arg))
211 ,x))))
212
213 (defmacro incf-after (place &optional (by 1))
214 "Increment PLACE by BY, returning the old value."
215 `(update-place-after + ,place ,by))
216
217 (defmacro decf-after (place &optional (by 1))
218 "Decrement PLACE by BY, returning the old value."
219 `(update-place-after - ,place ,by))
220
221 ;;;--------------------------------------------------------------------------
222 ;;; Locatives.
223
224 (defstruct (loc (:predicate locp) (:constructor make-loc (reader writer)))
225 "Locative data type. See `locf' and `ref'."
226 (reader (slot-uninitialized) :type function)
227 (writer (slot-uninitialized) :type function))
228
229 (defmacro locf (place &environment env)
230 "Slightly cheesy locatives. (locf PLACE) returns an object which, using
231 the `ref' function, can be used to read or set the value of PLACE. It's
232 cheesy because it uses closures rather than actually taking the address of
233 something. Also, unlike Zetalisp, we don't overload `car' to do our dirty
234 work."
235 (multiple-value-bind
236 (valtmps valforms newtmps setform getform)
237 (get-setf-expansion place env)
238 `(let* (,@(mapcar #'list valtmps valforms))
239 (make-loc (lambda () ,getform)
240 (lambda (,@newtmps) ,setform)))))
241
242 (declaim (inline loc (setf loc)))
243
244 (defun ref (loc)
245 "Fetch the value referred to by a locative."
246 (funcall (loc-reader loc)))
247
248 (defun (setf ref) (new loc)
249 "Store a new value in the place referred to by a locative."
250 (funcall (loc-writer loc) new))
251
252 (defmacro with-locatives (locs &body body)
253 "LOCS is a list of items of the form (SYM [LOC-EXPR]), where SYM is a
254 symbol and LOC-EXPR evaluates to a locative. If LOC-EXPR is omitted, it
255 defaults to SYM. As an abbreviation for a common case, LOCS may be a symbol
256 instead of a list. The BODY is evaluated in an environment where each SYM is
257 a symbol macro which expands to (ref LOC-EXPR) -- or, in fact, something
258 similar which doesn't break if LOC-EXPR has side-effects. Thus, references,
259 including `setf' forms, fetch or modify the thing referred to by the
260 LOC-EXPR. Useful for covering over where something uses a locative."
261 (setf locs (mapcar #'pairify (listify locs)))
262 (let ((tt (mapcar (lambda (l) (declare (ignore l)) (gensym)) locs))
263 (ll (mapcar #'cadr locs))
264 (ss (mapcar #'car locs)))
265 `(let (,@(mapcar (lambda (tmp loc) `(,tmp ,loc)) tt ll))
266 (symbol-macrolet (,@(mapcar (lambda (sym tmp)
267 `(,sym (ref ,tmp))) ss tt))
268 ,@body))))
269
270 ;;;----- That's all, folks --------------------------------------------------