Commit | Line | Data |
---|---|---|
dea4d055 MW |
1 | ;;; -*-lisp-*- |
2 | ;;; | |
3 | ;;; Various handy utilities | |
4 | ;;; | |
5 | ;;; (c) 2009 Straylight/Edgeware | |
6 | ;;; | |
7 | ||
8 | ;;;----- Licensing notice --------------------------------------------------- | |
9 | ;;; | |
e0808c47 | 10 | ;;; This file is part of the Sensible Object Design, an object system for C. |
dea4d055 MW |
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) | |
b8c698ee | 178 | (defun parse-body (body &key (docp t) (declp t)) |
dea4d055 MW |
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 | |
b8c698ee MW |
183 | `declare' form. If DOCP is nil then a docstring is not permitted; if |
184 | DECLP is nil, then declarations are not permitted." | |
dea4d055 MW |
185 | (let ((decls nil) |
186 | (doc nil)) | |
187 | (loop | |
188 | (cond ((null body) (return)) | |
b8c698ee | 189 | ((and declp (consp (car body)) (eq (caar body) 'declare)) |
dea4d055 | 190 | (setf decls (append decls (cdr (pop body))))) |
b8c698ee | 191 | ((and docp (stringp (car body)) (not doc) (cdr body)) |
dea4d055 MW |
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 | ;;;-------------------------------------------------------------------------- | |
e8abb286 MW |
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 | ;;;-------------------------------------------------------------------------- | |
dea4d055 MW |
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 | ||
3e166443 MW |
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 | ||
dea4d055 | 292 | (export 'acond) |
bf090e02 | 293 | (defmacro acond (&body clauses &environment env) |
dea4d055 MW |
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 | ||
bf090e02 MW |
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 | ||
dea4d055 MW |
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 | ||
9ec578d9 MW |
393 | (export '(generic-function-methods method-specializers |
394 | eql-specializer eql-specializer-object)) | |
395 | ||
dea4d055 MW |
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) | |
69dda0c9 | 436 | "Like a nondestructive `mapcan'. |
dea4d055 MW |
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 '(inconsistent-merge-error merge-error-candidates)) | |
443 | (define-condition inconsistent-merge-error (error) | |
444 | ((candidates :initarg :candidates | |
445 | :reader merge-error-candidates)) | |
446 | (:documentation | |
9fb4a980 | 447 | "Reports an inconsistency in the arguments passed to `merge-lists'.") |
dea4d055 | 448 | (:report (lambda (condition stream) |
e2838dc5 MW |
449 | (format stream "Merge inconsistency: failed to decide between ~ |
450 | ~{~#[~;~A~;~A and ~A~:;~ | |
451 | ~@{~A, ~#[~;and ~A~]~}~]~}" | |
dea4d055 MW |
452 | (merge-error-candidates condition))))) |
453 | ||
454 | (export 'merge-lists) | |
e2838dc5 | 455 | (defun merge-lists (lists &key pick (test #'eql) (present #'identity)) |
dea4d055 MW |
456 | "Return a merge of the given LISTS. |
457 | ||
e8c5a09e | 458 | The resulting list contains the items of the given LISTS, with duplicates |
dea4d055 MW |
459 | removed. The order of the resulting list is consistent with the orders of |
460 | the input LISTS in the sense that if A precedes B in some input list then | |
461 | A will also precede B in the output list. If the lists aren't consistent | |
462 | (e.g., some list contains A followed by B, and another contains B followed | |
e2838dc5 MW |
463 | by A) then an error of type `inconsistent-merge-error' is signalled. The |
464 | offending items are filtered for presentation through the PRESENT function | |
465 | before being attached to the condition, so as to produce a more useful | |
466 | diagnostic message. | |
dea4d055 MW |
467 | |
468 | Item equality is determined by TEST. | |
469 | ||
470 | If there is an ambiguity at any point -- i.e., a choice between two or | |
471 | more possible next items to emit -- then PICK is called to arbitrate. | |
472 | PICK is called with two arguments: the list of candidate next items, and | |
e8c5a09e MW |
473 | the current output list. It should return one of the candidate items. |
474 | The order of the candidates in the list given to the PICK function | |
475 | reflects their order in the input LISTS: item A will precede item B in the | |
476 | candidates list if and only if an occurrence of A appears in an earlier | |
477 | input list than any occurrence of item B. (This completely determines the | |
478 | order of the candidates: it is not possible that two candidates appear in | |
479 | the same input list would resolve the ambiguity between them.) If PICK is | |
480 | omitted then the item chosen is the one appearing in the earliest of the | |
481 | input lists: i.e., effectively, the default PICK function is | |
482 | ||
483 | (lambda (candidates output-so-far) | |
484 | (declare (ignore output-so-far)) | |
485 | (car candidates)) | |
dea4d055 MW |
486 | |
487 | The primary use of this function is in computing class precedence lists. | |
488 | By building the input lists and selecting the PICK function appropriately, | |
489 | a variety of different CPL algorithms can be implemented." | |
490 | ||
022a3499 MW |
491 | (do ((lb (make-list-builder))) |
492 | ((null lists) (lbuild-list lb)) | |
dea4d055 MW |
493 | |
494 | ;; The candidate items are the ones at the front of the input lists. | |
495 | ;; Gather them up, removing duplicates. If a candidate is somewhere in | |
496 | ;; one of the other lists other than at the front then we reject it. If | |
497 | ;; we've just rejected everything, then we can make no more progress and | |
498 | ;; the input lists were inconsistent. | |
e8c5a09e MW |
499 | (let* ((candidates (delete-duplicates (mapcar #'car lists) |
500 | :test test :from-end t)) | |
dea4d055 MW |
501 | (leasts (remove-if (lambda (item) |
502 | (some (lambda (list) | |
503 | (member item (cdr list) :test test)) | |
504 | lists)) | |
505 | candidates)) | |
506 | (winner (cond ((null leasts) | |
507 | (error 'inconsistent-merge-error | |
e2838dc5 | 508 | :candidates (mapcar present candidates))) |
dea4d055 MW |
509 | ((null (cdr leasts)) |
510 | (car leasts)) | |
511 | (pick | |
512 | (funcall pick leasts (lbuild-list lb))) | |
513 | (t (car leasts))))) | |
514 | ||
515 | ;; Check that the PICK function isn't conning us. | |
516 | (assert (member winner leasts :test test)) | |
517 | ||
518 | ;; Update the output list and remove the winning item from the input | |
519 | ;; lists. We know that it must be at the front of each input list | |
520 | ;; containing it. At this point, we discard input lists entirely when | |
521 | ;; they run out of entries. The loop ends when there are no more input | |
522 | ;; lists left, i.e., when we've munched all of the input items. | |
523 | (lbuild-add lb winner) | |
524 | (setf lists (delete nil (mapcar (lambda (list) | |
525 | (if (funcall test winner (car list)) | |
526 | (cdr list) | |
527 | list)) | |
528 | lists)))))) | |
529 | ||
530 | (export 'categorize) | |
531 | (defmacro categorize ((itemvar items &key bind) categories &body body) | |
532 | "Categorize ITEMS into lists and invoke BODY. | |
533 | ||
534 | The ITEMVAR is a symbol; as the macro iterates over the ITEMS, ITEMVAR | |
535 | will contain the current item. The BIND argument is a list of LET*-like | |
536 | clauses. The CATEGORIES are a list of clauses of the form (SYMBOL | |
537 | PREDICATE). | |
538 | ||
539 | The behaviour of the macro is as follows. ITEMVAR is assigned (not | |
540 | bound), in turn, each item in the list ITEMS. The PREDICATEs in the | |
541 | CATEGORIES list are evaluated in turn, in an environment containing | |
542 | ITEMVAR and the BINDings, until one of them evaluates to a non-nil value. | |
543 | At this point, the item is assigned to the category named by the | |
544 | corresponding SYMBOL. If none of the PREDICATEs returns non-nil then an | |
545 | error is signalled; a PREDICATE consisting only of T will (of course) | |
546 | match anything; it is detected specially so as to avoid compiler warnings. | |
547 | ||
548 | Once all of the ITEMS have been categorized in this fashion, the BODY is | |
549 | evaluated as an implicit PROGN. For each SYMBOL naming a category, a | |
550 | variable named after that symbol will be bound in the BODY's environment | |
551 | to a list of the items in that category, in the same order in which they | |
552 | were found in the list ITEMS. The final values of the macro are the final | |
553 | values of the BODY." | |
554 | ||
555 | (let* ((cat-names (mapcar #'car categories)) | |
556 | (cat-match-forms (mapcar #'cadr categories)) | |
557 | (cat-vars (mapcar (lambda (name) (gensym (concatenate 'string | |
558 | (symbol-name name) "-"))) | |
559 | cat-names)) | |
560 | (items-var (gensym "ITEMS-"))) | |
561 | `(let ((,items-var ,items) | |
562 | ,@(mapcar (lambda (cat-var) (list cat-var nil)) cat-vars)) | |
563 | (dolist (,itemvar ,items-var) | |
564 | (let* ,bind | |
565 | (cond ,@(mapcar (lambda (cat-match-form cat-var) | |
566 | `(,cat-match-form | |
567 | (push ,itemvar ,cat-var))) | |
568 | cat-match-forms cat-vars) | |
569 | ,@(and (not (member t cat-match-forms)) | |
570 | `((t (error "Failed to categorize ~A" ,itemvar))))))) | |
571 | (let ,(mapcar (lambda (name var) | |
572 | `(,name (nreverse ,var))) | |
573 | cat-names cat-vars) | |
574 | ,@body)))) | |
575 | ||
42291726 MW |
576 | (export 'partial-order-minima) |
577 | (defun partial-order-minima (items order) | |
578 | "Return a list of minimal items according to the non-strict partial ORDER. | |
579 | ||
580 | The ORDER function describes the partial order: (funcall ORDER X Y) should | |
581 | return true if X precedes or is equal to Y in the order." | |
582 | (reduce (lambda (tops this) | |
583 | (let ((new nil) (keep t)) | |
584 | (dolist (top tops) | |
585 | (cond ((funcall order top this) | |
586 | (setf keep nil) | |
587 | (push top new)) | |
588 | ((not (funcall order this top)) | |
589 | (push top new)))) | |
590 | (nreverse (if keep (cons this new) new)))) | |
591 | items | |
592 | :initial-value nil)) | |
593 | ||
dea4d055 MW |
594 | ;;;-------------------------------------------------------------------------- |
595 | ;;; Strings and characters. | |
596 | ||
597 | (export 'frob-identifier) | |
598 | (defun frob-identifier (string &key (swap-case t) (swap-hyphen t)) | |
599 | "Twiddles the case of STRING. | |
600 | ||
601 | If all the letters in STRING are uppercase, and SWAP-CASE is true, then | |
602 | switch them to lowercase; if they're all lowercase then switch them to | |
603 | uppercase. If there's a mix then leave them all alone. At the same time, | |
604 | if there are underscores but no hyphens, and SWAP-HYPHEN is true, then | |
605 | switch them to hyphens, if there are hyphens and no underscores, switch | |
606 | them underscores, and if there are both then leave them alone. | |
607 | ||
608 | This is an invertible transformation, which turns vaguely plausible Lisp | |
609 | names into vaguely plausible C names and vice versa. Lisp names with | |
610 | `funny characters' like stars and percent signs won't be any use, of | |
611 | course." | |
612 | ||
613 | ;; Work out what kind of a job we've got to do. Gather flags: bit 0 means | |
614 | ;; there are upper-case letters; bit 1 means there are lower-case letters; | |
615 | ;; bit 2 means there are hyphens; bit 3 means there are underscores. | |
616 | ;; | |
617 | ;; Consequently, (logxor flags (ash flags 1)) is interesting: bit 1 is set | |
618 | ;; if we have to frob case; bit 3 is set if we have to swap hyphens and | |
619 | ;; underscores. So use this to select functions which do bits of the | |
620 | ;; mapping, and then compose them together. | |
621 | (let* ((flags (reduce (lambda (state ch) | |
622 | (logior state | |
623 | (cond ((upper-case-p ch) 1) | |
624 | ((lower-case-p ch) 2) | |
625 | ((char= ch #\-) 4) | |
626 | ((char= ch #\_) 8) | |
627 | (t 0)))) | |
628 | string | |
629 | :initial-value 0)) | |
630 | (mask (logxor flags (ash flags 1))) | |
631 | (letter (cond ((or (not swap-case) (not (logbitp 1 mask))) | |
632 | (constantly nil)) | |
633 | ((logbitp 0 flags) | |
634 | (lambda (ch) | |
635 | (and (alpha-char-p ch) (char-downcase ch)))) | |
636 | (t | |
637 | (lambda (ch) | |
638 | (and (alpha-char-p ch) (char-upcase ch)))))) | |
639 | (uscore-hyphen (cond ((or (not (logbitp 3 mask)) (not swap-hyphen)) | |
640 | (constantly nil)) | |
641 | ((logbitp 2 flags) | |
642 | (lambda (ch) (and (char= ch #\-) #\_))) | |
643 | (t | |
644 | (lambda (ch) (and (char= ch #\_) #\-)))))) | |
645 | ||
646 | (if (logbitp 3 (logior mask (ash mask 2))) | |
647 | (map 'string (lambda (ch) | |
648 | (or (funcall letter ch) | |
649 | (funcall uscore-hyphen ch) | |
650 | ch)) | |
651 | string) | |
652 | string))) | |
653 | ||
654 | (export 'whitespace-char-p) | |
655 | (declaim (inline whitespace-char-p)) | |
656 | (defun whitespace-char-p (char) | |
657 | "Returns whether CHAR is a whitespace character. | |
658 | ||
659 | Whitespaceness is determined relative to the compile-time readtable, which | |
660 | is probably good enough for most purposes." | |
661 | (case char | |
662 | (#.(loop for i below char-code-limit | |
663 | for ch = (code-char i) | |
664 | unless (with-input-from-string (in (string ch)) | |
665 | (peek-char t in nil)) | |
666 | collect ch) t) | |
667 | (t nil))) | |
668 | ||
669 | (export 'update-position) | |
670 | (declaim (inline update-position)) | |
671 | (defun update-position (char line column) | |
672 | "Updates LINE and COLUMN appropriately for having read the character CHAR. | |
673 | ||
674 | Returns the new LINE and COLUMN numbers." | |
675 | (case char | |
676 | ((#\newline #\vt #\page) | |
677 | (values (1+ line) 0)) | |
678 | ((#\tab) | |
679 | (values line (logandc2 (+ column 8) 7))) | |
680 | (t | |
681 | (values line (1+ column))))) | |
682 | ||
683 | (export 'backtrack-position) | |
684 | (declaim (inline backtrack-position)) | |
685 | (defun backtrack-position (char line column) | |
686 | "Updates LINE and COLUMN appropriately for having unread CHAR. | |
687 | ||
688 | Well, actually an approximation for it; it will likely be wrong if the | |
689 | last character was a tab. But when the character is read again, it will | |
690 | be correct." | |
691 | ||
692 | ;; This isn't perfect: if the character doesn't actually match what was | |
693 | ;; really read then it might not actually be possible: for example, if we | |
694 | ;; push back a newline while in the middle of a line, or a tab while not at | |
695 | ;; a tab stop. In that case, we'll just lose, but hopefully not too badly. | |
696 | (case char | |
697 | ||
698 | ;; In the absence of better ideas, I'll set the column number to zero. | |
699 | ;; This is almost certainly wrong, but with a little luck nobody will ask | |
700 | ;; and it'll be all right soon. | |
701 | ((#\newline #\vt #\page) (values (1- line) 0)) | |
702 | ||
703 | ;; Winding back a single space is sufficient. If the position is | |
704 | ;; currently on a tab stop then it'll advance back here next time. If | |
705 | ;; not, we're going to lose anyway because the previous character | |
706 | ;; certainly couldn't have been a tab. | |
707 | (#\tab (values line (1- column))) | |
708 | ||
709 | ;; Anything else: just decrement the column and cross fingers. | |
710 | (t (values line (1- column))))) | |
711 | ||
712 | ;;;-------------------------------------------------------------------------- | |
713 | ;;; Functions. | |
714 | ||
715 | (export 'compose) | |
716 | (defun compose (function &rest more-functions) | |
717 | "Composition of functions. Functions are applied left-to-right. | |
718 | ||
719 | This is the reverse order of the usual mathematical notation, but I find | |
bf090e02 MW |
720 | it easier to read. It's also slightly easier to work with in programs. |
721 | That is, (compose F1 F2 ... Fn) is what a category theorist might write as | |
722 | F1 ; F2 ; ... ; Fn, rather than F1 o F2 o ... o Fn." | |
723 | ||
dea4d055 MW |
724 | (labels ((compose1 (func-a func-b) |
725 | (lambda (&rest args) | |
726 | (multiple-value-call func-b (apply func-a args))))) | |
727 | (reduce #'compose1 more-functions :initial-value function))) | |
728 | ||
729 | ;;;-------------------------------------------------------------------------- | |
c34b237d MW |
730 | ;;; Variables. |
731 | ||
732 | (export 'defvar-unbound) | |
733 | (defmacro defvar-unbound (var doc) | |
734 | "Make VAR a special variable with documentation DOC, but leave it unbound." | |
735 | `(eval-when (:compile-toplevel :load-toplevel :execute) | |
736 | (defvar ,var) | |
737 | (setf (documentation ',var 'variable) ',doc) | |
738 | ',var)) | |
739 | ||
740 | ;;;-------------------------------------------------------------------------- | |
dea4d055 MW |
741 | ;;; Symbols. |
742 | ||
743 | (export 'symbolicate) | |
744 | (defun symbolicate (&rest symbols) | |
745 | "Return a symbol named after the concatenation of the names of the SYMBOLS. | |
746 | ||
3109662a | 747 | The symbol is interned in the current `*package*'. Trad." |
dea4d055 MW |
748 | (intern (apply #'concatenate 'string (mapcar #'symbol-name symbols)))) |
749 | ||
750 | ;;;-------------------------------------------------------------------------- | |
751 | ;;; Object printing. | |
752 | ||
753 | (export 'maybe-print-unreadable-object) | |
754 | (defmacro maybe-print-unreadable-object | |
755 | ((object stream &rest args) &body body) | |
756 | "Print helper for usually-unreadable objects. | |
757 | ||
3109662a | 758 | If `*print-escape*' is set then print OBJECT unreadably using BODY. |
dea4d055 MW |
759 | Otherwise just print using BODY." |
760 | (with-gensyms (print) | |
761 | `(flet ((,print () ,@body)) | |
762 | (if *print-escape* | |
763 | (print-unreadable-object (,object ,stream ,@args) | |
764 | (,print)) | |
765 | (,print))))) | |
766 | ||
08b6e064 MW |
767 | (export 'print-ugly-stuff) |
768 | (defun print-ugly-stuff (stream func) | |
769 | "Print not-pretty things to the stream underlying STREAM. | |
770 | ||
771 | The Lisp pretty-printing machinery, notably `pprint-logical-block', may | |
772 | interpose additional streams between its body and the original target | |
773 | stream. This makes it difficult to make use of the underlying stream's | |
774 | special features, whatever they might be." | |
775 | ||
776 | ;; This is unpleasant. Hacky hacky. | |
777 | #.(or #+sbcl '(if (typep stream 'sb-pretty:pretty-stream) | |
778 | (let ((target (sb-pretty::pretty-stream-target stream))) | |
779 | (pprint-newline :mandatory stream) | |
780 | (funcall func target)) | |
781 | (funcall func stream)) | |
782 | #+cmu '(if (typep stream 'pp:pretty-stream) | |
783 | (let ((target (pp::pretty-stream-target stream))) | |
784 | (pprint-newline :mandatory stream) | |
785 | (funcall func target)) | |
786 | (funcall func stream)) | |
787 | '(funcall func stream))) | |
788 | ||
dea4d055 MW |
789 | ;;;-------------------------------------------------------------------------- |
790 | ;;; Iteration macros. | |
791 | ||
792 | (export 'dosequence) | |
793 | (defmacro dosequence ((var seq &key (start 0) (end nil) indexvar) | |
794 | &body body | |
795 | &environment env) | |
796 | "Macro for iterating over general sequences. | |
797 | ||
798 | Iterates over a (sub)sequence SEQ, delimited by START and END (which are | |
799 | evaluated). For each item of SEQ, BODY is invoked with VAR bound to the | |
800 | item, and INDEXVAR (if requested) bound to the item's index. (Note that | |
801 | this is different from most iteration constructs in Common Lisp, which | |
802 | work by mutating the variable.) | |
803 | ||
804 | The loop is surrounded by an anonymous BLOCK and the loop body forms an | |
805 | implicit TAGBODY, as is usual. There is no result-form, however." | |
806 | ||
807 | (once-only (:environment env seq start end) | |
808 | (with-gensyms ((ivar "INDEX-") (endvar "END-") (bodyfunc "BODY-")) | |
b8c698ee MW |
809 | (multiple-value-bind (docs decls body) (parse-body body :docp nil) |
810 | (declare (ignore docs)) | |
811 | ||
812 | (flet ((loopguts (indexp listp endvar) | |
813 | ;; Build a DO-loop to do what we want. | |
814 | (let* ((do-vars nil) | |
815 | (end-condition (if endvar | |
816 | `(>= ,ivar ,endvar) | |
817 | `(endp ,seq))) | |
818 | (item (if listp | |
819 | `(car ,seq) | |
820 | `(aref ,seq ,ivar))) | |
821 | (body-call `(,bodyfunc ,item))) | |
822 | (when listp | |
823 | (push `(,seq (nthcdr ,start ,seq) (cdr ,seq)) | |
824 | do-vars)) | |
825 | (when indexp | |
826 | (push `(,ivar ,start (1+ ,ivar)) do-vars)) | |
827 | (when indexvar | |
828 | (setf body-call (append body-call (list ivar)))) | |
829 | `(do ,do-vars (,end-condition) ,body-call)))) | |
830 | ||
831 | `(block nil | |
832 | (flet ((,bodyfunc (,var ,@(and indexvar `(,indexvar))) | |
833 | ,@decls | |
834 | (tagbody ,@body))) | |
dea4d055 MW |
835 | (etypecase ,seq |
836 | (vector | |
837 | (let ((,endvar (or ,end (length ,seq)))) | |
838 | ,(loopguts t nil endvar))) | |
839 | (list | |
840 | (if ,end | |
841 | ,(loopguts t t end) | |
b8c698ee | 842 | ,(loopguts indexvar t nil))))))))))) |
dea4d055 MW |
843 | |
844 | ;;;-------------------------------------------------------------------------- | |
4b8e5c03 MW |
845 | ;;; Structure accessor hacks. |
846 | ||
847 | (export 'define-access-wrapper) | |
848 | (defmacro define-access-wrapper (from to &key read-only) | |
849 | "Make (FROM THING) work like (TO THING). | |
850 | ||
851 | If not READ-ONLY, then also make (setf (FROM THING) VALUE) work like | |
852 | (setf (TO THING) VALUE). | |
853 | ||
854 | This is mostly useful for structure slot accessors where the slot has to | |
855 | be given an unpleasant name to avoid it being an external symbol." | |
856 | `(progn | |
857 | (declaim (inline ,from ,@(and (not read-only) `((setf ,from))))) | |
858 | (defun ,from (object) | |
859 | (,to object)) | |
860 | ,@(and (not read-only) | |
861 | `((defun (setf ,from) (value object) | |
862 | (setf (,to object) value)))))) | |
863 | ||
864 | ;;;-------------------------------------------------------------------------- | |
db6c3279 MW |
865 | ;;; Condition and error utilities. |
866 | ||
867 | (export 'designated-condition) | |
868 | (defun designated-condition (default-type datum arguments | |
869 | &key allow-pointless-arguments) | |
870 | "Return the condition designated by DATUM and ARGUMENTS. | |
871 | ||
872 | DATUM and ARGUMENTS together are a `condition designator' of (some | |
873 | supertype of) DEFAULT-TYPE; return the condition so designated." | |
874 | (typecase datum | |
875 | (condition | |
876 | (unless (or allow-pointless-arguments (null arguments)) | |
877 | (error "Argument list provided with specific condition")) | |
878 | datum) | |
879 | (symbol | |
880 | (apply #'make-condition datum arguments)) | |
881 | ((or string function) | |
882 | (make-condition default-type | |
883 | :format-control datum | |
884 | :format-arguments arguments)) | |
885 | (t | |
886 | (error "Unexpected condition designator datum ~S" datum)))) | |
887 | ||
888 | ;;;-------------------------------------------------------------------------- | |
dea4d055 MW |
889 | ;;; CLOS hacking. |
890 | ||
891 | (export 'default-slot) | |
892 | (defmacro default-slot ((instance slot &optional (slot-names t)) | |
893 | &body value | |
894 | &environment env) | |
895 | "If INSTANCE's slot named SLOT is unbound, set it to VALUE. | |
896 | ||
897 | Only set SLOT if it's listed in SLOT-NAMES, or SLOT-NAMES is `t' (i.e., we | |
898 | obey the `shared-initialize' protocol). SLOT-NAMES defaults to `t', so | |
899 | you can use it in `initialize-instance' or similar without ill effects. | |
900 | Both INSTANCE and SLOT are evaluated; VALUE is an implicit progn and only | |
901 | evaluated if it's needed." | |
902 | ||
903 | (once-only (:environment env instance slot slot-names) | |
904 | `(when ,(if (eq slot-names t) | |
905 | `(not (slot-boundp ,instance ,slot)) | |
906 | `(and (not (slot-boundp ,instance ,slot)) | |
907 | (or (eq ,slot-names t) | |
908 | (member ,slot ,slot-names)))) | |
909 | (setf (slot-value ,instance ,slot) | |
910 | (progn ,@value))))) | |
911 | ||
141283ff MW |
912 | (export 'define-on-demand-slot) |
913 | (defmacro define-on-demand-slot (class slot (instance) &body body) | |
914 | "Defines a slot which computes its initial value on demand. | |
915 | ||
916 | Sets up the named SLOT of CLASS to establish its value as the implicit | |
917 | progn BODY, by defining an appropriate method on `slot-unbound'." | |
b8c698ee MW |
918 | (multiple-value-bind (docs decls body) (parse-body body) |
919 | (with-gensyms (classvar slotvar) | |
920 | `(defmethod slot-unbound | |
921 | (,classvar (,instance ,class) (,slotvar (eql ',slot))) | |
922 | ,@docs ,@decls | |
923 | (declare (ignore ,classvar)) | |
fc09e191 | 924 | (setf (slot-value ,instance ',slot) (block ,slot ,@body)))))) |
141283ff | 925 | |
dea4d055 | 926 | ;;;----- That's all, folks -------------------------------------------------- |