chiark / gitweb /
0415a90fed193ee950fc8ee01ca0e8e7334f3d3b
[sod] / src / utilities.lisp
1 ;;; -*-lisp-*-
2 ;;;
3 ;;; Various handy utilities
4 ;;;
5 ;;; (c) 2009 Straylight/Edgeware
6 ;;;
7
8 ;;;----- Licensing notice ---------------------------------------------------
9 ;;;
10 ;;; This file is part of the Sensible Object Design, an object system for C.
11 ;;;
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.
16 ;;;
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.
21 ;;;
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.
25
26 (cl:defpackage #:sod-utilities
27   (:use #:common-lisp
28
29         ;; MOP from somewhere.
30         #+sbcl #:sb-mop
31         #+(or cmu clisp) #:mop
32         #+ecl #:clos))
33
34 (cl:in-package #:sod-utilities)
35
36 ;;;--------------------------------------------------------------------------
37 ;;; Macro hacks.
38
39 (export 'with-gensyms)
40 (defmacro with-gensyms ((&rest binds) &body body)
41   "Evaluate BODY with variables bound to fresh symbols.
42
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)
48                          (if (atom bind)
49                              (values bind (concatenate 'string
50                                            (symbol-name bind) "-"))
51                              (destructuring-bind
52                                  (var &optional
53                                       (name (concatenate 'string
54                                              (symbol-name var) "-")))
55                                  bind
56                                (values var name)))
57                        `(,var (gensym ,name))))
58                    binds))
59      ,@body))
60
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.
64
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'."
68
69     (cond ((and (consp form)
70                 (eq (car form) 'quote)
71                 (cdr form)
72                 (null (cddr form)))
73            (let ((body (cadr form)))
74              (if (or (not (or (consp body) (symbolp body)))
75                      (member body '(t nil))
76                      (keywordp body))
77                  body
78                  form)))
79           ((and (symbolp form) (boundp form) (null (symbol-value form)))
80            nil)
81           (t
82            form))))
83
84 (export 'once-only)
85 (defmacro once-only (binds &body body)
86   "Macro helper for preventing repeated evaluation.
87
88    The syntax is actually hairier than shown:
89
90         once-only ( [[ :environment ENV ]] { VAR | (VAR [VALUE-FORM]) }* )
91           { FORM }*
92
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.
97
98    The result of evaluating a ONCE-ONLY form is a form with the structure
99
100         (let ((#:GS1 VALUE-FORM1)
101               ...
102               (#:GSn VALUE-FORMn))
103           STUFF)
104
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.
107
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
113    stripped away."
114
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.
122
123   (with-gensyms ((envvar "ENV-") lets sym (bodyfunc "BODY-"))
124     (let ((env nil))
125
126       ;; First things first: let's pick up the keywords.
127       (loop
128         (unless (and binds (keywordp (car binds)))
129           (return))
130         (ecase (pop binds)
131           (:environment (setf env (pop binds)))))
132
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
135       ;; above.
136       (let ((canon (mapcar (lambda (bind)
137                              (multiple-value-bind (var form)
138                                  (if (atom bind)
139                                      (values bind bind)
140                                      (destructuring-bind
141                                          (var &optional (form var)) bind
142                                        (values var form)))
143                                (list var form
144                                      (gensym (format nil "T-~A-"
145                                                      (symbol-name var))))))
146                            binds)))
147
148         `(let* (,@(and env `((,envvar ,env)))
149                 (,lets nil)
150                 ,@(mapcar (lambda (bind)
151                             (destructuring-bind (var form temp) bind
152                               (declare (ignore var))
153                               `(,temp ,form)))
154                           canon)
155                 ,@(mapcar (lambda (bind)
156                             (destructuring-bind (var form temp) bind
157                               (declare (ignore form))
158                               `(,var
159                                 (cond ((constantp ,temp
160                                                   ,@(and env `(,envvar)))
161                                        (strip-quote ,temp))
162                                       ((symbolp ,temp)
163                                        ,temp)
164                                       (t
165                                        (let ((,sym (gensym
166                                                     ,(concatenate 'string
167                                                       (symbol-name var)
168                                                       "-"))))
169                                          (push (list ,sym ,temp) ,lets)
170                                          ,sym))))))
171                           canon))
172            (flet ((,bodyfunc () ,@body))
173              (if ,lets
174                  `(let (,@(nreverse ,lets)) ,(,bodyfunc))
175                  (,bodyfunc))))))))
176
177 (export 'parse-body)
178 (defun parse-body (body &key (docp t) (declp t))
179   "Parse the BODY into a docstring, declarations and the body forms.
180
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
183    `declare' form.  If DOCP is nil then a docstring is not permitted; if
184    DECLP is nil, then declarations are not permitted."
185   (let ((decls nil)
186         (doc nil))
187     (loop
188       (cond ((null body) (return))
189             ((and declp (consp (car body)) (eq (caar body) 'declare))
190              (setf decls (append decls (cdr (pop body)))))
191             ((and docp (stringp (car body)) (not doc) (cdr body))
192              (setf doc (pop body)))
193             (t (return))))
194     (values (and doc (list doc))
195             (and decls (list (cons 'declare decls)))
196             body)))
197
198 ;;;--------------------------------------------------------------------------
199 ;;; Locatives.
200
201 (export '(loc locp))
202 (defstruct (loc (:predicate locp) (:constructor make-loc (reader writer)))
203   "Locative data type.  See `locf' and `ref'."
204   (reader nil :type function)
205   (writer nil :type function))
206
207 (export 'locf)
208 (defmacro locf (place &environment env)
209   "Slightly cheesy locatives.
210
211    (locf PLACE) returns an object which, using the `ref' function, can be
212    used to read or set the value of PLACE.  It's cheesy because it uses
213    closures rather than actually taking the address of something.  Also,
214    unlike Zetalisp, we don't overload `car' to do our dirty work."
215   (multiple-value-bind
216       (valtmps valforms newtmps setform getform)
217       (get-setf-expansion place env)
218     `(let* (,@(mapcar #'list valtmps valforms))
219        (make-loc (lambda () ,getform)
220                  (lambda (,@newtmps) ,setform)))))
221
222 (export 'ref)
223 (declaim (inline ref (setf ref)))
224 (defun ref (loc)
225   "Fetch the value referred to by a locative."
226   (funcall (loc-reader loc)))
227 (defun (setf ref) (new loc)
228   "Store a new value in the place referred to by a locative."
229   (funcall (loc-writer loc) new))
230
231 (export 'with-locatives)
232 (defmacro with-locatives (locs &body body)
233   "Evaluate BODY with implicit locatives.
234
235    LOCS is a list of items of the form (SYM [LOC-EXPR]), where SYM is a
236    symbol and LOC-EXPR evaluates to a locative.  If LOC-EXPR is omitted, it
237    defaults to SYM.  As an abbreviation for a common case, LOCS may be a
238    symbol instead of a list.
239
240    The BODY is evaluated in an environment where each SYM is a symbol macro
241    which expands to (ref LOC-EXPR) -- or, in fact, something similar which
242    doesn't break if LOC-EXPR has side-effects.  Thus, references, including
243    `setf' forms, fetch or modify the thing referred to by the LOC-EXPR.
244    Useful for covering over where something uses a locative."
245   (setf locs (mapcar (lambda (item)
246                        (cond ((atom item) (list item item))
247                              ((null (cdr item)) (list (car item) (car item)))
248                              (t item)))
249                      (if (listp locs) locs (list locs))))
250   (let ((tt (mapcar (lambda (l) (declare (ignore l)) (gensym)) locs))
251         (ll (mapcar #'cadr locs))
252         (ss (mapcar #'car locs)))
253     `(let (,@(mapcar (lambda (tmp loc) `(,tmp ,loc)) tt ll))
254        (symbol-macrolet (,@(mapcar (lambda (sym tmp)
255                                      `(,sym (ref ,tmp))) ss tt))
256          ,@body))))
257
258 ;;;--------------------------------------------------------------------------
259 ;;; Anaphorics.
260
261 (export 'it)
262
263 (export 'aif)
264 (defmacro aif (cond cons &optional (alt nil altp))
265   "If COND is not nil, evaluate CONS with `it' bound to the value of COND.
266
267    Otherwise, if given, evaluate ALT; `it' isn't bound in ALT."
268   (once-only (cond)
269     `(if ,cond (let ((it ,cond)) ,cons) ,@(and altp `(,alt)))))
270
271 (export 'awhen)
272 (defmacro awhen (cond &body body)
273   "If COND, evaluate BODY as a progn with `it' bound to the value of COND."
274   `(let ((it ,cond)) (when it ,@body)))
275
276 (export 'aand)
277 (defmacro aand (&rest forms)
278   "Like `and', but anaphoric.
279
280    Each FORM except the first is evaluated with `it' bound to the value of
281    the previous one.  If there are no forms, then the result it `t'; if there
282    is exactly one, then wrapping it in `aand' is pointless."
283   (labels ((doit (first rest)
284              (if (null rest)
285                  first
286                  `(let ((it ,first))
287                     (if it ,(doit (car rest) (cdr rest)) nil)))))
288     (if (null forms)
289         't
290         (doit (car forms) (cdr forms)))))
291
292 (export 'acond)
293 (defmacro acond (&body clauses &environment env)
294   "Like COND, but with `it' bound to the value of the condition.
295
296    Each of the CLAUSES has the form (CONDITION FORM*); if a CONDITION is
297    non-nil then evaluate the FORMs with `it' bound to the non-nil value, and
298    return the value of the last FORM; if there are no FORMs, then return `it'
299    itself.  If the CONDITION is nil then continue with the next clause; if
300    all clauses evaluate to nil then the result is nil."
301   (labels ((walk (clauses)
302              (if (null clauses)
303                  `nil
304                  (once-only (:environment env (cond (caar clauses)))
305                    (if (and (constantp cond)
306                             (if (and (consp cond) (eq (car cond) 'quote))
307                                 (cadr cond) cond))
308                        (if (cdar clauses)
309                            `(let ((it ,cond))
310                               (declare (ignorable it))
311                               ,@(cdar clauses))
312                            cond)
313                        `(if ,cond
314                             ,(if (cdar clauses)
315                                  `(let ((it ,cond))
316                                     (declare (ignorable it))
317                                     ,@(cdar clauses))
318                                  cond)
319                             ,(walk (cdr clauses))))))))
320     (walk clauses)))
321
322 (export '(acase aecase atypecase aetypecase))
323 (defmacro acase (value &body clauses)
324   `(let ((it ,value)) (case it ,@clauses)))
325 (defmacro aecase (value &body clauses)
326   `(let ((it ,value)) (ecase it ,@clauses)))
327 (defmacro atypecase (value &body clauses)
328   `(let ((it ,value)) (typecase it ,@clauses)))
329 (defmacro aetypecase (value &body clauses)
330   `(let ((it ,value)) (etypecase it ,@clauses)))
331
332 (export 'asetf)
333 (defmacro asetf (&rest places-and-values &environment env)
334   "Anaphoric update of places.
335
336    The PLACES-AND-VALUES are alternating PLACEs and VALUEs.  Each VALUE is
337    evaluated with IT bound to the current value stored in the corresponding
338    PLACE."
339   `(progn ,@(loop for (place value) on places-and-values by #'cddr
340                   collect (multiple-value-bind
341                               (temps inits newtemps setform getform)
342                               (get-setf-expansion place env)
343                             `(let* (,@(mapcar #'list temps inits)
344                                     (it ,getform))
345                                (multiple-value-bind ,newtemps ,value
346                                  ,setform))))))
347
348 ;;;--------------------------------------------------------------------------
349 ;;; MOP hacks (not terribly demanding).
350
351 (export 'instance-initargs)
352 (defgeneric instance-initargs (instance)
353   (:documentation
354    "Return a plausble list of initargs for INSTANCE.
355
356    The idea is that you can make a copy of INSTANCE by invoking
357
358         (apply #'make-instance (class-of INSTANCE)
359                (instance-initargs INSTANCE))
360
361    The default implementation works by inspecting the slot definitions and
362    extracting suitable initargs, so this will only succeed if enough slots
363    actually have initargs specified that `initialize-instance' can fill in
364    the rest correctly.
365
366    The list returned is freshly consed, and you can destroy it if you like.")
367   (:method ((instance standard-object))
368     (mapcan (lambda (slot)
369               (aif (slot-definition-initargs slot)
370                    (list (car it)
371                          (slot-value instance (slot-definition-name slot)))
372                    nil))
373             (class-slots (class-of instance)))))
374
375 (export '(copy-instance copy-instance-using-class))
376 (defgeneric copy-instance-using-class (class instance &rest initargs)
377   (:documentation
378    "Metaobject protocol hook for `copy-instance'.")
379   (:method ((class standard-class) instance &rest initargs)
380     (let ((copy (allocate-instance class)))
381       (dolist (slot (class-slots class))
382         (let ((name (slot-definition-name slot)))
383           (when (slot-boundp instance name)
384             (setf (slot-value copy name) (slot-value instance name)))))
385       (apply #'shared-initialize copy nil initargs))))
386 (defun copy-instance (object &rest initargs)
387   "Construct and return a copy of OBJECT.
388
389    The new object has the same class as OBJECT, and the same slot values
390    except where overridden by INITARGS."
391   (apply #'copy-instance-using-class (class-of object) object initargs))
392
393 (export '(generic-function-methods method-specializers
394           eql-specializer eql-specializer-object))
395
396 ;;;--------------------------------------------------------------------------
397 ;;; List utilities.
398
399 (export 'make-list-builder)
400 (defun make-list-builder (&optional initial)
401   "Return a simple list builder."
402
403   ;; The `builder' is just a cons cell whose cdr will be the list that's
404   ;; wanted.  Effectively, then, we have a list that's one item longer than
405   ;; we actually want.  The car of this extra initial cons cell is always the
406   ;; last cons in the list -- which is now well defined because there's
407   ;; always at least one.
408
409   (let ((builder (cons nil initial)))
410     (setf (car builder) (last builder))
411     builder))
412
413 (export 'lbuild-add)
414 (defun lbuild-add (builder item)
415   "Add an ITEM to the end of a list BUILDER."
416   (let ((new (cons item nil)))
417     (setf (cdar builder) new
418           (car builder) new))
419   builder)
420
421 (export 'lbuild-add-list)
422 (defun lbuild-add-list (builder list)
423   "Add a LIST to the end of a list BUILDER.  The LIST will be clobbered."
424   (when list
425     (setf (cdar builder) list
426           (car builder) (last list)))
427   builder)
428
429 (export 'lbuild-list)
430 (defun lbuild-list (builder)
431   "Return the constructed list."
432   (cdr builder))
433
434 (export 'mappend)
435 (defun mappend (function list &rest more-lists)
436   "Like a nondestructive `mapcan'.
437
438    Map FUNCTION over the the corresponding elements of LIST and MORE-LISTS,
439    and return the result of appending all of the resulting lists."
440   (reduce #'append (apply #'mapcar function list more-lists) :from-end t))
441
442 (export 'distinguished-point-shortest-paths)
443 (defun distinguished-point-shortest-paths (root neighbours-func)
444   "Moderately efficient shortest-paths-from-root computation.
445
446    The ROOT is a distinguished vertex in a graph.  The NEIGHBOURS-FUNC
447    accepts a VERTEX as its only argument, and returns a list of conses (V .
448    C) for each of the VERTEX's neighbours, indicating that there is an edge
449    from VERTEX to V, with cost C.
450
451    The return value is a list of entries (COST . REV-PATH) for each vertex
452    reachable from the ROOT; the COST is the total cost of the shortest path,
453    and REV-PATH is the path from the ROOT, in reverse order -- so the first
454    element is the vertex itself and the last element is the ROOT.
455
456    The NEIGHBOURS-FUNC is called at most N times, and may take O(N) time to
457    produce its output list.  The computation as a whole takes O(N^2) time,
458    where N is the number of vertices in the graph, assuming there is at most
459    one edge between any pair of vertices."
460
461   ;; This is a listish version of Dijkstra's shortest-path algorithm.  It
462   ;; could be made more efficient by using a fancy priority queue rather than
463   ;; a linear search for finding the nearest live element (see below), but it
464   ;; still runs pretty well.
465
466   (let ((map (make-hash-table))
467         (dead nil)
468         (live (list (list 0 root))))
469     (setf (gethash root map) (cons :live (car live)))
470     (loop
471       ;; The dead list contains a record, in output format (COST . PATH), for
472       ;; each vertex whose shortest path has been finally decided.  The live
473       ;; list contains a record for the vertices of current interest, also in
474       ;; output format; the COST for a live record shows the best cost for a
475       ;; path using only dead vertices.
476       ;;
477       ;; Each time through here, we pull an item off the live list and
478       ;; push it onto the dead list, so we do at most N iterations total.
479
480       ;; If there are no more live items, then we're done; the remaining
481       ;; vertices, if any, are unreachable from the ROOT.
482       (when (null live) (return))
483
484       ;; Find the closest live vertex to the root.  The linear scan through
485       ;; the live list costs at most N time.
486       (let* ((best (reduce (lambda (x y) (if (< (car x) (car y)) x y)) live))
487              (best-cost (car best))
488              (best-path (cdr best))
489              (best-vertex (car best-path)))
490
491         ;; Remove the chosen vertex from the LIVE list, and add the
492         ;; appropriate record to the dead list.  We must have the shortest
493         ;; path to this vertex now: we have the shortest path using currently
494         ;; dead vertices; any other path must use at least one live vertex,
495         ;; and, by construction, the path through any such vertex must be
496         ;; further than the path we already have.
497         ;;
498         ;; Removal from the live list uses a linear scan which costs N time.
499         (setf live (delete best live))
500         (push best dead)
501         (setf (car (gethash best-vertex map)) :dead)
502
503         ;; Work through the chosen vertex's neighbours, adding each of them
504         ;; to the live list if they're not already there.  If a neighbour is
505         ;; already live, and we find a shorter path to it through our chosen
506         ;; vertex, then update the neighbour's record.
507         ;;
508         ;; The chosen vertex obviously has at most N neighbours.  There's no
509         ;; more looping in here, so performance is as claimed.
510         (dolist (neigh (funcall neighbours-func best-vertex))
511           (let* ((neigh-vertex (car neigh))
512                  (neigh-cost (+ best-cost (cdr neigh)))
513                  (neigh-record (gethash neigh-vertex map)))
514             (cond ((null neigh-record)
515                    ;; If the neighbour isn't known, then now's the time to
516                    ;; make a fresh live record for it.
517                    (let ((new-record (list* :live neigh-cost
518                                             neigh-vertex best-path)))
519                      (push (cdr new-record) live)
520                      (setf (gethash neigh-vertex map) new-record)))
521                   ((and (eq (car neigh-record) :live)
522                         (< neigh-cost (cadr neigh-record)))
523                    ;; If the neighbour is live, and we've found a better path
524                    ;; to it, then update its record.
525                    (setf (cadr neigh-record) neigh-cost
526                          (cdddr neigh-record) best-path)))))))
527     dead))
528
529 (export '(inconsistent-merge-error merge-error-candidates))
530 (define-condition inconsistent-merge-error (error)
531   ((candidates :initarg :candidates
532                :reader merge-error-candidates))
533   (:documentation
534    "Reports an inconsistency in the arguments passed to `merge-lists'.")
535   (:report (lambda (condition stream)
536              (format stream "Merge inconsistency: failed to decide between ~
537                              ~{~#[~;~A~;~A and ~A~:;~
538                                   ~@{~A, ~#[~;and ~A~]~}~]~}"
539                      (merge-error-candidates condition)))))
540
541 (export 'merge-lists)
542 (defun merge-lists (lists &key pick (test #'eql) (present #'identity))
543   "Return a merge of the given LISTS.
544
545    The resulting list contains the items of the given LISTS, with duplicates
546    removed.  The order of the resulting list is consistent with the orders of
547    the input LISTS in the sense that if A precedes B in some input list then
548    A will also precede B in the output list.  If the lists aren't consistent
549    (e.g., some list contains A followed by B, and another contains B followed
550    by A) then an error of type `inconsistent-merge-error' is signalled.  The
551    offending items are filtered for presentation through the PRESENT function
552    before being attached to the condition, so as to produce a more useful
553    diagnostic message.
554
555    Item equality is determined by TEST.
556
557    If there is an ambiguity at any point -- i.e., a choice between two or
558    more possible next items to emit -- then PICK is called to arbitrate.
559    PICK is called with two arguments: the list of candidate next items, and
560    the current output list.  It should return one of the candidate items.
561    The order of the candidates in the list given to the PICK function
562    reflects their order in the input LISTS: item A will precede item B in the
563    candidates list if and only if an occurrence of A appears in an earlier
564    input list than any occurrence of item B.  (This completely determines the
565    order of the candidates: it is not possible that two candidates appear in
566    the same input list would resolve the ambiguity between them.)  If PICK is
567    omitted then the item chosen is the one appearing in the earliest of the
568    input lists: i.e., effectively, the default PICK function is
569
570         (lambda (candidates output-so-far)
571           (declare (ignore output-so-far))
572           (car candidates))
573
574    The primary use of this function is in computing class precedence lists.
575    By building the input lists and selecting the PICK function appropriately,
576    a variety of different CPL algorithms can be implemented."
577
578   (do ((lb (make-list-builder)))
579       ((null lists) (lbuild-list lb))
580
581     ;; The candidate items are the ones at the front of the input lists.
582     ;; Gather them up, removing duplicates.  If a candidate is somewhere in
583     ;; one of the other lists other than at the front then we reject it.  If
584     ;; we've just rejected everything, then we can make no more progress and
585     ;; the input lists were inconsistent.
586     (let* ((candidates (delete-duplicates (mapcar #'car lists)
587                                           :test test :from-end t))
588            (leasts (remove-if (lambda (item)
589                                 (some (lambda (list)
590                                         (member item (cdr list) :test test))
591                                       lists))
592                               candidates))
593            (winner (cond ((null leasts)
594                           (error 'inconsistent-merge-error
595                                  :candidates (mapcar present candidates)))
596                          ((null (cdr leasts))
597                           (car leasts))
598                          (pick
599                           (funcall pick leasts (lbuild-list lb)))
600                          (t (car leasts)))))
601
602       ;; Check that the PICK function isn't conning us.
603       (assert (member winner leasts :test test))
604
605       ;; Update the output list and remove the winning item from the input
606       ;; lists.  We know that it must be at the front of each input list
607       ;; containing it.  At this point, we discard input lists entirely when
608       ;; they run out of entries.  The loop ends when there are no more input
609       ;; lists left, i.e., when we've munched all of the input items.
610       (lbuild-add lb winner)
611       (setf lists (delete nil (mapcar (lambda (list)
612                                         (if (funcall test winner (car list))
613                                             (cdr list)
614                                             list))
615                                       lists))))))
616
617 (export 'categorize)
618 (defmacro categorize ((itemvar items &key bind) categories &body body)
619   "Categorize ITEMS into lists and invoke BODY.
620
621    The ITEMVAR is a symbol; as the macro iterates over the ITEMS, ITEMVAR
622    will contain the current item.  The BIND argument is a list of LET*-like
623    clauses.  The CATEGORIES are a list of clauses of the form (SYMBOL
624    PREDICATE).
625
626    The behaviour of the macro is as follows.  ITEMVAR is assigned (not
627    bound), in turn, each item in the list ITEMS.  The PREDICATEs in the
628    CATEGORIES list are evaluated in turn, in an environment containing
629    ITEMVAR and the BINDings, until one of them evaluates to a non-nil value.
630    At this point, the item is assigned to the category named by the
631    corresponding SYMBOL.  If none of the PREDICATEs returns non-nil then an
632    error is signalled; a PREDICATE consisting only of T will (of course)
633    match anything; it is detected specially so as to avoid compiler warnings.
634
635    Once all of the ITEMS have been categorized in this fashion, the BODY is
636    evaluated as an implicit PROGN.  For each SYMBOL naming a category, a
637    variable named after that symbol will be bound in the BODY's environment
638    to a list of the items in that category, in the same order in which they
639    were found in the list ITEMS.  The final values of the macro are the final
640    values of the BODY."
641
642   (let* ((cat-names (mapcar #'car categories))
643          (cat-match-forms (mapcar #'cadr categories))
644          (cat-vars (mapcar (lambda (name) (gensym (concatenate 'string
645                                                    (symbol-name name) "-")))
646                            cat-names))
647          (items-var (gensym "ITEMS-")))
648     `(let ((,items-var ,items)
649            ,@(mapcar (lambda (cat-var) (list cat-var nil)) cat-vars))
650        (dolist (,itemvar ,items-var)
651          (let* ,bind
652            (cond ,@(mapcar (lambda (cat-match-form cat-var)
653                              `(,cat-match-form
654                                (push ,itemvar ,cat-var)))
655                            cat-match-forms cat-vars)
656                  ,@(and (not (member t cat-match-forms))
657                         `((t (error "Failed to categorize ~A" ,itemvar)))))))
658        (let ,(mapcar (lambda (name var)
659                        `(,name (nreverse ,var)))
660                      cat-names cat-vars)
661          ,@body))))
662
663 (export 'partial-order-minima)
664 (defun partial-order-minima (items order)
665   "Return a list of minimal items according to the non-strict partial ORDER.
666
667    The ORDER function describes the partial order: (funcall ORDER X Y) should
668    return true if X precedes or is equal to Y in the order."
669   (reduce (lambda (tops this)
670             (let ((new nil) (keep t))
671               (dolist (top tops)
672                 (cond ((funcall order top this)
673                        (setf keep nil)
674                        (push top new))
675                       ((not (funcall order this top))
676                        (push top new))))
677               (nreverse (if keep (cons this new) new))))
678           items
679           :initial-value nil))
680
681 ;;;--------------------------------------------------------------------------
682 ;;; Strings and characters.
683
684 (export 'frob-identifier)
685 (defun frob-identifier (string &key (swap-case t) (swap-hyphen t))
686   "Twiddles the case of STRING.
687
688    If all the letters in STRING are uppercase, and SWAP-CASE is true, then
689    switch them to lowercase; if they're all lowercase then switch them to
690    uppercase.  If there's a mix then leave them all alone.  At the same time,
691    if there are underscores but no hyphens, and SWAP-HYPHEN is true, then
692    switch them to hyphens, if there are hyphens and no underscores, switch
693    them underscores, and if there are both then leave them alone.
694
695    This is an invertible transformation, which turns vaguely plausible Lisp
696    names into vaguely plausible C names and vice versa.  Lisp names with
697    `funny characters' like stars and percent signs won't be any use, of
698    course."
699
700   ;; Work out what kind of a job we've got to do.  Gather flags: bit 0 means
701   ;; there are upper-case letters; bit 1 means there are lower-case letters;
702   ;; bit 2 means there are hyphens; bit 3 means there are underscores.
703   ;;
704   ;; Consequently, (logxor flags (ash flags 1)) is interesting: bit 1 is set
705   ;; if we have to frob case; bit 3 is set if we have to swap hyphens and
706   ;; underscores.  So use this to select functions which do bits of the
707   ;; mapping, and then compose them together.
708   (let* ((flags (reduce (lambda (state ch)
709                           (logior state
710                                   (cond ((upper-case-p ch) 1)
711                                         ((lower-case-p ch) 2)
712                                         ((char= ch #\-) 4)
713                                         ((char= ch #\_) 8)
714                                         (t 0))))
715                         string
716                         :initial-value 0))
717          (mask (logxor flags (ash flags 1)))
718          (letter (cond ((or (not swap-case) (not (logbitp 1 mask)))
719                         (constantly nil))
720                        ((logbitp 0 flags)
721                         (lambda (ch)
722                           (and (alpha-char-p ch) (char-downcase ch))))
723                        (t
724                         (lambda (ch)
725                           (and (alpha-char-p ch) (char-upcase ch))))))
726          (uscore-hyphen (cond ((or (not (logbitp 3 mask)) (not swap-hyphen))
727                                (constantly nil))
728                               ((logbitp 2 flags)
729                                (lambda (ch) (and (char= ch #\-) #\_)))
730                               (t
731                                (lambda (ch) (and (char= ch #\_) #\-))))))
732
733     (if (logbitp 3 (logior mask (ash mask 2)))
734         (map 'string (lambda (ch)
735                        (or (funcall letter ch)
736                            (funcall uscore-hyphen ch)
737                            ch))
738              string)
739         string)))
740
741 (export 'whitespace-char-p)
742 (declaim (inline whitespace-char-p))
743 (defun whitespace-char-p (char)
744   "Returns whether CHAR is a whitespace character.
745
746    Whitespaceness is determined relative to the compile-time readtable, which
747    is probably good enough for most purposes."
748   (case char
749     (#.(loop for i below char-code-limit
750              for ch = (code-char i)
751              unless (with-input-from-string (in (string ch))
752                       (peek-char t in nil))
753              collect ch) t)
754     (t nil)))
755
756 (export 'update-position)
757 (declaim (inline update-position))
758 (defun update-position (char line column)
759   "Updates LINE and COLUMN appropriately for having read the character CHAR.
760
761    Returns the new LINE and COLUMN numbers."
762   (case char
763     ((#\newline #\vt #\page)
764      (values (1+ line) 0))
765     ((#\tab)
766      (values line (logandc2 (+ column 8) 7)))
767     (t
768      (values line (1+ column)))))
769
770 (export 'backtrack-position)
771 (declaim (inline backtrack-position))
772 (defun backtrack-position (char line column)
773   "Updates LINE and COLUMN appropriately for having unread CHAR.
774
775    Well, actually an approximation for it; it will likely be wrong if the
776    last character was a tab.  But when the character is read again, it will
777    be correct."
778
779   ;; This isn't perfect: if the character doesn't actually match what was
780   ;; really read then it might not actually be possible: for example, if we
781   ;; push back a newline while in the middle of a line, or a tab while not at
782   ;; a tab stop.  In that case, we'll just lose, but hopefully not too badly.
783   (case char
784
785     ;; In the absence of better ideas, I'll set the column number to zero.
786     ;; This is almost certainly wrong, but with a little luck nobody will ask
787     ;; and it'll be all right soon.
788     ((#\newline #\vt #\page) (values (1- line) 0))
789
790     ;; Winding back a single space is sufficient.  If the position is
791     ;; currently on a tab stop then it'll advance back here next time.  If
792     ;; not, we're going to lose anyway because the previous character
793     ;; certainly couldn't have been a tab.
794     (#\tab (values line (1- column)))
795
796     ;; Anything else: just decrement the column and cross fingers.
797     (t (values line (1- column)))))
798
799 ;;;--------------------------------------------------------------------------
800 ;;; Functions.
801
802 (export 'compose)
803 (defun compose (function &rest more-functions)
804   "Composition of functions.  Functions are applied left-to-right.
805
806    This is the reverse order of the usual mathematical notation, but I find
807    it easier to read.  It's also slightly easier to work with in programs.
808    That is, (compose F1 F2 ... Fn) is what a category theorist might write as
809    F1 ; F2 ; ... ; Fn, rather than F1 o F2 o ... o Fn."
810
811   (labels ((compose1 (func-a func-b)
812              (lambda (&rest args)
813                (multiple-value-call func-b (apply func-a args)))))
814     (reduce #'compose1 more-functions :initial-value function)))
815
816 ;;;--------------------------------------------------------------------------
817 ;;; Variables.
818
819 (export 'defvar-unbound)
820 (defmacro defvar-unbound (var doc)
821   "Make VAR a special variable with documentation DOC, but leave it unbound."
822   `(eval-when (:compile-toplevel :load-toplevel :execute)
823      (defvar ,var)
824      (setf (documentation ',var 'variable) ',doc)
825      ',var))
826
827 ;;;--------------------------------------------------------------------------
828 ;;; Symbols.
829
830 (export 'symbolicate)
831 (defun symbolicate (&rest symbols)
832   "Return a symbol named after the concatenation of the names of the SYMBOLS.
833
834    The symbol is interned in the current `*package*'.  Trad."
835   (intern (apply #'concatenate 'string (mapcar #'symbol-name symbols))))
836
837 ;;;--------------------------------------------------------------------------
838 ;;; Object printing.
839
840 (export 'maybe-print-unreadable-object)
841 (defmacro maybe-print-unreadable-object
842     ((object stream &rest args) &body body)
843   "Print helper for usually-unreadable objects.
844
845    If `*print-escape*' is set then print OBJECT unreadably using BODY.
846    Otherwise just print using BODY."
847   (with-gensyms (print)
848     `(flet ((,print () ,@body))
849        (if *print-escape*
850            (print-unreadable-object (,object ,stream ,@args)
851              (,print))
852            (,print)))))
853
854 (export 'print-ugly-stuff)
855 (defun print-ugly-stuff (stream func)
856   "Print not-pretty things to the stream underlying STREAM.
857
858    The Lisp pretty-printing machinery, notably `pprint-logical-block', may
859    interpose additional streams between its body and the original target
860    stream.  This makes it difficult to make use of the underlying stream's
861    special features, whatever they might be."
862
863   ;; This is unpleasant.  Hacky hacky.
864   #.(or #+sbcl '(if (typep stream 'sb-pretty:pretty-stream)
865                   (let ((target (sb-pretty::pretty-stream-target stream)))
866                     (pprint-newline :mandatory stream)
867                     (funcall func target))
868                   (funcall func stream))
869         #+cmu '(if (typep stream 'pp:pretty-stream)
870                   (let ((target (pp::pretty-stream-target stream)))
871                     (pprint-newline :mandatory stream)
872                     (funcall func target))
873                   (funcall func stream))
874         '(funcall func stream)))
875
876 ;;;--------------------------------------------------------------------------
877 ;;; Iteration macros.
878
879 (export 'dosequence)
880 (defmacro dosequence ((var seq &key (start 0) (end nil) indexvar)
881                       &body body
882                       &environment env)
883   "Macro for iterating over general sequences.
884
885    Iterates over a (sub)sequence SEQ, delimited by START and END (which are
886    evaluated).  For each item of SEQ, BODY is invoked with VAR bound to the
887    item, and INDEXVAR (if requested) bound to the item's index.  (Note that
888    this is different from most iteration constructs in Common Lisp, which
889    work by mutating the variable.)
890
891    The loop is surrounded by an anonymous BLOCK and the loop body forms an
892    implicit TAGBODY, as is usual.  There is no result-form, however."
893
894   (once-only (:environment env seq start end)
895     (with-gensyms ((ivar "INDEX-") (endvar "END-") (bodyfunc "BODY-"))
896       (multiple-value-bind (docs decls body) (parse-body body :docp nil)
897         (declare (ignore docs))
898
899         (flet ((loopguts (indexp listp endvar)
900                  ;; Build a DO-loop to do what we want.
901                  (let* ((do-vars nil)
902                         (end-condition (if endvar
903                                            `(>= ,ivar ,endvar)
904                                            `(endp ,seq)))
905                         (item (if listp
906                                   `(car ,seq)
907                                   `(aref ,seq ,ivar)))
908                         (body-call `(,bodyfunc ,item)))
909                    (when listp
910                      (push `(,seq (nthcdr ,start ,seq) (cdr ,seq))
911                            do-vars))
912                    (when indexp
913                      (push `(,ivar ,start (1+ ,ivar)) do-vars))
914                    (when indexvar
915                      (setf body-call (append body-call (list ivar))))
916                    `(do ,do-vars (,end-condition) ,body-call))))
917
918           `(block nil
919              (flet ((,bodyfunc (,var ,@(and indexvar `(,indexvar)))
920                       ,@decls
921                       (tagbody ,@body)))
922                (etypecase ,seq
923                  (vector
924                   (let ((,endvar (or ,end (length ,seq))))
925                     ,(loopguts t nil endvar)))
926                  (list
927                   (if ,end
928                       ,(loopguts t t end)
929                       ,(loopguts indexvar t nil)))))))))))
930
931 ;;;--------------------------------------------------------------------------
932 ;;; Structure accessor hacks.
933
934 (export 'define-access-wrapper)
935 (defmacro define-access-wrapper (from to &key read-only)
936   "Make (FROM THING) work like (TO THING).
937
938    If not READ-ONLY, then also make (setf (FROM THING) VALUE) work like
939    (setf (TO THING) VALUE).
940
941    This is mostly useful for structure slot accessors where the slot has to
942    be given an unpleasant name to avoid it being an external symbol."
943   `(progn
944      (declaim (inline ,from ,@(and (not read-only) `((setf ,from)))))
945      (defun ,from (object)
946        (,to object))
947      ,@(and (not read-only)
948             `((defun (setf ,from) (value object)
949                 (setf (,to object) value))))))
950
951 ;;;--------------------------------------------------------------------------
952 ;;; Condition and error utilities.
953
954 (export 'designated-condition)
955 (defun designated-condition (default-type datum arguments
956                              &key allow-pointless-arguments)
957   "Return the condition designated by DATUM and ARGUMENTS.
958
959    DATUM and ARGUMENTS together are a `condition designator' of (some
960    supertype of) DEFAULT-TYPE; return the condition so designated."
961   (typecase datum
962     (condition
963      (unless (or allow-pointless-arguments (null arguments))
964        (error "Argument list provided with specific condition"))
965      datum)
966     (symbol
967      (apply #'make-condition datum arguments))
968     ((or string function)
969      (make-condition default-type
970                      :format-control datum
971                      :format-arguments arguments))
972     (t
973      (error "Unexpected condition designator datum ~S" datum))))
974
975 ;;;--------------------------------------------------------------------------
976 ;;; CLOS hacking.
977
978 (export 'default-slot)
979 (defmacro default-slot ((instance slot &optional (slot-names t))
980                           &body value
981                           &environment env)
982   "If INSTANCE's slot named SLOT is unbound, set it to VALUE.
983
984    Only set SLOT if it's listed in SLOT-NAMES, or SLOT-NAMES is `t' (i.e., we
985    obey the `shared-initialize' protocol).  SLOT-NAMES defaults to `t', so
986    you can use it in `initialize-instance' or similar without ill effects.
987    Both INSTANCE and SLOT are evaluated; VALUE is an implicit progn and only
988    evaluated if it's needed."
989
990   (once-only (:environment env instance slot slot-names)
991     `(when ,(if (eq slot-names t)
992                   `(not (slot-boundp ,instance ,slot))
993                   `(and (not (slot-boundp ,instance ,slot))
994                         (or (eq ,slot-names t)
995                             (member ,slot ,slot-names))))
996        (setf (slot-value ,instance ,slot)
997              (progn ,@value)))))
998
999 (export 'define-on-demand-slot)
1000 (defmacro define-on-demand-slot (class slot (instance) &body body)
1001   "Defines a slot which computes its initial value on demand.
1002
1003    Sets up the named SLOT of CLASS to establish its value as the implicit
1004    progn BODY, by defining an appropriate method on `slot-unbound'."
1005   (multiple-value-bind (docs decls body) (parse-body body)
1006     (with-gensyms (classvar slotvar)
1007       `(defmethod slot-unbound
1008            (,classvar (,instance ,class) (,slotvar (eql ',slot)))
1009          ,@docs ,@decls
1010          (declare (ignore ,classvar))
1011          (setf (slot-value ,instance ',slot) (block ,slot ,@body))))))
1012
1013 ;;;----- That's all, folks --------------------------------------------------