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 #: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 value."
59 (format t "~&~S: ~S~%" ',x ,tmp)
62 (defun stringify (str)
63 "Return a string representation of STR. Strings are returned unchanged;
64 symbols are converted to their names (unqualified!). Other objects are
65 converted to their print representations."
68 (symbol (symbol-name str))
69 (t (with-output-to-string (s)
72 (compile-time-defun listify (x)
73 "If X is a (possibly empty) list, return X; otherwise return (list X)."
74 (if (listp x) x (list x)))
76 (compile-time-defun do-fix-pair (x y defaultp)
77 "Helper function for fix-pair and pairify."
78 (flet ((singleton (x) (values x (if defaultp y x))))
79 (cond ((atom x) (singleton x))
80 ((null (cdr x)) (singleton (car x)))
81 ((atom (cdr x)) (values (car x) (cdr x)))
82 ((cddr x) (error "Too many elements for a pair."))
83 (t (values (car x) (cadr x))))))
85 (compile-time-defun fix-pair (x &optional (y nil defaultp))
86 "Return two values extracted from X. It works as follows:
92 where Y defaults to A if not specified."
93 (do-fix-pair x y defaultp))
95 (compile-time-defun pairify (x &optional (y nil defaultp))
96 "As for fix-pair, but returns a list instead of two values."
97 (multiple-value-call #'list (do-fix-pair x y defaultp)))
99 (defun whitespace-char-p (ch)
100 "Return whether CH is a whitespace character or not."
102 ((#\space #\tab #\newline #\return #\vt #\formfeed) t)
105 (declaim (ftype (function nil ()) slot-unitialized))
106 (defun slot-uninitialized ()
107 "A function which signals an error. Can be used as an initializer form in
108 structure definitions without doom ensuing."
109 (error "No initializer for slot."))
111 (compile-time-defun parse-body (body &key (allow-docstring-p t))
112 "Given a BODY (a list of forms), parses it into three sections: a
113 docstring, a list of declarations (forms beginning with the symbol
114 `declare') and the body forms. The result is returned as three lists
115 (even the docstring), suitable for interpolation into a backquoted list
116 using `@,'. If ALLOW-DOCSTRING-P is nil, docstrings aren't allowed at
118 (let ((doc nil) (decls nil))
119 (do ((forms body (cdr forms))) (nil)
120 (let ((form (and forms (car forms))))
121 (cond ((and allow-docstring-p (not doc) (stringp form) (cdr forms))
124 (eq (car form) 'declare))
125 (setf decls (append decls (cdr form))))
126 (t (return (values (and doc (list doc))
127 (and decls (list (cons 'declare decls)))
132 (declaim (inline fixnump))
133 (defun fixnump (object)
134 "Answer non-nil if OBJECT is a fixnum, or nil if it isn't."
135 (typep object 'fixnum)))
137 ;;;--------------------------------------------------------------------------
138 ;;; Generating symbols.
140 (defmacro with-gensyms (syms &body body)
141 "Everyone's favourite macro helper."
142 `(let (,@(mapcar (lambda (sym) `(,sym (gensym ,(symbol-name sym))))
146 (defmacro let*/gensyms (binds &body body)
147 "A macro helper. BINDS is a list of binding pairs (VAR VALUE), where VALUE
148 defaults to VAR. The result is that BODY is evaluated in a context where
149 each VAR is bound to a gensym, and in the final expansion, each of those
150 gensyms will be bound to the corresponding VALUE."
151 (labels ((more (binds)
152 (let ((tmp (gensym "TMP")) (bind (car binds)))
153 `((let ((,tmp ,(cadr bind))
154 (,(car bind) (gensym ,(symbol-name (car bind)))))
155 `(let ((,,(car bind) ,,tmp))
161 (car (more (mapcar #'pairify (listify binds)))))))
163 ;;;--------------------------------------------------------------------------
164 ;;; Some simple yet useful control structures.
166 (defmacro nlet (name binds &body body)
167 "Scheme's named let."
168 (multiple-value-bind (vars vals)
169 (loop for bind in binds
170 for (var val) = (pairify bind nil)
171 collect var into vars
172 collect val into vals
173 finally (return (values vars vals)))
174 `(labels ((,name ,vars
178 (defmacro while (cond &body body)
179 "If COND is false, evaluate to nil; otherwise evaluate BODY and try again."
181 (unless ,cond (return))
184 (compile-time-defun do-case2-like (kind vform clauses)
185 "Helper function for `case2' and `ecase2'."
186 (with-gensyms (scrutinee argument)
187 `(multiple-value-bind (,scrutinee ,argument) ,vform
188 (declare (ignorable ,argument))
190 ,@(mapcar (lambda (clause)
192 (cases (&optional varx vary) &rest forms)
196 (list `(let ((,(or vary varx) ,argument)
198 `((,varx ,scrutinee))))
203 (defmacro case2 (vform &body clauses)
204 "VFORM is a form which evaluates to two values, SCRUTINEE and ARGUMENT.
205 The CLAUSES have the form (CASES ([[SCRUVAR] ARGVAR]) FORMS...), where a
206 standard `case' clause has the form (CASES FORMS...). The `case2' form
207 evaluates the VFORM, and compares the SCRUTINEE to the various CASES, in
208 order, just like `case'. If there is a match, then the corresponding
209 FORMs are evaluated with ARGVAR bound to the ARGUMENT and SCRUVAR bound to
210 the SCRUTINEE (where specified). Note the bizarre defaulting behaviour:
211 ARGVAR is less optional than SCRUVAR."
212 (do-case2-like 'case vform clauses))
214 (defmacro ecase2 (vform &body clauses)
215 "Like `case2', but signals an error if no clause matches the SCRUTINEE."
216 (do-case2-like 'ecase vform clauses))
218 ;;;--------------------------------------------------------------------------
221 (defmacro %place-ref (getform setform newtmp)
222 "Grim helper macro for with-places."
223 (declare (ignore setform newtmp))
226 (define-setf-expander %place-ref (getform setform newtmp)
227 "Grim helper macro for with-places."
228 (values nil nil newtmp setform getform))
230 (defmacro with-places ((&key environment) places &body body)
231 "A hairy helper, for writing setf-like macros. PLACES is a list of binding
232 pairs (VAR PLACE), where PLACE defaults to VAR. The result is that BODY
233 is evaluated in a context where each VAR is bound to a gensym, and in the
234 final expansion, each of those gensyms will be bound to a symbol-macro
235 capable of reading or setting the value of the corresponding PLACE."
238 (let*/gensyms (environment)
241 (let ((place (car places)))
242 (with-gensyms (tmp valtmps valforms
243 newtmps setform getform)
244 `((let ((,tmp ,(cadr place))
246 (gensym ,(symbol-name (car place)))))
249 ,newtmps ,setform ,getform)
250 (get-setf-expansion ,tmp
253 (mapcar #'list ,valtmps ,valforms)
254 `(symbol-macrolet ((,,(car place)
255 (%place-ref ,,getform
261 (car (more (mapcar #'pairify (listify places))))))))
263 ;;;--------------------------------------------------------------------------
264 ;;; Update-in-place macros built using with-places.
266 (defmacro update-place (op place arg &environment env)
267 "Update PLACE with the value of OP PLACE ARG, returning the new value."
268 (with-places (:environment env) (place)
269 `(setf ,place (,op ,place ,arg))))
271 (defmacro update-place-after (op place arg &environment env)
272 "Update PLACE with the value of OP PLACE ARG, returning the old value."
273 (with-places (:environment env) (place)
276 (setf ,place (,op ,x ,arg))
279 (defmacro incf-after (place &optional (by 1))
280 "Increment PLACE by BY, returning the old value."
281 `(update-place-after + ,place ,by))
283 (defmacro decf-after (place &optional (by 1))
284 "Decrement PLACE by BY, returning the old value."
285 `(update-place-after - ,place ,by))
287 ;;;--------------------------------------------------------------------------
290 (defstruct (loc (:predicate locp) (:constructor make-loc (reader writer)))
291 "Locative data type. See `locf' and `ref'."
292 (reader (slot-uninitialized) :type function)
293 (writer (slot-uninitialized) :type function))
295 (defmacro locf (place &environment env)
296 "Slightly cheesy locatives. (locf PLACE) returns an object which, using
297 the `ref' function, can be used to read or set the value of PLACE. It's
298 cheesy because it uses closures rather than actually taking the address of
299 something. Also, unlike Zetalisp, we don't overload `car' to do our dirty
302 (valtmps valforms newtmps setform getform)
303 (get-setf-expansion place env)
304 `(let* (,@(mapcar #'list valtmps valforms))
305 (make-loc (lambda () ,getform)
306 (lambda (,@newtmps) ,setform)))))
308 (declaim (inline loc (setf loc)))
311 "Fetch the value referred to by a locative."
312 (funcall (loc-reader loc)))
314 (defun (setf ref) (new loc)
315 "Store a new value in the place referred to by a locative."
316 (funcall (loc-writer loc) new))
318 (defmacro with-locatives (locs &body body)
319 "LOCS is a list of items of the form (SYM [LOC-EXPR]), where SYM is a
320 symbol and LOC-EXPR evaluates to a locative. If LOC-EXPR is omitted, it
321 defaults to SYM. As an abbreviation for a common case, LOCS may be a
322 symbol instead of a list. The BODY is evaluated in an environment where
323 each SYM is a symbol macro which expands to (ref LOC-EXPR) -- or, in fact,
324 something similar which doesn't break if LOC-EXPR has side-effects. Thus,
325 references, including `setf' forms, fetch or modify the thing referred to
326 by the LOC-EXPR. Useful for covering over where something uses a
328 (setf locs (mapcar #'pairify (listify locs)))
329 (let ((tt (mapcar (lambda (l) (declare (ignore l)) (gensym)) locs))
330 (ll (mapcar #'cadr locs))
331 (ss (mapcar #'car locs)))
332 `(let (,@(mapcar (lambda (tmp loc) `(,tmp ,loc)) tt ll))
333 (symbol-macrolet (,@(mapcar (lambda (sym tmp)
334 `(,sym (ref ,tmp))) ss tt))
337 ;;;----- That's all, folks --------------------------------------------------