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