3 ;;; Various handy utilities
5 ;;; (c) 2009 Straylight/Edgeware
8 ;;;----- Licensing notice ---------------------------------------------------
10 ;;; This file is part of the Sensble Object Design, an object system for C.
12 ;;; SOD 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 ;;; SOD 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 SOD; if not, write to the Free Software Foundation,
24 ;;; Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
26 (cl:defpackage #:sod-utilities
29 ;; MOP from somewhere.
31 #+(or cmu clisp) #:mop
34 (cl:in-package #:sod-utilities)
36 ;;;--------------------------------------------------------------------------
39 (export 'with-gensyms)
40 (defmacro with-gensyms ((&rest binds) &body body)
41 "Evaluate BODY with variables bound to fresh symbols.
43 The BINDS are a list of entries (VAR [NAME]), and a singleton list can be
44 replaced by just a symbol; each VAR is bound to a fresh symbol generated
45 by (gensym NAME), where NAME defaults to the symbol-name of VAR."
46 `(let (,@(mapcar (lambda (bind)
47 (multiple-value-bind (var name)
49 (values bind (concatenate 'string
50 (symbol-name bind) "-"))
53 (name (concatenate 'string
54 (symbol-name var) "-")))
57 `(,var (gensym ,name))))
61 (eval-when (:compile-toplevel :load-toplevel :execute)
62 (defun strip-quote (form)
63 "If FORM looks like (quote FOO) for self-evaluating FOO, return FOO.
65 If FORM is a symbol whose constant value is `nil' then return `nil'.
66 Otherwise return FORM unchanged. This makes it easier to inspect constant
67 things. This is a utility for `once-only'."
69 (cond ((and (consp form)
70 (eq (car form) 'quote)
73 (let ((body (cadr form)))
74 (if (or (not (or (consp body) (symbolp body)))
75 (member body '(t nil))
79 ((and (symbolp form) (boundp form) (null (symbol-value form)))
85 (defmacro once-only (binds &body body)
86 "Macro helper for preventing repeated evaluation.
88 The syntax is actually hairier than shown:
90 once-only ( [[ :environment ENV ]] { VAR | (VAR [VALUE-FORM]) }* )
93 So, the BINDS are a list of entries (VAR [VALUE-FORM]); a singleton list
94 can be replaced by just a symbol VAR, and the VALUE-FORM defaults to VAR.
95 But before them you can have keyword arguments. Only one is defined so
96 far. See below for the crazy things that does.
98 The result of evaluating a ONCE-ONLY form is a form with the structure
100 (let ((#:GS1 VALUE-FORM1)
105 where STUFF is the value of the BODY forms, as an implicit progn, in an
106 environment with the VARs bound to the corresponding gensyms.
108 As additional magic, if any of the VALUE-FORMs is actually constant (as
109 determined by inspection, and aided by `constantp' if an :environment is
110 supplied, then no gensym is constructed for it, and the VAR is bound
111 directly to the constant form. Moreover, if the constant form looks like
112 (quote FOO) for a self-evaluating FOO then the outer layer of quoting is
115 ;; We need an extra layer of gensyms in our expansion: we'll want the
116 ;; expansion to examine the various VALUE-FORMs to find out whether they're
117 ;; constant without evaluating them repeatedly. This also helps with
118 ;; another problem: we explicitly encourage the rebinding of a VAR
119 ;; (probably a macro argument) to a gensym which will be bound to the value
120 ;; of the form previously held in VAR itself -- so the gensym and value
121 ;; form must exist at the same time and we need two distinct variables.
123 (with-gensyms ((envvar "ENV-") lets sym (bodyfunc "BODY-"))
126 ;; First things first: let's pick up the keywords.
128 (unless (and binds (keywordp (car binds)))
131 (:environment (setf env (pop binds)))))
133 ;; Now we'll investigate the bindings. Turn each one into a list (VAR
134 ;; VALUE-FORM TEMP) where TEMP is an appropriate gensym -- see the note
136 (let ((canon (mapcar (lambda (bind)
137 (multiple-value-bind (var form)
141 (var &optional (form var)) bind
144 (gensym (format nil "T-~A-"
145 (symbol-name var))))))
148 `(let* (,@(and env `((,envvar ,env)))
150 ,@(mapcar (lambda (bind)
151 (destructuring-bind (var form temp) bind
152 (declare (ignore var))
155 ,@(mapcar (lambda (bind)
156 (destructuring-bind (var form temp) bind
157 (declare (ignore form))
159 (cond ((constantp ,temp
160 ,@(and env `(,envvar)))
166 ,(concatenate 'string
169 (push (list ,sym ,temp) ,lets)
172 (flet ((,bodyfunc () ,@body))
174 `(let (,@(nreverse ,lets)) ,(,bodyfunc))
178 (defun parse-body (body)
179 "Parse the BODY into a docstring, declarations and the body forms.
181 These are returned as three lists, so that they can be spliced into a
182 macro expansion easily. The declarations are consolidated into a single
187 (cond ((null body) (return))
188 ((and (consp (car body)) (eq (caar body) 'declare))
189 (setf decls (append decls (cdr (pop body)))))
190 ((and (stringp (car body)) (not doc) (cdr body))
191 (setf doc (pop body)))
193 (values (and doc (list doc))
194 (and decls (list (cons 'declare decls)))
197 ;;;--------------------------------------------------------------------------
203 (defmacro aif (cond cons &optional (alt nil altp))
204 "If COND is not nil, evaluate CONS with `it' bound to the value of COND.
206 Otherwise, if given, evaluate ALT; `it' isn't bound in ALT."
208 `(if ,cond (let ((it ,cond)) ,cons) ,@(and altp `(,alt)))))
211 (defmacro awhen (cond &body body)
212 "If COND, evaluate BODY as a progn with `it' bound to the value of COND."
213 `(let ((it ,cond)) (when it ,@body)))
216 (defmacro acond (&rest clauses &environment env)
217 "Like COND, but with `it' bound to the value of the condition.
219 Each of the CLAUSES has the form (CONDITION FORM*); if a CONDITION is
220 non-nil then evaluate the FORMs with `it' bound to the non-nil value, and
221 return the value of the last FORM; if there are no FORMs, then return `it'
222 itself. If the CONDITION is nil then continue with the next clause; if
223 all clauses evaluate to nil then the result is nil."
224 (labels ((walk (clauses)
227 (once-only (:environment env (cond (caar clauses)))
228 (if (and (constantp cond)
229 (if (and (consp cond) (eq (car cond) 'quote))
233 (declare (ignorable it))
239 (declare (ignorable it))
242 ,(walk (cdr clauses))))))))
245 (export '(acase aecase atypecase aetypecase))
246 (defmacro acase (value &body clauses)
247 `(let ((it ,value)) (case it ,@clauses)))
248 (defmacro aecase (value &body clauses)
249 `(let ((it ,value)) (ecase it ,@clauses)))
250 (defmacro atypecase (value &body clauses)
251 `(let ((it ,value)) (typecase it ,@clauses)))
252 (defmacro aetypecase (value &body clauses)
253 `(let ((it ,value)) (etypecase it ,@clauses)))
256 (defmacro asetf (&rest places-and-values &environment env)
257 "Anaphoric update of places.
259 The PLACES-AND-VALUES are alternating PLACEs and VALUEs. Each VALUE is
260 evaluated with IT bound to the current value stored in the corresponding
262 `(progn ,@(loop for (place value) on places-and-values by #'cddr
263 collect (multiple-value-bind
264 (temps inits newtemps setform getform)
265 (get-setf-expansion place env)
266 `(let* (,@(mapcar #'list temps inits)
268 (multiple-value-bind ,newtemps ,value
271 ;;;--------------------------------------------------------------------------
272 ;;; MOP hacks (not terribly demanding).
274 (export '(copy-instance copy-instance-using-class))
275 (defgeneric copy-instance-using-class (class instance &rest initargs)
277 "Metaobject protocol hook for `copy-instance'.")
278 (:method ((class standard-class) instance &rest initargs)
279 (let ((copy (allocate-instance class)))
280 (dolist (slot (class-slots class))
281 (let ((name (slot-definition-name slot)))
282 (when (slot-boundp instance name)
283 (setf (slot-value copy name) (slot-value instance name)))))
284 (apply #'shared-initialize copy nil initargs))))
285 (defun copy-instance (object &rest initargs)
286 "Construct and return a copy of OBJECT.
288 The new object has the same class as OBJECT, and the same slot values
289 except where overridden by INITARGS."
290 (apply #'copy-instance-using-class (class-of object) object initargs))
292 ;;;--------------------------------------------------------------------------
295 (export 'make-list-builder)
296 (defun make-list-builder (&optional initial)
297 "Return a simple list builder."
299 ;; The `builder' is just a cons cell whose cdr will be the list that's
300 ;; wanted. Effectively, then, we have a list that's one item longer than
301 ;; we actually want. The car of this extra initial cons cell is always the
302 ;; last cons in the list -- which is now well defined because there's
303 ;; always at least one.
305 (let ((builder (cons nil initial)))
306 (setf (car builder) (last builder))
310 (defun lbuild-add (builder item)
311 "Add an ITEM to the end of a list BUILDER."
312 (let ((new (cons item nil)))
313 (setf (cdar builder) new
317 (export 'lbuild-add-list)
318 (defun lbuild-add-list (builder list)
319 "Add a LIST to the end of a list BUILDER. The LIST will be clobbered."
321 (setf (cdar builder) list
322 (car builder) (last list)))
325 (export 'lbuild-list)
326 (defun lbuild-list (builder)
327 "Return the constructed list."
331 (defun mappend (function list &rest more-lists)
332 "Like a nondestructive MAPCAN.
334 Map FUNCTION over the the corresponding elements of LIST and MORE-LISTS,
335 and return the result of appending all of the resulting lists."
336 (reduce #'append (apply #'mapcar function list more-lists) :from-end t))
338 (export '(inconsistent-merge-error merge-error-candidates))
339 (define-condition inconsistent-merge-error (error)
340 ((candidates :initarg :candidates
341 :reader merge-error-candidates))
343 "Reports an inconsistency in the arguments passed to MERGE-LISTS.")
344 (:report (lambda (condition stream)
345 (format stream "Merge inconsistency: failed to decide among ~A."
346 (merge-error-candidates condition)))))
348 (export 'merge-lists)
349 (defun merge-lists (lists &key pick (test #'eql))
350 "Return a merge of the given LISTS.
352 The resulting LIST contains the items of the given lists, with duplicates
353 removed. The order of the resulting list is consistent with the orders of
354 the input LISTS in the sense that if A precedes B in some input list then
355 A will also precede B in the output list. If the lists aren't consistent
356 (e.g., some list contains A followed by B, and another contains B followed
357 by A) then an error of type INCONSISTENT-MERGE-ERROR is signalled.
359 Item equality is determined by TEST.
361 If there is an ambiguity at any point -- i.e., a choice between two or
362 more possible next items to emit -- then PICK is called to arbitrate.
363 PICK is called with two arguments: the list of candidate next items, and
364 the current output list. It should return one of the candidate items. If
365 PICK is omitted then an arbitrary choice is made.
367 The primary use of this function is in computing class precedence lists.
368 By building the input lists and selecting the PICK function appropriately,
369 a variety of different CPL algorithms can be implemented."
371 (do* ((lb (make-list-builder)))
372 ((null lists) (lbuild-list lb))
374 ;; The candidate items are the ones at the front of the input lists.
375 ;; Gather them up, removing duplicates. If a candidate is somewhere in
376 ;; one of the other lists other than at the front then we reject it. If
377 ;; we've just rejected everything, then we can make no more progress and
378 ;; the input lists were inconsistent.
379 (let* ((candidates (delete-duplicates (mapcar #'car lists) :test test))
380 (leasts (remove-if (lambda (item)
382 (member item (cdr list) :test test))
385 (winner (cond ((null leasts)
386 (error 'inconsistent-merge-error
387 :candidates candidates))
391 (funcall pick leasts (lbuild-list lb)))
394 ;; Check that the PICK function isn't conning us.
395 (assert (member winner leasts :test test))
397 ;; Update the output list and remove the winning item from the input
398 ;; lists. We know that it must be at the front of each input list
399 ;; containing it. At this point, we discard input lists entirely when
400 ;; they run out of entries. The loop ends when there are no more input
401 ;; lists left, i.e., when we've munched all of the input items.
402 (lbuild-add lb winner)
403 (setf lists (delete nil (mapcar (lambda (list)
404 (if (funcall test winner (car list))
410 (defmacro categorize ((itemvar items &key bind) categories &body body)
411 "Categorize ITEMS into lists and invoke BODY.
413 The ITEMVAR is a symbol; as the macro iterates over the ITEMS, ITEMVAR
414 will contain the current item. The BIND argument is a list of LET*-like
415 clauses. The CATEGORIES are a list of clauses of the form (SYMBOL
418 The behaviour of the macro is as follows. ITEMVAR is assigned (not
419 bound), in turn, each item in the list ITEMS. The PREDICATEs in the
420 CATEGORIES list are evaluated in turn, in an environment containing
421 ITEMVAR and the BINDings, until one of them evaluates to a non-nil value.
422 At this point, the item is assigned to the category named by the
423 corresponding SYMBOL. If none of the PREDICATEs returns non-nil then an
424 error is signalled; a PREDICATE consisting only of T will (of course)
425 match anything; it is detected specially so as to avoid compiler warnings.
427 Once all of the ITEMS have been categorized in this fashion, the BODY is
428 evaluated as an implicit PROGN. For each SYMBOL naming a category, a
429 variable named after that symbol will be bound in the BODY's environment
430 to a list of the items in that category, in the same order in which they
431 were found in the list ITEMS. The final values of the macro are the final
434 (let* ((cat-names (mapcar #'car categories))
435 (cat-match-forms (mapcar #'cadr categories))
436 (cat-vars (mapcar (lambda (name) (gensym (concatenate 'string
437 (symbol-name name) "-")))
439 (items-var (gensym "ITEMS-")))
440 `(let ((,items-var ,items)
441 ,@(mapcar (lambda (cat-var) (list cat-var nil)) cat-vars))
442 (dolist (,itemvar ,items-var)
444 (cond ,@(mapcar (lambda (cat-match-form cat-var)
446 (push ,itemvar ,cat-var)))
447 cat-match-forms cat-vars)
448 ,@(and (not (member t cat-match-forms))
449 `((t (error "Failed to categorize ~A" ,itemvar)))))))
450 (let ,(mapcar (lambda (name var)
451 `(,name (nreverse ,var)))
455 ;;;--------------------------------------------------------------------------
456 ;;; Strings and characters.
458 (export 'frob-identifier)
459 (defun frob-identifier (string &key (swap-case t) (swap-hyphen t))
460 "Twiddles the case of STRING.
462 If all the letters in STRING are uppercase, and SWAP-CASE is true, then
463 switch them to lowercase; if they're all lowercase then switch them to
464 uppercase. If there's a mix then leave them all alone. At the same time,
465 if there are underscores but no hyphens, and SWAP-HYPHEN is true, then
466 switch them to hyphens, if there are hyphens and no underscores, switch
467 them underscores, and if there are both then leave them alone.
469 This is an invertible transformation, which turns vaguely plausible Lisp
470 names into vaguely plausible C names and vice versa. Lisp names with
471 `funny characters' like stars and percent signs won't be any use, of
474 ;; Work out what kind of a job we've got to do. Gather flags: bit 0 means
475 ;; there are upper-case letters; bit 1 means there are lower-case letters;
476 ;; bit 2 means there are hyphens; bit 3 means there are underscores.
478 ;; Consequently, (logxor flags (ash flags 1)) is interesting: bit 1 is set
479 ;; if we have to frob case; bit 3 is set if we have to swap hyphens and
480 ;; underscores. So use this to select functions which do bits of the
481 ;; mapping, and then compose them together.
482 (let* ((flags (reduce (lambda (state ch)
484 (cond ((upper-case-p ch) 1)
485 ((lower-case-p ch) 2)
491 (mask (logxor flags (ash flags 1)))
492 (letter (cond ((or (not swap-case) (not (logbitp 1 mask)))
496 (and (alpha-char-p ch) (char-downcase ch))))
499 (and (alpha-char-p ch) (char-upcase ch))))))
500 (uscore-hyphen (cond ((or (not (logbitp 3 mask)) (not swap-hyphen))
503 (lambda (ch) (and (char= ch #\-) #\_)))
505 (lambda (ch) (and (char= ch #\_) #\-))))))
507 (if (logbitp 3 (logior mask (ash mask 2)))
508 (map 'string (lambda (ch)
509 (or (funcall letter ch)
510 (funcall uscore-hyphen ch)
515 (export 'whitespace-char-p)
516 (declaim (inline whitespace-char-p))
517 (defun whitespace-char-p (char)
518 "Returns whether CHAR is a whitespace character.
520 Whitespaceness is determined relative to the compile-time readtable, which
521 is probably good enough for most purposes."
523 (#.(loop for i below char-code-limit
524 for ch = (code-char i)
525 unless (with-input-from-string (in (string ch))
526 (peek-char t in nil))
530 (export 'update-position)
531 (declaim (inline update-position))
532 (defun update-position (char line column)
533 "Updates LINE and COLUMN appropriately for having read the character CHAR.
535 Returns the new LINE and COLUMN numbers."
537 ((#\newline #\vt #\page)
538 (values (1+ line) 0))
540 (values line (logandc2 (+ column 8) 7)))
542 (values line (1+ column)))))
544 (export 'backtrack-position)
545 (declaim (inline backtrack-position))
546 (defun backtrack-position (char line column)
547 "Updates LINE and COLUMN appropriately for having unread CHAR.
549 Well, actually an approximation for it; it will likely be wrong if the
550 last character was a tab. But when the character is read again, it will
553 ;; This isn't perfect: if the character doesn't actually match what was
554 ;; really read then it might not actually be possible: for example, if we
555 ;; push back a newline while in the middle of a line, or a tab while not at
556 ;; a tab stop. In that case, we'll just lose, but hopefully not too badly.
559 ;; In the absence of better ideas, I'll set the column number to zero.
560 ;; This is almost certainly wrong, but with a little luck nobody will ask
561 ;; and it'll be all right soon.
562 ((#\newline #\vt #\page) (values (1- line) 0))
564 ;; Winding back a single space is sufficient. If the position is
565 ;; currently on a tab stop then it'll advance back here next time. If
566 ;; not, we're going to lose anyway because the previous character
567 ;; certainly couldn't have been a tab.
568 (#\tab (values line (1- column)))
570 ;; Anything else: just decrement the column and cross fingers.
571 (t (values line (1- column)))))
573 ;;;--------------------------------------------------------------------------
577 (defun compose (function &rest more-functions)
578 "Composition of functions. Functions are applied left-to-right.
580 This is the reverse order of the usual mathematical notation, but I find
581 it easier to read. It's also slightly easier to work with in programs."
582 (labels ((compose1 (func-a func-b)
584 (multiple-value-call func-b (apply func-a args)))))
585 (reduce #'compose1 more-functions :initial-value function)))
587 ;;;--------------------------------------------------------------------------
590 (export 'symbolicate)
591 (defun symbolicate (&rest symbols)
592 "Return a symbol named after the concatenation of the names of the SYMBOLS.
594 The symbol is interned in the current *PACKAGE*. Trad."
595 (intern (apply #'concatenate 'string (mapcar #'symbol-name symbols))))
597 ;;;--------------------------------------------------------------------------
600 (export 'maybe-print-unreadable-object)
601 (defmacro maybe-print-unreadable-object
602 ((object stream &rest args) &body body)
603 "Print helper for usually-unreadable objects.
605 If *PRINT-ESCAPE* is set then print OBJECT unreadably using BODY.
606 Otherwise just print using BODY."
607 (with-gensyms (print)
608 `(flet ((,print () ,@body))
610 (print-unreadable-object (,object ,stream ,@args)
614 ;;;--------------------------------------------------------------------------
615 ;;; Iteration macros.
618 (defmacro dosequence ((var seq &key (start 0) (end nil) indexvar)
621 "Macro for iterating over general sequences.
623 Iterates over a (sub)sequence SEQ, delimited by START and END (which are
624 evaluated). For each item of SEQ, BODY is invoked with VAR bound to the
625 item, and INDEXVAR (if requested) bound to the item's index. (Note that
626 this is different from most iteration constructs in Common Lisp, which
627 work by mutating the variable.)
629 The loop is surrounded by an anonymous BLOCK and the loop body forms an
630 implicit TAGBODY, as is usual. There is no result-form, however."
632 (once-only (:environment env seq start end)
633 (with-gensyms ((ivar "INDEX-") (endvar "END-") (bodyfunc "BODY-"))
635 (flet ((loopguts (indexp listp endvar)
636 ;; Build a DO-loop to do what we want.
638 (end-condition (if endvar
644 (body-call `(,bodyfunc ,item)))
646 (push `(,seq (nthcdr ,start ,seq) (cdr ,seq))
649 (push `(,ivar ,start (1+ ,ivar)) do-vars))
651 (setf body-call (append body-call (list ivar))))
652 `(do ,do-vars (,end-condition) ,body-call))))
655 (flet ((,bodyfunc (,var ,@(and indexvar `(,indexvar)))
659 (let ((,endvar (or ,end (length ,seq))))
660 ,(loopguts t nil endvar)))
664 ,(loopguts indexvar t nil))))))))))
666 ;;;--------------------------------------------------------------------------
669 (export 'default-slot)
670 (defmacro default-slot ((instance slot &optional (slot-names t))
673 "If INSTANCE's slot named SLOT is unbound, set it to VALUE.
675 Only set SLOT if it's listed in SLOT-NAMES, or SLOT-NAMES is `t' (i.e., we
676 obey the `shared-initialize' protocol). SLOT-NAMES defaults to `t', so
677 you can use it in `initialize-instance' or similar without ill effects.
678 Both INSTANCE and SLOT are evaluated; VALUE is an implicit progn and only
679 evaluated if it's needed."
681 (once-only (:environment env instance slot slot-names)
682 `(when ,(if (eq slot-names t)
683 `(not (slot-boundp ,instance ,slot))
684 `(and (not (slot-boundp ,instance ,slot))
685 (or (eq ,slot-names t)
686 (member ,slot ,slot-names))))
687 (setf (slot-value ,instance ,slot)
690 ;;;----- That's all, folks --------------------------------------------------