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