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 #+cmu (:import-from #:extensions #:fixnump))
33 (in-package #:mdw.base)
35 ;;;--------------------------------------------------------------------------
38 (export 'unsigned-fixnum)
39 (deftype unsigned-fixnum ()
40 "Unsigned fixnums; useful as array indices and suchlike."
41 `(mod ,most-positive-fixnum))
43 ;;;--------------------------------------------------------------------------
44 ;;; Some simple macros to get things going.
46 (export 'compile-time-defun)
47 (defmacro compile-time-defun (name args &body body)
48 "Define a function which can be used by macros during the compilation
50 `(eval-when (:compile-toplevel :load-toplevel :execute)
51 (defun ,name ,args ,@body)))
55 "Debugging tool: print the expression X and its values."
57 `(let ((,tmp (multiple-value-list ,x)))
59 (pprint-logical-block (*standard-output* nil :per-line-prefix ";; ")
61 "~S = ~@_~:I~:[#<no values>~;~:*~{~S~^ ~_~}~]"
68 (defun stringify (str)
69 "Return a string representation of STR. Strings are returned unchanged;
70 symbols are converted to their names (unqualified!). Other objects are
71 converted to their print representations."
74 (symbol (symbol-name str))
75 (t (princ-to-string str))))
78 (defun functionify (func)
79 "Convert the function-designator FUNC to a function."
80 (declare (type (or function symbol) func))
83 (symbol (symbol-function func))))
86 (defun mappend (function list &rest more-lists)
87 "Apply FUNCTION to corresponding elements of LIST and MORE-LISTS, yielding
88 a list. Return the concatenation of all the resulting lists. Like
89 mapcan, but nondestructive."
90 (apply #'append (apply #'mapcar function list more-lists)))
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)))
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))))))
107 (compile-time-defun fix-pair (x &optional (y nil defaultp))
108 "Return two values extracted from X. It works as follows:
114 where Y defaults to A if not specified."
115 (do-fix-pair x y defaultp))
118 (compile-time-defun pairify (x &optional (y nil defaultp))
119 "As for fix-pair, but returns a list instead of two values."
120 (multiple-value-call #'list (do-fix-pair x y defaultp)))
122 (export 'whitespace-char-p)
123 (defun whitespace-char-p (ch)
124 "Return whether CH is a whitespace character or not."
126 (#.(loop for i below char-code-limit
127 for ch = (code-char i)
128 unless (with-input-from-string (in (string ch))
129 (peek-char t in nil))
134 (export 'defconstant*)
135 (defmacro defconstant* (name value &key doc test)
136 "Define a constant, like `defconstant'. The TEST is an equality test used
137 to decide whether to override the current definition, if any."
138 (let ((temp (gensym)))
139 `(eval-when (:compile-toplevel :load-toplevel :execute)
140 (let ((,temp ,value))
141 (unless (and (boundp ',name)
142 (funcall ,(or test ''eql) (symbol-value ',name) ,temp))
143 (defconstant ,name ,value ,@(and doc (list doc))))
146 (export 'slot-uninitialized)
147 (declaim (ftype (function nil ()) slot-unitialized))
148 (defun slot-uninitialized ()
149 "A function which signals an error. Can be used as an initializer form in
150 structure definitions without doom ensuing."
151 (error "No initializer for slot."))
154 (compile-time-defun parse-body (body &key (allow-docstring-p t))
155 "Given a BODY (a list of forms), parses it into three sections: a
156 docstring, a list of declarations (forms beginning with the symbol
157 `declare') and the body forms. The result is returned as three lists
158 (even the docstring), suitable for interpolation into a backquoted list
159 using `@,'. If ALLOW-DOCSTRING-P is nil, docstrings aren't allowed at
161 (let ((doc nil) (decls nil))
162 (do ((forms body (cdr forms))) (nil)
163 (let ((form (and forms (car forms))))
164 (cond ((and allow-docstring-p (not doc) (stringp form) (cdr forms))
167 (eq (car form) 'declare))
168 (setf decls (append decls (cdr form))))
169 (t (return (values (and doc (list doc))
170 (and decls (list (cons 'declare decls)))
173 (export 'with-parsed-body)
174 (defmacro with-parsed-body
175 ((bodyvar declvar &optional (docvar (gensym) docp)) form &body body)
176 "Parse FORM into a body, declarations and (maybe) a docstring; bind BODYVAR
177 to the body, DECLVAR to the declarations, and DOCVAR to (a list
178 containing) the docstring, and evaluate BODY."
179 `(multiple-value-bind
180 (,docvar ,declvar ,bodyvar)
181 (parse-body ,form :allow-docstring-p ,docp)
182 ,@(if docp nil `((declare (ignore ,docvar))))
188 (declaim (inline fixnump))
189 (defun fixnump (object)
190 "Answer non-nil if OBJECT is a fixnum, or nil if it isn't."
191 (typep object 'fixnum)))
193 ;;;--------------------------------------------------------------------------
194 ;;; Generating symbols.
196 (export 'with-gensyms)
197 (defmacro with-gensyms (syms &body body)
198 "Everyone's favourite macro helper."
199 `(let (,@(mapcar (lambda (sym) `(,sym (gensym ,(symbol-name sym))))
203 (export 'let*/gensyms)
204 (defmacro let*/gensyms (binds &body body)
205 "A macro helper. BINDS is a list of binding pairs (VAR VALUE), where VALUE
206 defaults to VAR. The result is that BODY is evaluated in a context where
207 each VAR is bound to a gensym, and in the final expansion, each of those
208 gensyms will be bound to the corresponding VALUE."
209 (labels ((more (binds)
210 (let ((tmp (gensym "TMP")) (bind (car binds)))
211 `((let ((,tmp ,(cadr bind))
212 (,(car bind) (gensym ,(symbol-name (car bind)))))
213 `(let ((,,(car bind) ,,tmp))
219 (car (more (mapcar #'pairify (listify binds)))))))
221 ;;;--------------------------------------------------------------------------
222 ;;; Some simple yet useful control structures.
225 (defmacro nlet (name binds &body body)
226 "Scheme's named let."
227 (multiple-value-bind (vars vals)
228 (loop for bind in binds
229 for (var val) = (pairify bind nil)
230 collect var into vars
231 collect val into vals
232 finally (return (values vars vals)))
233 `(labels ((,name ,vars
238 (defmacro while (cond &body body)
239 "If COND is false, evaluate to nil; otherwise evaluate BODY and try again."
240 `(loop (unless ,cond (return)) (progn ,@body)))
243 (defmacro until (cond &body body)
244 "If COND is true, evaluate to nil; otherwise evaluate BODY and try again."
245 `(loop (when ,cond (return)) (progn ,@body)))
247 (compile-time-defun do-case2-like (kind vform clauses)
248 "Helper function for `case2' and `ecase2'."
249 (with-gensyms (scrutinee argument)
250 `(multiple-value-bind (,scrutinee ,argument) ,vform
251 (declare (ignorable ,argument))
253 ,@(mapcar (lambda (clause)
255 (cases (&optional varx vary) &rest forms)
259 (list `(let ((,(or vary varx) ,argument)
261 `((,varx ,scrutinee))))
267 (defmacro case2 (vform &body clauses)
268 "VFORM is a form which evaluates to two values, SCRUTINEE and ARGUMENT.
269 The CLAUSES have the form (CASES ([[SCRUVAR] ARGVAR]) FORMS...), where a
270 standard `case' clause has the form (CASES FORMS...). The `case2' form
271 evaluates the VFORM, and compares the SCRUTINEE to the various CASES, in
272 order, just like `case'. If there is a match, then the corresponding
273 FORMs are evaluated with ARGVAR bound to the ARGUMENT and SCRUVAR bound to
274 the SCRUTINEE (where specified). Note the bizarre defaulting behaviour:
275 ARGVAR is less optional than SCRUVAR."
276 (do-case2-like 'case vform clauses))
279 (defmacro ecase2 (vform &body clauses)
280 "Like `case2', but signals an error if no clause matches the SCRUTINEE."
281 (do-case2-like 'ecase vform clauses))
283 (export 'setf-default)
284 (defmacro setf-default (&rest specs &environment env)
285 "Like setf, but only sets places which are currently nil.
287 The arguments are an alternating list of PLACEs and DEFAULTs. If a PLACE
288 is nil, the DEFAULT is evaluated and stored in the PLACE; otherwise the
289 default is /not/ stored. The result is the (new) value of the last
291 (labels ((doit (specs)
292 (cond ((null specs) nil)
294 (error "Odd number of arguments for SETF-DEFAULT."))
296 (let ((place (car specs))
297 (default (cadr specs))
300 (vars vals store-vals writer reader)
301 (get-setf-expansion place env)
302 `(let* ,(mapcar #'list vars vals)
304 (multiple-value-bind ,store-vals ,default
306 ,@(and rest (list (doit rest))))))))))
309 ;;;--------------------------------------------------------------------------
310 ;;; Capturing places as symbols.
312 (defmacro %place-ref (getform setform newtmp)
313 "Grim helper macro for with-places."
314 (declare (ignore setform newtmp))
317 (define-setf-expander %place-ref (getform setform newtmp)
318 "Grim helper macro for with-places."
319 (values nil nil newtmp setform getform))
321 (export 'with-places)
322 (defmacro with-places (clauses &body body &environment env)
323 "Define symbols which refer to `setf'-able places.
325 The syntax is similar to `let'. The CLAUSES are a list of (NAME PLACE)
326 pairs. Each NAME is defined as a symbol-macro referring to the
327 corresponding PLACE: a mention of the NAME within the BODY forms extracts
328 the current value(s) of the PLACE, while a `setf' (or `setq', because
329 symbol macros are strange like that) of a NAME updates the value(s) in the
330 PLACE. The returned values are those of the BODY, evaluated as an
333 (let ((temp-binds nil)
335 (dolist (clause clauses)
336 (destructuring-bind (name place) clause
337 (multiple-value-bind (valtmps valforms newtmps setform getform)
338 (get-setf-expansion place env)
340 (nconc (nreverse (mapcar #'list valtmps valforms))
342 (push `(,name (%place-ref ,getform ,setform ,newtmps))
344 `(let (,@(nreverse temp-binds))
345 (symbol-macrolet (,@(nreverse macro-binds))
348 (export 'with-places/gensyms)
349 (defmacro with-places/gensyms (clauses &body body)
350 "A kind of a cross between `with-places' and `let*/gensyms'.
352 This is a hairy helper for writing `setf'-like macros. The CLAUSES are a
353 list of (NAME [PLACE]) pairs, where the PLACE defaults to NAME, and a
354 bare NAME may be written in place of the singleton list (NAME). The
355 PLACEs are evaluated.
357 The BODY forms are evaluated as an implicit `progn', with each NAME bound
358 to a gensym, to produce a Lisp form, called the `kernel'. The result of
359 the `with-places/gensyms' macro is then itself a Lisp form, called the
362 The effect of evaluating the `result' form is to evaluate the `kernel'
363 form with each of the gensyms stands for the value(s) stored in the
364 corresponding PLACE; a `setf' (or `setq') of one of the gensyms updates
365 the value(s) in the corresponding PLACE. The values returned by the
366 `result' form are the values returned by the `kernel'."
368 (let* ((clauses (mapcar #'pairify clauses))
369 (names (mapcar #'car clauses))
370 (places (mapcar #'cadr clauses))
371 (gensyms (mapcar (lambda (name) (gensym (symbol-name name)))
373 ``(with-places (,,@(mapcar (lambda (gensym place)
374 ``(,',gensym ,,place))
376 ,(let (,@(mapcar (lambda (name gensym)
381 ;;;--------------------------------------------------------------------------
382 ;;; Update-in-place macros built using with-places.
384 (export 'update-place)
385 (defmacro update-place (op place &rest args)
386 "Update PLACE with (OP PLACE . ARGS), returning the new value."
387 (with-places/gensyms (place)
388 `(setf ,place (,op ,place ,@args))))
390 (export 'update-place-after)
391 (defmacro update-place-after (op place &rest args)
392 "Update PLACE with (OP PLACE . ARGS), returning the old value."
393 (with-places/gensyms (place)
396 (setf ,place (,op ,x ,@args))
400 (defmacro incf-after (place &optional (by 1))
401 "Increment PLACE by BY, returning the old value."
402 `(update-place-after + ,place ,by))
405 (defmacro decf-after (place &optional (by 1))
406 "Decrement PLACE by BY, returning the old value."
407 `(update-place-after - ,place ,by))
409 ;;;--------------------------------------------------------------------------
413 (defstruct (loc (:predicate locp) (:constructor make-loc (reader writer)))
414 "Locative data type. See `locf' and `ref'."
415 (reader (slot-uninitialized) :type function :read-only t)
416 (writer (slot-uninitialized) :type function :read-only t))
419 (defmacro locf (place &environment env)
420 "Slightly cheesy locatives. (locf PLACE) returns an object which, using
421 the `ref' function, can be used to read or set the value of PLACE. It's
422 cheesy because it uses closures rather than actually taking the address of
423 something. Also, unlike Zetalisp, we don't overload `car' to do our dirty
426 (valtmps valforms newtmps setform getform)
427 (get-setf-expansion place env)
428 `(let* (,@(mapcar #'list valtmps valforms))
429 (make-loc (lambda () ,getform)
430 (lambda (,@newtmps) ,setform)))))
433 (declaim (inline ref (setf ref)))
435 "Fetch the value referred to by a locative."
436 (funcall (loc-reader loc)))
437 (defun (setf ref) (new loc)
438 "Store a new value in the place referred to by a locative."
439 (funcall (loc-writer loc) new))
441 (export 'with-locatives)
442 (defmacro with-locatives (locs &body body)
443 "LOCS is a list of items of the form (SYM [LOC-EXPR]), where SYM is a
444 symbol and LOC-EXPR evaluates to a locative. If LOC-EXPR is omitted, it
445 defaults to SYM. As an abbreviation for a common case, LOCS may be a
446 symbol instead of a list. The BODY is evaluated in an environment where
447 each SYM is a symbol macro which expands to (ref LOC-EXPR) -- or, in fact,
448 something similar which doesn't break if LOC-EXPR has side-effects. Thus,
449 references, including `setf' forms, fetch or modify the thing referred to
450 by the LOC-EXPR. Useful for covering over where something uses a
452 (setf locs (mapcar #'pairify (listify locs)))
453 (let ((tt (mapcar (lambda (l) (declare (ignore l)) (gensym)) locs))
454 (ll (mapcar #'cadr locs))
455 (ss (mapcar #'car locs)))
456 `(let (,@(mapcar (lambda (tmp loc) `(,tmp ,loc)) tt ll))
457 (symbol-macrolet (,@(mapcar (lambda (sym tmp)
458 `(,sym (ref ,tmp))) ss tt))
461 ;;;----- That's all, folks --------------------------------------------------