Debian Codegraph @

contrib/asdf/asdf.lisp

raw
1 ;;; -*- mode: Lisp; Base: 10 ; Syntax: ANSI-Common-Lisp ; buffer-read-only: t; -*-
2 ;;; This is ASDF 3.1.8.10: Another System Definition Facility.
3 ;;;
4 ;;; Feedback, bug reports, and patches are all welcome:
5 ;;; please mail to <[email protected]>.
6 ;;; Note first that the canonical source for ASDF is presently
7 ;;; <URL:http://common-lisp.net/project/asdf/>.
8 ;;;
9 ;;; If you obtained this copy from anywhere else, and you experience
10 ;;; trouble using it, or find bugs, you may want to check at the
11 ;;; location above for a more recent version (and for documentation
12 ;;; and test files, if your copy came without them) before reporting
13 ;;; bugs. There are usually two "supported" revisions - the git master
14 ;;; branch is the latest development version, whereas the git release
15 ;;; branch may be slightly older but is considered `stable'
16
17 ;;; -- LICENSE START
18 ;;; (This is the MIT / X Consortium license as taken from
19 ;;; http://www.opensource.org/licenses/mit-license.html on or about
20 ;;; Monday; July 13, 2009)
21 ;;;
22 ;;; Copyright (c) 2001-2016 Daniel Barlow and contributors
23 ;;;
24 ;;; Permission is hereby granted, free of charge, to any person obtaining
25 ;;; a copy of this software and associated documentation files (the
26 ;;; "Software"), to deal in the Software without restriction, including
27 ;;; without limitation the rights to use, copy, modify, merge, publish,
28 ;;; distribute, sublicense, and/or sell copies of the Software, and to
29 ;;; permit persons to whom the Software is furnished to do so, subject to
30 ;;; the following conditions:
31 ;;;
32 ;;; The above copyright notice and this permission notice shall be
33 ;;; included in all copies or substantial portions of the Software.
34 ;;;
35 ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
36 ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
37 ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
38 ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
39 ;;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
40 ;;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
41 ;;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
42 ;;;
43 ;;; -- LICENSE END
44
45 ;;; The problem with writing a defsystem replacement is bootstrapping:
46 ;;; we can't use defsystem to compile it. Hence, all in one file.
47
48 ;;;; ---------------------------------------------------------------------------
49 ;;;; Handle ASDF package upgrade, including implementation-dependent magic.
50 ;;
51 ;; See https://bugs.launchpad.net/asdf/+bug/485687
52 ;;
53
54 (defpackage :uiop/package
55 ;; CAUTION: we must handle the first few packages specially for hot-upgrade.
56 ;; This package definition MUST NOT change unless its name too changes;
57 ;; if/when it changes, don't forget to add new functions missing from below.
58 ;; Until then, uiop/package is frozen to forever
59 ;; import and export the same exact symbols as for ASDF 2.27.
60 ;; Any other symbol must be import-from'ed and re-export'ed in a different package.
61 (:use :common-lisp)
62 (:export
63 #:find-package* #:find-symbol* #:symbol-call
64 #:intern* #:export* #:import* #:shadowing-import* #:shadow* #:make-symbol* #:unintern*
65 #:symbol-shadowing-p #:home-package-p
66 #:symbol-package-name #:standard-common-lisp-symbol-p
67 #:reify-package #:unreify-package #:reify-symbol #:unreify-symbol
68 #:nuke-symbol-in-package #:nuke-symbol #:rehome-symbol
69 #:ensure-package-unused #:delete-package*
70 #:package-names #:packages-from-names #:fresh-package-name #:rename-package-away
71 #:package-definition-form #:parse-define-package-form
72 #:ensure-package #:define-package))
73
74 (in-package :uiop/package)
75
76 ;;;; General purpose package utilities
77
78 (eval-when (:load-toplevel :compile-toplevel :execute)
79 (defun find-package* (package-designator &optional (error t))
80 (let ((package (find-package package-designator)))
81 (cond
82 (package package)
83 (error (error "No package named ~S" (string package-designator)))
84 (t nil))))
85 (defun find-symbol* (name package-designator &optional (error t))
86 "Find a symbol in a package of given string'ified NAME;
87 unlike CL:FIND-SYMBOL, work well with 'modern' case sensitive syntax
88 by letting you supply a symbol or keyword for the name;
89 also works well when the package is not present.
90 If optional ERROR argument is NIL, return NIL instead of an error
91 when the symbol is not found."
92 (block nil
93 (let ((package (find-package* package-designator error)))
94 (when package ;; package error handled by find-package* already
95 (multiple-value-bind (symbol status) (find-symbol (string name) package)
96 (cond
97 (status (return (values symbol status)))
98 (error (error "There is no symbol ~S in package ~S" name (package-name package))))))
99 (values nil nil))))
100 (defun symbol-call (package name &rest args)
101 "Call a function associated with symbol of given name in given package,
102 with given ARGS. Useful when the call is read before the package is loaded,
103 or when loading the package is optional."
104 (apply (find-symbol* name package) args))
105 (defun intern* (name package-designator &optional (error t))
106 (intern (string name) (find-package* package-designator error)))
107 (defun export* (name package-designator)
108 (let* ((package (find-package* package-designator))
109 (symbol (intern* name package)))
110 (export (or symbol (list symbol)) package)))
111 (defun import* (symbol package-designator)
112 (import (or symbol (list symbol)) (find-package* package-designator)))
113 (defun shadowing-import* (symbol package-designator)
114 (shadowing-import (or symbol (list symbol)) (find-package* package-designator)))
115 (defun shadow* (name package-designator)
116 (shadow (list (string name)) (find-package* package-designator)))
117 (defun make-symbol* (name)
118 (etypecase name
119 (string (make-symbol name))
120 (symbol (copy-symbol name))))
121 (defun unintern* (name package-designator &optional (error t))
122 (block nil
123 (let ((package (find-package* package-designator error)))
124 (when package
125 (multiple-value-bind (symbol status) (find-symbol* name package error)
126 (cond
127 (status (unintern symbol package)
128 (return (values symbol status)))
129 (error (error "symbol ~A not present in package ~A"
130 (string symbol) (package-name package))))))
131 (values nil nil))))
132 (defun symbol-shadowing-p (symbol package)
133 (and (member symbol (package-shadowing-symbols package)) t))
134 (defun home-package-p (symbol package)
135 (and package (let ((sp (symbol-package symbol)))
136 (and sp (let ((pp (find-package* package)))
137 (and pp (eq sp pp))))))))
138
139
140 (eval-when (:load-toplevel :compile-toplevel :execute)
141 (defun symbol-package-name (symbol)
142 (let ((package (symbol-package symbol)))
143 (and package (package-name package))))
144 (defun standard-common-lisp-symbol-p (symbol)
145 (multiple-value-bind (sym status) (find-symbol* symbol :common-lisp nil)
146 (and (eq sym symbol) (eq status :external))))
147 (defun reify-package (package &optional package-context)
148 (if (eq package package-context) t
149 (etypecase package
150 (null nil)
151 ((eql (find-package :cl)) :cl)
152 (package (package-name package)))))
153 (defun unreify-package (package &optional package-context)
154 (etypecase package
155 (null nil)
156 ((eql t) package-context)
157 ((or symbol string) (find-package package))))
158 (defun reify-symbol (symbol &optional package-context)
159 (etypecase symbol
160 ((or keyword (satisfies standard-common-lisp-symbol-p)) symbol)
161 (symbol (vector (symbol-name symbol)
162 (reify-package (symbol-package symbol) package-context)))))
163 (defun unreify-symbol (symbol &optional package-context)
164 (etypecase symbol
165 (symbol symbol)
166 ((simple-vector 2)
167 (let* ((symbol-name (svref symbol 0))
168 (package-foo (svref symbol 1))
169 (package (unreify-package package-foo package-context)))
170 (if package (intern* symbol-name package)
171 (make-symbol* symbol-name)))))))
172
173 (eval-when (:load-toplevel :compile-toplevel :execute)
174 (defvar *all-package-happiness* '())
175 (defvar *all-package-fishiness* (list t))
176 (defun record-fishy (info)
177 ;;(format t "~&FISHY: ~S~%" info)
178 (push info *all-package-fishiness*))
179 (defmacro when-package-fishiness (&body body)
180 `(when *all-package-fishiness* ,@body))
181 (defmacro note-package-fishiness (&rest info)
182 `(when-package-fishiness (record-fishy (list ,@info)))))
183
184 (eval-when (:load-toplevel :compile-toplevel :execute)
185 #+(or clisp clozure)
186 (defun get-setf-function-symbol (symbol)
187 #+clisp (let ((sym (get symbol 'system::setf-function)))
188 (if sym (values sym :setf-function)
189 (let ((sym (get symbol 'system::setf-expander)))
190 (if sym (values sym :setf-expander)
191 (values nil nil)))))
192 #+clozure (gethash symbol ccl::%setf-function-names%))
193 #+(or clisp clozure)
194 (defun set-setf-function-symbol (new-setf-symbol symbol &optional kind)
195 #+clisp (assert (member kind '(:setf-function :setf-expander)))
196 #+clozure (assert (eq kind t))
197 #+clisp
198 (cond
199 ((null new-setf-symbol)
200 (remprop symbol 'system::setf-function)
201 (remprop symbol 'system::setf-expander))
202 ((eq kind :setf-function)
203 (setf (get symbol 'system::setf-function) new-setf-symbol))
204 ((eq kind :setf-expander)
205 (setf (get symbol 'system::setf-expander) new-setf-symbol))
206 (t (error "invalid kind of setf-function ~S for ~S to be set to ~S"
207 kind symbol new-setf-symbol)))
208 #+clozure
209 (progn
210 (gethash symbol ccl::%setf-function-names%) new-setf-symbol
211 (gethash new-setf-symbol ccl::%setf-function-name-inverses%) symbol))
212 #+(or clisp clozure)
213 (defun create-setf-function-symbol (symbol)
214 #+clisp (system::setf-symbol symbol)
215 #+clozure (ccl::construct-setf-function-name symbol))
216 (defun set-dummy-symbol (symbol reason other-symbol)
217 (setf (get symbol 'dummy-symbol) (cons reason other-symbol)))
218 (defun make-dummy-symbol (symbol)
219 (let ((dummy (copy-symbol symbol)))
220 (set-dummy-symbol dummy 'replacing symbol)
221 (set-dummy-symbol symbol 'replaced-by dummy)
222 dummy))
223 (defun dummy-symbol (symbol)
224 (get symbol 'dummy-symbol))
225 (defun get-dummy-symbol (symbol)
226 (let ((existing (dummy-symbol symbol)))
227 (if existing (values (cdr existing) (car existing))
228 (make-dummy-symbol symbol))))
229 (defun nuke-symbol-in-package (symbol package-designator)
230 (let ((package (find-package* package-designator))
231 (name (symbol-name symbol)))
232 (multiple-value-bind (sym stat) (find-symbol name package)
233 (when (and (member stat '(:internal :external)) (eq symbol sym))
234 (if (symbol-shadowing-p symbol package)
235 (shadowing-import* (get-dummy-symbol symbol) package)
236 (unintern* symbol package))))))
237 (defun nuke-symbol (symbol &optional (packages (list-all-packages)))
238 #+(or clisp clozure)
239 (multiple-value-bind (setf-symbol kind)
240 (get-setf-function-symbol symbol)
241 (when kind (nuke-symbol setf-symbol)))
242 (loop :for p :in packages :do (nuke-symbol-in-package symbol p)))
243 (defun rehome-symbol (symbol package-designator)
244 "Changes the home package of a symbol, also leaving it present in its old home if any"
245 (let* ((name (symbol-name symbol))
246 (package (find-package* package-designator))
247 (old-package (symbol-package symbol))
248 (old-status (and old-package (nth-value 1 (find-symbol name old-package))))
249 (shadowing (and old-package (symbol-shadowing-p symbol old-package) (make-symbol name))))
250 (multiple-value-bind (overwritten-symbol overwritten-symbol-status) (find-symbol name package)
251 (unless (eq package old-package)
252 (let ((overwritten-symbol-shadowing-p
253 (and overwritten-symbol-status
254 (symbol-shadowing-p overwritten-symbol package))))
255 (note-package-fishiness
256 :rehome-symbol name
257 (when old-package (package-name old-package)) old-status (and shadowing t)
258 (package-name package) overwritten-symbol-status overwritten-symbol-shadowing-p)
259 (when old-package
260 (if shadowing
261 (shadowing-import* shadowing old-package))
262 (unintern* symbol old-package))
263 (cond
264 (overwritten-symbol-shadowing-p
265 (shadowing-import* symbol package))
266 (t
267 (when overwritten-symbol-status
268 (unintern* overwritten-symbol package))
269 (import* symbol package)))
270 (if shadowing
271 (shadowing-import* symbol old-package)
272 (import* symbol old-package))
273 #+(or clisp clozure)
274 (multiple-value-bind (setf-symbol kind)
275 (get-setf-function-symbol symbol)
276 (when kind
277 (let* ((setf-function (fdefinition setf-symbol))
278 (new-setf-symbol (create-setf-function-symbol symbol)))
279 (note-package-fishiness
280 :setf-function
281 name (package-name package)
282 (symbol-name setf-symbol) (symbol-package-name setf-symbol)
283 (symbol-name new-setf-symbol) (symbol-package-name new-setf-symbol))
284 (when (symbol-package setf-symbol)
285 (unintern* setf-symbol (symbol-package setf-symbol)))
286 (setf (fdefinition new-setf-symbol) setf-function)
287 (set-setf-function-symbol new-setf-symbol symbol kind))))
288 #+(or clisp clozure)
289 (multiple-value-bind (overwritten-setf foundp)
290 (get-setf-function-symbol overwritten-symbol)
291 (when foundp
292 (unintern overwritten-setf)))
293 (when (eq old-status :external)
294 (export* symbol old-package))
295 (when (eq overwritten-symbol-status :external)
296 (export* symbol package))))
297 (values overwritten-symbol overwritten-symbol-status))))
298 (defun ensure-package-unused (package)
299 (loop :for p :in (package-used-by-list package) :do
300 (unuse-package package p)))
301 (defun delete-package* (package &key nuke)
302 (let ((p (find-package package)))
303 (when p
304 (when nuke (do-symbols (s p) (when (home-package-p s p) (nuke-symbol s))))
305 (ensure-package-unused p)
306 (delete-package package))))
307 (defun package-names (package)
308 (cons (package-name package) (package-nicknames package)))
309 (defun packages-from-names (names)
310 (remove-duplicates (remove nil (mapcar #'find-package names)) :from-end t))
311 (defun fresh-package-name (&key (prefix :%TO-BE-DELETED)
312 separator
313 (index (random most-positive-fixnum)))
314 (loop :for i :from index
315 :for n = (format nil "~A~@[~A~D~]" prefix (and (plusp i) (or separator "")) i)
316 :thereis (and (not (find-package n)) n)))
317 (defun rename-package-away (p &rest keys &key prefix &allow-other-keys)
318 (let ((new-name
319 (apply 'fresh-package-name
320 :prefix (or prefix (format nil "__~A__" (package-name p))) keys)))
321 (record-fishy (list :rename-away (package-names p) new-name))
322 (rename-package p new-name))))
323
324
325 ;;; Communicable representation of symbol and package information
326
327 (eval-when (:load-toplevel :compile-toplevel :execute)
328 (defun package-definition-form (package-designator
329 &key (nicknamesp t) (usep t)
330 (shadowp t) (shadowing-import-p t)
331 (exportp t) (importp t) internp (error t))
332 (let* ((package (or (find-package* package-designator error)
333 (return-from package-definition-form nil)))
334 (name (package-name package))
335 (nicknames (package-nicknames package))
336 (use (mapcar #'package-name (package-use-list package)))
337 (shadow ())
338 (shadowing-import (make-hash-table :test 'equal))
339 (import (make-hash-table :test 'equal))
340 (export ())
341 (intern ()))
342 (when package
343 (loop :for sym :being :the :symbols :in package
344 :for status = (nth-value 1 (find-symbol* sym package)) :do
345 (ecase status
346 ((nil :inherited))
347 ((:internal :external)
348 (let* ((name (symbol-name sym))
349 (external (eq status :external))
350 (home (symbol-package sym))
351 (home-name (package-name home))
352 (imported (not (eq home package)))
353 (shadowing (symbol-shadowing-p sym package)))
354 (cond
355 ((and shadowing imported)
356 (push name (gethash home-name shadowing-import)))
357 (shadowing
358 (push name shadow))
359 (imported
360 (push name (gethash home-name import))))
361 (cond
362 (external
363 (push name export))
364 (imported)
365 (t (push name intern)))))))
366 (labels ((sort-names (names)
367 (sort (copy-list names) #'string<))
368 (table-keys (table)
369 (loop :for k :being :the :hash-keys :of table :collect k))
370 (when-relevant (key value)
371 (when value (list (cons key value))))
372 (import-options (key table)
373 (loop :for i :in (sort-names (table-keys table))
374 :collect `(,key ,i ,@(sort-names (gethash i table))))))
375 `(defpackage ,name
376 ,@(when-relevant :nicknames (and nicknamesp (sort-names nicknames)))
377 (:use ,@(and usep (sort-names use)))
378 ,@(when-relevant :shadow (and shadowp (sort-names shadow)))
379 ,@(import-options :shadowing-import-from (and shadowing-import-p shadowing-import))
380 ,@(import-options :import-from (and importp import))
381 ,@(when-relevant :export (and exportp (sort-names export)))
382 ,@(when-relevant :intern (and internp (sort-names intern)))))))))
383
384
385 ;;; ensure-package, define-package
386 (eval-when (:load-toplevel :compile-toplevel :execute)
387 (defun ensure-shadowing-import (name to-package from-package shadowed imported)
388 (check-type name string)
389 (check-type to-package package)
390 (check-type from-package package)
391 (check-type shadowed hash-table)
392 (check-type imported hash-table)
393 (let ((import-me (find-symbol* name from-package)))
394 (multiple-value-bind (existing status) (find-symbol name to-package)
395 (cond
396 ((gethash name shadowed)
397 (unless (eq import-me existing)
398 (error "Conflicting shadowings for ~A" name)))
399 (t
400 (setf (gethash name shadowed) t)
401 (setf (gethash name imported) t)
402 (unless (or (null status)
403 (and (member status '(:internal :external))
404 (eq existing import-me)
405 (symbol-shadowing-p existing to-package)))
406 (note-package-fishiness
407 :shadowing-import name
408 (package-name from-package)
409 (or (home-package-p import-me from-package) (symbol-package-name import-me))
410 (package-name to-package) status
411 (and status (or (home-package-p existing to-package) (symbol-package-name existing)))))
412 (shadowing-import* import-me to-package))))))
413 (defun ensure-imported (import-me into-package &optional from-package)
414 (check-type import-me symbol)
415 (check-type into-package package)
416 (check-type from-package (or null package))
417 (let ((name (symbol-name import-me)))
418 (multiple-value-bind (existing status) (find-symbol name into-package)
419 (cond
420 ((not status)
421 (import* import-me into-package))
422 ((eq import-me existing))
423 (t
424 (let ((shadowing-p (symbol-shadowing-p existing into-package)))
425 (note-package-fishiness
426 :ensure-imported name
427 (and from-package (package-name from-package))
428 (or (home-package-p import-me from-package) (symbol-package-name import-me))
429 (package-name into-package)
430 status
431 (and status (or (home-package-p existing into-package) (symbol-package-name existing)))
432 shadowing-p)
433 (cond
434 ((or shadowing-p (eq status :inherited))
435 (shadowing-import* import-me into-package))
436 (t
437 (unintern* existing into-package)
438 (import* import-me into-package))))))))
439 (values))
440 (defun ensure-import (name to-package from-package shadowed imported)
441 (check-type name string)
442 (check-type to-package package)
443 (check-type from-package package)
444 (check-type shadowed hash-table)
445 (check-type imported hash-table)
446 (multiple-value-bind (import-me import-status) (find-symbol name from-package)
447 (when (null import-status)
448 (note-package-fishiness
449 :import-uninterned name (package-name from-package) (package-name to-package))
450 (setf import-me (intern* name from-package)))
451 (multiple-value-bind (existing status) (find-symbol name to-package)
452 (cond
453 ((and imported (gethash name imported))
454 (unless (and status (eq import-me existing))
455 (error "Can't import ~S from both ~S and ~S"
456 name (package-name (symbol-package existing)) (package-name from-package))))
457 ((gethash name shadowed)
458 (error "Can't both shadow ~S and import it from ~S" name (package-name from-package)))
459 (t
460 (setf (gethash name imported) t))))
461 (ensure-imported import-me to-package from-package)))
462 (defun ensure-inherited (name symbol to-package from-package mixp shadowed imported inherited)
463 (check-type name string)
464 (check-type symbol symbol)
465 (check-type to-package package)
466 (check-type from-package package)
467 (check-type mixp (member nil t)) ; no cl:boolean on Genera
468 (check-type shadowed hash-table)
469 (check-type imported hash-table)
470 (check-type inherited hash-table)
471 (multiple-value-bind (existing status) (find-symbol name to-package)
472 (let* ((sp (symbol-package symbol))
473 (in (gethash name inherited))
474 (xp (and status (symbol-package existing))))
475 (when (null sp)
476 (note-package-fishiness
477 :import-uninterned name
478 (package-name from-package) (package-name to-package) mixp)
479 (import* symbol from-package)
480 (setf sp (package-name from-package)))
481 (cond
482 ((gethash name shadowed))
483 (in
484 (unless (equal sp (first in))
485 (if mixp
486 (ensure-shadowing-import name to-package (second in) shadowed imported)
487 (error "Can't inherit ~S from ~S, it is inherited from ~S"
488 name (package-name sp) (package-name (first in))))))
489 ((gethash name imported)
490 (unless (eq symbol existing)
491 (error "Can't inherit ~S from ~S, it is imported from ~S"
492 name (package-name sp) (package-name xp))))
493 (t
494 (setf (gethash name inherited) (list sp from-package))
495 (when (and status (not (eq sp xp)))
496 (let ((shadowing (symbol-shadowing-p existing to-package)))
497 (note-package-fishiness
498 :inherited name
499 (package-name from-package)
500 (or (home-package-p symbol from-package) (symbol-package-name symbol))
501 (package-name to-package)
502 (or (home-package-p existing to-package) (symbol-package-name existing)))
503 (if shadowing (ensure-shadowing-import name to-package from-package shadowed imported)
504 (unintern* existing to-package)))))))))
505 (defun ensure-mix (name symbol to-package from-package shadowed imported inherited)
506 (check-type name string)
507 (check-type symbol symbol)
508 (check-type to-package package)
509 (check-type from-package package)
510 (check-type shadowed hash-table)
511 (check-type imported hash-table)
512 (check-type inherited hash-table)
513 (unless (gethash name shadowed)
514 (multiple-value-bind (existing status) (find-symbol name to-package)
515 (let* ((sp (symbol-package symbol))
516 (im (gethash name imported))
517 (in (gethash name inherited)))
518 (cond
519 ((or (null status)
520 (and status (eq symbol existing))
521 (and in (eq sp (first in))))
522 (ensure-inherited name symbol to-package from-package t shadowed imported inherited))
523 (in
524 (remhash name inherited)
525 (ensure-shadowing-import name to-package (second in) shadowed imported))
526 (im
527 (error "Symbol ~S import from ~S~:[~; actually ~:[uninterned~;~:*from ~S~]~] conflicts with existing symbol in ~S~:[~; actually ~:[uninterned~;from ~:*~S~]~]"
528 name (package-name from-package)
529 (home-package-p symbol from-package) (symbol-package-name symbol)
530 (package-name to-package)
531 (home-package-p existing to-package) (symbol-package-name existing)))
532 (t
533 (ensure-inherited name symbol to-package from-package t shadowed imported inherited)))))))
534
535 (defun recycle-symbol (name recycle exported)
536 ;; Takes a symbol NAME (a string), a list of package designators for RECYCLE
537 ;; packages, and a hash-table of names (strings) of symbols scheduled to be
538 ;; EXPORTED from the package being defined. It returns two values, the
539 ;; symbol found (if any, or else NIL), and a boolean flag indicating whether
540 ;; a symbol was found. The caller (DEFINE-PACKAGE) will then do the
541 ;; re-homing of the symbol, etc.
542 (check-type name string)
543 (check-type recycle list)
544 (check-type exported hash-table)
545 (when (gethash name exported) ;; don't bother recycling private symbols
546 (let (recycled foundp)
547 (dolist (r recycle (values recycled foundp))
548 (multiple-value-bind (symbol status) (find-symbol name r)
549 (when (and status (home-package-p symbol r))
550 (cond
551 (foundp
552 ;; (nuke-symbol symbol)) -- even simple variable names like O or C will do that.
553 (note-package-fishiness :recycled-duplicate name (package-name foundp) (package-name r)))
554 (t
555 (setf recycled symbol foundp r)))))))))
556 (defun symbol-recycled-p (sym recycle)
557 (check-type sym symbol)
558 (check-type recycle list)
559 (and (member (symbol-package sym) recycle) t))
560 (defun ensure-symbol (name package intern recycle shadowed imported inherited exported)
561 (check-type name string)
562 (check-type package package)
563 (check-type intern (member nil t)) ; no cl:boolean on Genera
564 (check-type shadowed hash-table)
565 (check-type imported hash-table)
566 (check-type inherited hash-table)
567 (unless (or (gethash name shadowed)
568 (gethash name imported)
569 (gethash name inherited))
570 (multiple-value-bind (existing status)
571 (find-symbol name package)
572 (multiple-value-bind (recycled previous) (recycle-symbol name recycle exported)
573 (cond
574 ((and status (eq existing recycled) (eq previous package)))
575 (previous
576 (rehome-symbol recycled package))
577 ((and status (eq package (symbol-package existing))))
578 (t
579 (when status
580 (note-package-fishiness
581 :ensure-symbol name
582 (reify-package (symbol-package existing) package)
583 status intern)
584 (unintern existing))
585 (when intern
586 (intern* name package))))))))
587 (declaim (ftype (function (t t t &optional t) t) ensure-exported))
588 (defun ensure-exported-to-user (name symbol to-package &optional recycle)
589 (check-type name string)
590 (check-type symbol symbol)
591 (check-type to-package package)
592 (check-type recycle list)
593 (assert (equal name (symbol-name symbol)))
594 (multiple-value-bind (existing status) (find-symbol name to-package)
595 (unless (and status (eq symbol existing))
596 (let ((accessible
597 (or (null status)
598 (let ((shadowing (symbol-shadowing-p existing to-package))
599 (recycled (symbol-recycled-p existing recycle)))
600 (unless (and shadowing (not recycled))
601 (note-package-fishiness
602 :ensure-export name (symbol-package-name symbol)
603 (package-name to-package)
604 (or (home-package-p existing to-package) (symbol-package-name existing))
605 status shadowing)
606 (if (or (eq status :inherited) shadowing)
607 (shadowing-import* symbol to-package)
608 (unintern existing to-package))
609 t)))))
610 (when (and accessible (eq status :external))
611 (ensure-exported name symbol to-package recycle))))))
612 (defun ensure-exported (name symbol from-package &optional recycle)
613 (dolist (to-package (package-used-by-list from-package))
614 (ensure-exported-to-user name symbol to-package recycle))
615 (unless (eq from-package (symbol-package symbol))
616 (ensure-imported symbol from-package))
617 (export* name from-package))
618 (defun ensure-export (name from-package &optional recycle)
619 (multiple-value-bind (symbol status) (find-symbol* name from-package)
620 (unless (eq status :external)
621 (ensure-exported name symbol from-package recycle))))
622 (defun ensure-package (name &key
623 nicknames documentation use
624 shadow shadowing-import-from
625 import-from export intern
626 recycle mix reexport
627 unintern)
628 #+genera (declare (ignore documentation))
629 (let* ((package-name (string name))
630 (nicknames (mapcar #'string nicknames))
631 (names (cons package-name nicknames))
632 (previous (packages-from-names names))
633 (discarded (cdr previous))
634 (to-delete ())
635 (package (or (first previous) (make-package package-name :nicknames nicknames)))
636 (recycle (packages-from-names recycle))
637 (use (mapcar 'find-package* use))
638 (mix (mapcar 'find-package* mix))
639 (reexport (mapcar 'find-package* reexport))
640 (shadow (mapcar 'string shadow))
641 (export (mapcar 'string export))
642 (intern (mapcar 'string intern))
643 (unintern (mapcar 'string unintern))
644 (shadowed (make-hash-table :test 'equal)) ; string to bool
645 (imported (make-hash-table :test 'equal)) ; string to bool
646 (exported (make-hash-table :test 'equal)) ; string to bool
647 ;; string to list home package and use package:
648 (inherited (make-hash-table :test 'equal)))
649 (when-package-fishiness (record-fishy package-name))
650 #-genera
651 (when documentation (setf (documentation package t) documentation))
652 (loop :for p :in (set-difference (package-use-list package) (append mix use))
653 :do (note-package-fishiness :over-use name (package-names p))
654 (unuse-package p package))
655 (loop :for p :in discarded
656 :for n = (remove-if #'(lambda (x) (member x names :test 'equal))
657 (package-names p))
658 :do (note-package-fishiness :nickname name (package-names p))
659 (cond (n (rename-package p (first n) (rest n)))
660 (t (rename-package-away p)
661 (push p to-delete))))
662 (rename-package package package-name nicknames)
663 (dolist (name unintern)
664 (multiple-value-bind (existing status) (find-symbol name package)
665 (when status
666 (unless (eq status :inherited)
667 (note-package-fishiness
668 :unintern (package-name package) name (symbol-package-name existing) status)
669 (unintern* name package nil)))))
670 (dolist (name export)
671 (setf (gethash name exported) t))
672 (dolist (p reexport)
673 (do-external-symbols (sym p)
674 (setf (gethash (string sym) exported) t)))
675 (do-external-symbols (sym package)
676 (let ((name (symbol-name sym)))
677 (unless (gethash name exported)
678 (note-package-fishiness
679 :over-export (package-name package) name
680 (or (home-package-p sym package) (symbol-package-name sym)))
681 (unexport sym package))))
682 (dolist (name shadow)
683 (setf (gethash name shadowed) t)
684 (multiple-value-bind (existing status) (find-symbol name package)
685 (multiple-value-bind (recycled previous) (recycle-symbol name recycle exported)
686 (let ((shadowing (and status (symbol-shadowing-p existing package))))
687 (cond
688 ((eq previous package))
689 (previous
690 (rehome-symbol recycled package))
691 ((or (member status '(nil :inherited))
692 (home-package-p existing package)))
693 (t
694 (let ((dummy (make-symbol name)))
695 (note-package-fishiness
696 :shadow-imported (package-name package) name
697 (symbol-package-name existing) status shadowing)
698 (shadowing-import* dummy package)
699 (import* dummy package)))))))
700 (shadow* name package))
701 (loop :for (p . syms) :in shadowing-import-from
702 :for pp = (find-package* p) :do
703 (dolist (sym syms) (ensure-shadowing-import (string sym) package pp shadowed imported)))
704 (loop :for p :in mix
705 :for pp = (find-package* p) :do
706 (do-external-symbols (sym pp) (ensure-mix (symbol-name sym) sym package pp shadowed imported inherited)))
707 (loop :for (p . syms) :in import-from
708 :for pp = (find-package p) :do
709 (dolist (sym syms) (ensure-import (symbol-name sym) package pp shadowed imported)))
710 (dolist (p (append use mix))
711 (do-external-symbols (sym p) (ensure-inherited (string sym) sym package p nil shadowed imported inherited))
712 (use-package p package))
713 (loop :for name :being :the :hash-keys :of exported :do
714 (ensure-symbol name package t recycle shadowed imported inherited exported)
715 (ensure-export name package recycle))
716 (dolist (name intern)
717 (ensure-symbol name package t recycle shadowed imported inherited exported))
718 (do-symbols (sym package)
719 (ensure-symbol (symbol-name sym) package nil recycle shadowed imported inherited exported))
720 (map () 'delete-package* to-delete)
721 package)))
722
723 (eval-when (:load-toplevel :compile-toplevel :execute)
724 (defun parse-define-package-form (package clauses)
725 (loop
726 :with use-p = nil :with recycle-p = nil
727 :with documentation = nil
728 :for (kw . args) :in clauses
729 :when (eq kw :nicknames) :append args :into nicknames :else
730 :when (eq kw :documentation)
731 :do (cond
732 (documentation (error "define-package: can't define documentation twice"))
733 ((or (atom args) (cdr args)) (error "define-package: bad documentation"))
734 (t (setf documentation (car args)))) :else
735 :when (eq kw :use) :append args :into use :and :do (setf use-p t) :else
736 :when (eq kw :shadow) :append args :into shadow :else
737 :when (eq kw :shadowing-import-from) :collect args :into shadowing-import-from :else
738 :when (eq kw :import-from) :collect args :into import-from :else
739 :when (eq kw :export) :append args :into export :else
740 :when (eq kw :intern) :append args :into intern :else
741 :when (eq kw :recycle) :append args :into recycle :and :do (setf recycle-p t) :else
742 :when (eq kw :mix) :append args :into mix :else
743 :when (eq kw :reexport) :append args :into reexport :else
744 :when (eq kw :use-reexport) :append args :into use :and :append args :into reexport
745 :and :do (setf use-p t) :else
746 :when (eq kw :mix-reexport) :append args :into mix :and :append args :into reexport
747 :and :do (setf use-p t) :else
748 :when (eq kw :unintern) :append args :into unintern :else
749 :do (error "unrecognized define-package keyword ~S" kw)
750 :finally (return `(,package
751 :nicknames ,nicknames :documentation ,documentation
752 :use ,(if use-p use '(:common-lisp))
753 :shadow ,shadow :shadowing-import-from ,shadowing-import-from
754 :import-from ,import-from :export ,export :intern ,intern
755 :recycle ,(if recycle-p recycle (cons package nicknames))
756 :mix ,mix :reexport ,reexport :unintern ,unintern)))))
757
758 (defmacro define-package (package &rest clauses)
759 "DEFINE-PACKAGE takes a PACKAGE and a number of CLAUSES, of the form
760 \(KEYWORD . ARGS\).
761 DEFINE-PACKAGE supports the following keywords:
762 USE, SHADOW, SHADOWING-IMPORT-FROM, IMPORT-FROM, EXPORT, INTERN -- as per CL:DEFPACKAGE.
763 RECYCLE -- Recycle the package's exported symbols from the specified packages,
764 in order. For every symbol scheduled to be exported by the DEFINE-PACKAGE,
765 either through an :EXPORT option or a :REEXPORT option, if the symbol exists in
766 one of the :RECYCLE packages, the first such symbol is re-homed to the package
767 being defined.
768 For the sake of idempotence, it is important that the package being defined
769 should appear in first position if it already exists, and even if it doesn't,
770 ahead of any package that is not going to be deleted afterwards and never
771 created again. In short, except for special cases, always make it the first
772 package on the list if the list is not empty.
773 MIX -- Takes a list of package designators. MIX behaves like
774 \(:USE PKG1 PKG2 ... PKGn\) but additionally uses :SHADOWING-IMPORT-FROM to
775 resolve conflicts in favor of the first found symbol. It may still yield
776 an error if there is a conflict with an explicitly :IMPORT-FROM symbol.
777 REEXPORT -- Takes a list of package designators. For each package, p, in the list,
778 export symbols with the same name as those exported from p. Note that in the case
779 of shadowing, etc. the symbols with the same name may not be the same symbols.
780 UNINTERN -- Remove symbols here from PACKAGE."
781 (let ((ensure-form
782 `(apply 'ensure-package ',(parse-define-package-form package clauses))))
783 `(progn
784 #+(or clasp ecl gcl mkcl) (defpackage ,package (:use))
785 (eval-when (:compile-toplevel :load-toplevel :execute)
786 ,ensure-form))))
787
788 ;;;; Final tricks to keep various implementations happy.
789 ;; We want most such tricks in common-lisp.lisp,
790 ;; but these need to be done before the define-package form there,
791 ;; that we nevertheless want to be the very first form.
792 (eval-when (:load-toplevel :compile-toplevel :execute)
793 #+allegro ;; We need to disable autoloading BEFORE any mention of package ASDF.
794 (setf excl::*autoload-package-name-alist*
795 (remove "asdf" excl::*autoload-package-name-alist*
796 :test 'equalp :key 'car)))
797
798 ;; Compatibility with whoever calls asdf/package
799 (define-package :asdf/package (:use :cl :uiop/package) (:reexport :uiop/package))
800 ;;;; -------------------------------------------------------------------------
801 ;;;; Handle compatibility with multiple implementations.
802 ;;; This file is for papering over the deficiencies and peculiarities
803 ;;; of various Common Lisp implementations.
804 ;;; For implementation-specific access to the system, see os.lisp instead.
805 ;;; A few functions are defined here, but actually exported from utility;
806 ;;; from this package only common-lisp symbols are exported.
807
808 (uiop/package:define-package :uiop/common-lisp
809 (:nicknames :uoip/cl :asdf/common-lisp :asdf/cl)
810 (:use :uiop/package)
811 (:use-reexport #-genera :common-lisp #+genera :future-common-lisp)
812 (:recycle :uiop/common-lisp :uoip/cl :asdf/common-lisp :asdf/cl :asdf)
813 #+allegro (:intern #:*acl-warn-save*)
814 #+cormanlisp (:shadow #:user-homedir-pathname)
815 #+cormanlisp
816 (:export
817 #:logical-pathname #:translate-logical-pathname
818 #:make-broadcast-stream #:file-namestring)
819 #+genera (:shadowing-import-from :scl #:boolean)
820 #+genera (:export #:boolean #:ensure-directories-exist #:read-sequence #:write-sequence)
821 #+(or mcl cmucl) (:shadow #:user-homedir-pathname))
822 (in-package :uiop/common-lisp)
823
824 #-(or abcl allegro clasp clisp clozure cmucl cormanlisp ecl gcl genera lispworks mcl mkcl sbcl scl xcl)
825 (error "ASDF is not supported on your implementation. Please help us port it.")
826
827 ;; (declaim (optimize (speed 1) (debug 3) (safety 3))) ; DON'T: trust implementation defaults.
828
829
830 ;;;; Early meta-level tweaks
831
832 #+(or allegro clasp clisp clozure cmucl ecl mkcl sbcl)
833 (eval-when (:load-toplevel :compile-toplevel :execute)
834 (when (and #+allegro (member :ics *features*)
835 #+(or clasp clisp cmucl ecl mkcl) (member :unicode *features*)
836 #+clozure (member :openmcl-unicode-strings *features*)
837 #+sbcl (member :sb-unicode *features*))
838 ;; Check for unicode at runtime, so that a hypothetical FASL compiled with unicode
839 ;; but loaded in a non-unicode setting (e.g. on Allegro) won't tell a lie.
840 (pushnew :asdf-unicode *features*)))
841
842 #+allegro
843 (eval-when (:load-toplevel :compile-toplevel :execute)
844 (defparameter *acl-warn-save*
845 (when (boundp 'excl:*warn-on-nested-reader-conditionals*)
846 excl:*warn-on-nested-reader-conditionals*))
847 (when (boundp 'excl:*warn-on-nested-reader-conditionals*)
848 (setf excl:*warn-on-nested-reader-conditionals* nil))
849 (setf *print-readably* nil))
850
851 #+clasp
852 (eval-when (:load-toplevel :compile-toplevel :execute)
853 (setf *load-verbose* nil)
854 (defun use-ecl-byte-compiler-p () nil))
855
856 #+clozure (in-package :ccl)
857 #+(and clozure windows-target) ;; See http://trac.clozure.com/ccl/ticket/1117
858 (eval-when (:load-toplevel :compile-toplevel :execute)
859 (unless (fboundp 'external-process-wait)
860 (in-development-mode
861 (defun external-process-wait (proc)
862 (when (and (external-process-pid proc) (eq (external-process-%status proc) :running))
863 (with-interrupts-enabled
864 (wait-on-semaphore (external-process-completed proc))))
865 (values (external-process-%exit-code proc)
866 (external-process-%status proc))))))
867 #+clozure (in-package :uiop/common-lisp) ;; back in this package.
868
869 #+cmucl
870 (eval-when (:load-toplevel :compile-toplevel :execute)
871 (setf ext:*gc-verbose* nil)
872 (defun user-homedir-pathname ()
873 (first (ext:search-list (cl:user-homedir-pathname)))))
874
875 #+cormanlisp
876 (eval-when (:load-toplevel :compile-toplevel :execute)
877 (deftype logical-pathname () nil)
878 (defun make-broadcast-stream () *error-output*)
879 (defun translate-logical-pathname (x) x)
880 (defun user-homedir-pathname (&optional host)
881 (declare (ignore host))
882 (parse-namestring (format nil "~A\\" (cl:user-homedir-pathname))))
883 (defun file-namestring (p)
884 (setf p (pathname p))
885 (format nil "~@[~A~]~@[.~A~]" (pathname-name p) (pathname-type p))))
886
887 #+(and ecl (not clasp))
888 (eval-when (:load-toplevel :compile-toplevel :execute)
889 (setf *load-verbose* nil)
890 (defun use-ecl-byte-compiler-p () (and (member :ecl-bytecmp *features*) t))
891 (unless (use-ecl-byte-compiler-p) (require :cmp)))
892
893 #+gcl
894 (eval-when (:load-toplevel :compile-toplevel :execute)
895 (unless (member :ansi-cl *features*)
896 (error "ASDF only supports GCL in ANSI mode. Aborting.~%"))
897 (setf compiler::*compiler-default-type* (pathname "")
898 compiler::*lsp-ext* "")
899 #.(let ((code ;; Only support very recent GCL 2.7.0 from November 2013 or later.
900 (cond
901 #+gcl
902 ((or (< system::*gcl-major-version* 2)
903 (and (= system::*gcl-major-version* 2)
904 (< system::*gcl-minor-version* 7)))
905 '(error "GCL 2.7 or later required to use ASDF")))))
906 (eval code)
907 code))
908
909 #+genera
910 (eval-when (:load-toplevel :compile-toplevel :execute)
911 (unless (fboundp 'lambda)
912 (defmacro lambda (&whole form &rest bvl-decls-and-body)
913 (declare (ignore bvl-decls-and-body)(zwei::indentation 1 1))
914 `#',(cons 'lisp::lambda (cdr form))))
915 (unless (fboundp 'ensure-directories-exist)
916 (defun ensure-directories-exist (path)
917 (fs:create-directories-recursively (pathname path))))
918 (unless (fboundp 'read-sequence)
919 (defun read-sequence (sequence stream &key (start 0) end)
920 (scl:send stream :string-in nil sequence start end)))
921 (unless (fboundp 'write-sequence)
922 (defun write-sequence (sequence stream &key (start 0) end)
923 (scl:send stream :string-out sequence start end)
924 sequence)))
925
926 #+lispworks
927 (eval-when (:load-toplevel :compile-toplevel :execute)
928 ;; lispworks 3 and earlier cannot be checked for so we always assume
929 ;; at least version 4
930 (unless (member :lispworks4 *features*)
931 (pushnew :lispworks5+ *features*)
932 (unless (member :lispworks5 *features*)
933 (pushnew :lispworks6+ *features*)
934 (unless (member :lispworks6 *features*)
935 (pushnew :lispworks7+ *features*)))))
936
937 #.(or #+mcl ;; the #$ doesn't work on other lisps, even protected by #+mcl, so we use this trick
938 (read-from-string
939 "(eval-when (:load-toplevel :compile-toplevel :execute)
940 (ccl:define-entry-point (_getenv \"getenv\") ((name :string)) :string)
941 (ccl:define-entry-point (_system \"system\") ((name :string)) :int)
942 ;; Note: ASDF may expect user-homedir-pathname to provide
943 ;; the pathname of the current user's home directory, whereas
944 ;; MCL by default provides the directory from which MCL was started.
945 ;; See http://code.google.com/p/mcl/wiki/Portability
946 (defun user-homedir-pathname ()
947 (ccl::findfolder #$kuserdomain #$kCurrentUserFolderType))
948 (defun probe-posix (posix-namestring)
949 \"If a file exists for the posix namestring, return the pathname\"
950 (ccl::with-cstrs ((cpath posix-namestring))
951 (ccl::rlet ((is-dir :boolean)
952 (fsref :fsref))
953 (when (eq #$noerr (#_fspathmakeref cpath fsref is-dir))
954 (ccl::%path-from-fsref fsref is-dir))))))"))
955
956 #+mkcl
957 (eval-when (:load-toplevel :compile-toplevel :execute)
958 (require :cmp)
959 (setq clos::*redefine-class-in-place* t)) ;; Make sure we have strict ANSI class redefinition semantics
960
961
962 ;;;; Looping
963 (eval-when (:load-toplevel :compile-toplevel :execute)
964 (defmacro loop* (&rest rest)
965 #-genera `(loop ,@rest)
966 #+genera `(lisp:loop ,@rest))) ;; In genera, CL:LOOP can't destructure, so we use LOOP*. Sigh.
967
968
969 ;;;; compatfmt: avoid fancy format directives when unsupported
970 (eval-when (:load-toplevel :compile-toplevel :execute)
971 (defun frob-substrings (string substrings &optional frob)
972 "for each substring in SUBSTRINGS, find occurrences of it within STRING
973 that don't use parts of matched occurrences of previous strings, and
974 FROB them, that is to say, remove them if FROB is NIL,
975 replace by FROB if FROB is a STRING, or if FROB is a FUNCTION,
976 call FROB with the match and a function that emits a string in the output.
977 Return a string made of the parts not omitted or emitted by FROB."
978 (declare (optimize (speed 0) (safety #-gcl 3 #+gcl 0) (debug 3)))
979 (let ((length (length string)) (stream nil))
980 (labels ((emit-string (x &optional (start 0) (end (length x)))
981 (when (< start end)
982 (unless stream (setf stream (make-string-output-stream)))
983 (write-string x stream :start start :end end)))
984 (emit-substring (start end)
985 (when (and (zerop start) (= end length))
986 (return-from frob-substrings string))
987 (emit-string string start end))
988 (recurse (substrings start end)
989 (cond
990 ((>= start end))
991 ((null substrings) (emit-substring start end))
992 (t (let* ((sub-spec (first substrings))
993 (sub (if (consp sub-spec) (car sub-spec) sub-spec))
994 (fun (if (consp sub-spec) (cdr sub-spec) frob))
995 (found (search sub string :start2 start :end2 end))
996 (more (rest substrings)))
997 (cond
998 (found
999 (recurse more start found)
1000 (etypecase fun
1001 (null)
1002 (string (emit-string fun))
1003 (function (funcall fun sub #'emit-string)))
1004 (recurse substrings (+ found (length sub)) end))
1005 (t
1006 (recurse more start end))))))))
1007 (recurse substrings 0 length))
1008 (if stream (get-output-stream-string stream) "")))
1009
1010 (defmacro compatfmt (format)
1011 #+(or gcl genera)
1012 (frob-substrings format `("~3i~_" #+genera ,@'("~@<" "~@;" "~@:>" "~:>")))
1013 #-(or gcl genera) format))
1014 ;;;; -------------------------------------------------------------------------
1015 ;;;; General Purpose Utilities for ASDF
1016
1017 (uiop/package:define-package :uiop/utility
1018 (:nicknames :asdf/utility)
1019 (:recycle :uiop/utility :asdf/utility :asdf)
1020 (:use :uiop/common-lisp :uiop/package)
1021 ;; import and reexport a few things defined in :uiop/common-lisp
1022 (:import-from :uiop/common-lisp #:compatfmt #:loop* #:frob-substrings
1023 #+(or clasp ecl) #:use-ecl-byte-compiler-p #+mcl #:probe-posix)
1024 (:export #:compatfmt #:loop* #:frob-substrings #:compatfmt
1025 #+(or clasp ecl) #:use-ecl-byte-compiler-p #+mcl #:probe-posix)
1026 (:export
1027 ;; magic helper to define debugging functions:
1028 #:uiop-debug #:load-uiop-debug-utility #:*uiop-debug-utility*
1029 #:with-upgradability ;; (un)defining functions in an upgrade-friendly way
1030 #:undefine-function #:undefine-functions #:defun* #:defgeneric*
1031 #:nest #:if-let ;; basic flow control
1032 #:while-collecting #:appendf #:length=n-p #:ensure-list ;; lists
1033 #:remove-plist-keys #:remove-plist-key ;; plists
1034 #:emptyp ;; sequences
1035 #:+non-base-chars-exist-p+ ;; characters
1036 #:+max-character-type-index+ #:character-type-index #:+character-types+
1037 #:base-string-p #:strings-common-element-type #:reduce/strcat #:strcat ;; strings
1038 #:first-char #:last-char #:split-string #:stripln #:+cr+ #:+lf+ #:+crlf+
1039 #:string-prefix-p #:string-enclosed-p #:string-suffix-p
1040 #:standard-case-symbol-name #:find-standard-case-symbol
1041 #:coerce-class ;; CLOS
1042 #:stamp< #:stamps< #:stamp*< #:stamp<= ;; stamps
1043 #:earlier-stamp #:stamps-earliest #:earliest-stamp
1044 #:later-stamp #:stamps-latest #:latest-stamp #:latest-stamp-f
1045 #:list-to-hash-set #:ensure-gethash ;; hash-table
1046 #:ensure-function #:access-at #:access-at-count ;; functions
1047 #:call-function #:call-functions #:register-hook-function
1048 #:lexicographic< #:lexicographic<= ;; version
1049 #:parse-version #:unparse-version #:version< #:version<= #:version-compatible-p
1050 #:match-condition-p #:match-any-condition-p ;; conditions
1051 #:call-with-muffled-conditions #:with-muffled-conditions
1052 #:not-implemented-error #:parameter-error))
1053 (in-package :uiop/utility)
1054
1055 ;;;; Defining functions in a way compatible with hot-upgrade:
1056 ;; DEFUN* and DEFGENERIC* use FMAKUNBOUND to delete any previous fdefinition,
1057 ;; thus replacing the function without warning or error
1058 ;; even if the signature and/or generic-ness of the function has changed.
1059 ;; For a generic function, this invalidates any previous DEFMETHOD.
1060 (eval-when (:load-toplevel :compile-toplevel :execute)
1061 (defun undefine-function (function-spec)
1062 (cond
1063 ((symbolp function-spec)
1064 ;; undefining the previous function is the portable way
1065 ;; of overriding any incompatible previous gf,
1066 ;; but CLISP needs extra help with getting rid of previous methods.
1067 #+clisp
1068 (let ((f (and (fboundp function-spec) (fdefinition function-spec))))
1069 (when (typep f 'clos:standard-generic-function)
1070 (loop :for m :in (clos:generic-function-methods f)
1071 :do (remove-method f m))))
1072 (fmakunbound function-spec))
1073 ((and (consp function-spec) (eq (car function-spec) 'setf)
1074 (consp (cdr function-spec)) (null (cddr function-spec)))
1075 (fmakunbound function-spec))
1076 (t (error "bad function spec ~S" function-spec))))
1077 (defun undefine-functions (function-spec-list)
1078 (map () 'undefine-function function-spec-list))
1079 (macrolet
1080 ((defdef (def* def)
1081 `(defmacro ,def* (name formals &rest rest)
1082 (destructuring-bind (name &key (supersede t))
1083 (if (or (atom name) (eq (car name) 'setf))
1084 (list name :supersede nil)
1085 name)
1086 (declare (ignorable supersede))
1087 `(progn
1088 ;; We usually try to do it only for the functions that need it,
1089 ;; which happens in asdf/upgrade - however, for ECL, we need this hammer.
1090 ,@(when (or supersede #+(or clasp ecl) t)
1091 `((undefine-function ',name)))
1092 ,@(when (and #+(or clasp ecl) (symbolp name)) ; fails for setf functions on ecl
1093 `((declaim (notinline ,name))))
1094 (,',def ,name ,formals ,@rest))))))
1095 (defdef defgeneric* defgeneric)
1096 (defdef defun* defun))
1097 (defmacro with-upgradability ((&optional) &body body)
1098 "Evaluate BODY at compile- load- and run- times, with DEFUN and DEFGENERIC modified
1099 to also declare the functions NOTINLINE and to accept a wrapping the function name
1100 specification into a list with keyword argument SUPERSEDE (which defaults to T if the name
1101 is not wrapped, and NIL if it is wrapped). If SUPERSEDE is true, call UNDEFINE-FUNCTION
1102 to supersede any previous definition."
1103 `(eval-when (:compile-toplevel :load-toplevel :execute)
1104 ,@(loop :for form :in body :collect
1105 (if (consp form)
1106 (destructuring-bind (car . cdr) form
1107 (case car
1108 ((defun) `(defun* ,@cdr))
1109 ((defgeneric) `(defgeneric* ,@cdr))
1110 (otherwise form)))
1111 form)))))
1112
1113 ;;; Magic debugging help. See contrib/debug.lisp
1114 (with-upgradability ()
1115 (defvar *uiop-debug-utility*
1116 '(or (ignore-errors
1117 (symbol-call :asdf :system-relative-pathname :uiop "contrib/debug.lisp"))
1118 (symbol-call :uiop/pathname :subpathname (user-homedir-pathname) "cl/asdf/uiop/contrib/debug.lisp"))
1119 "form that evaluates to the pathname to your favorite debugging utilities")
1120
1121 (defmacro uiop-debug (&rest keys)
1122 `(eval-when (:compile-toplevel :load-toplevel :execute)
1123 (load-uiop-debug-utility ,@keys)))
1124
1125 (defun load-uiop-debug-utility (&key package utility-file)
1126 (let* ((*package* (if package (find-package package) *package*))
1127 (keyword (read-from-string
1128 (format nil ":DBG-~:@(~A~)" (package-name *package*)))))
1129 (unless (member keyword *features*)
1130 (let* ((utility-file (or utility-file *uiop-debug-utility*))
1131 (file (ignore-errors (probe-file (eval utility-file)))))
1132 (if file (load file)
1133 (error "Failed to locate debug utility file: ~S" utility-file)))))))
1134
1135 ;;; Flow control
1136 (with-upgradability ()
1137 (defmacro nest (&rest things)
1138 "Macro to do keep code nesting and indentation under control." ;; Thanks to mbaringer
1139 (reduce #'(lambda (outer inner) `(,@outer ,inner))
1140 things :from-end t))
1141
1142 (defmacro if-let (bindings &body (then-form &optional else-form)) ;; from alexandria
1143 ;; bindings can be (var form) or ((var1 form1) ...)
1144 (let* ((binding-list (if (and (consp bindings) (symbolp (car bindings)))
1145 (list bindings)
1146 bindings))
1147 (variables (mapcar #'car binding-list)))
1148 `(let ,binding-list
1149 (if (and ,@variables)
1150 ,then-form
1151 ,else-form)))))
1152
1153 ;;; List manipulation
1154 (with-upgradability ()
1155 (defmacro while-collecting ((&rest collectors) &body body)
1156 "COLLECTORS should be a list of names for collections. A collector
1157 defines a function that, when applied to an argument inside BODY, will
1158 add its argument to the corresponding collection. Returns multiple values,
1159 a list for each collection, in order.
1160 E.g.,
1161 \(while-collecting \(foo bar\)
1162 \(dolist \(x '\(\(a 1\) \(b 2\) \(c 3\)\)\)
1163 \(foo \(first x\)\)
1164 \(bar \(second x\)\)\)\)
1165 Returns two values: \(A B C\) and \(1 2 3\)."
1166 (let ((vars (mapcar #'(lambda (x) (gensym (symbol-name x))) collectors))
1167 (initial-values (mapcar (constantly nil) collectors)))
1168 `(let ,(mapcar #'list vars initial-values)
1169 (flet ,(mapcar #'(lambda (c v) `(,c (x) (push x ,v) (values))) collectors vars)
1170 ,@body
1171 (values ,@(mapcar #'(lambda (v) `(reverse ,v)) vars))))))
1172
1173 (define-modify-macro appendf (&rest args)
1174 append "Append onto list") ;; only to be used on short lists.
1175
1176 (defun length=n-p (x n) ;is it that (= (length x) n) ?
1177 (check-type n (integer 0 *))
1178 (loop
1179 :for l = x :then (cdr l)
1180 :for i :downfrom n :do
1181 (cond
1182 ((zerop i) (return (null l)))
1183 ((not (consp l)) (return nil)))))
1184
1185 (defun ensure-list (x)
1186 (if (listp x) x (list x))))
1187
1188
1189 ;;; remove a key from a plist, i.e. for keyword argument cleanup
1190 (with-upgradability ()
1191 (defun remove-plist-key (key plist)
1192 "Remove a single key from a plist"
1193 (loop* :for (k v) :on plist :by #'cddr
1194 :unless (eq k key)
1195 :append (list k v)))
1196
1197 (defun remove-plist-keys (keys plist)
1198 "Remove a list of keys from a plist"
1199 (loop* :for (k v) :on plist :by #'cddr
1200 :unless (member k keys)
1201 :append (list k v))))
1202
1203
1204 ;;; Sequences
1205 (with-upgradability ()
1206 (defun emptyp (x)
1207 "Predicate that is true for an empty sequence"
1208 (or (null x) (and (vectorp x) (zerop (length x))))))
1209
1210
1211 ;;; Characters
1212 (with-upgradability ()
1213 ;; base-char != character on ECL, LW, SBCL, Genera.
1214 ;; NB: We assume a total order on character types.
1215 ;; If that's not true... this code will need to be updated.
1216 (defparameter +character-types+ ;; assuming a simple hierarchy
1217 #.(coerce (loop* :for (type next) :on
1218 '(;; In SCL, all characters seem to be 16-bit base-char
1219 ;; Yet somehow character fails to be a subtype of base-char
1220 #-scl base-char
1221 ;; LW6 has BASE-CHAR < SIMPLE-CHAR < CHARACTER
1222 ;; LW7 has BASE-CHAR < BMP-CHAR < SIMPLE-CHAR = CHARACTER
1223 #+lispworks7+ lw:bmp-char
1224 #+lispworks lw:simple-char
1225 character)
1226 :unless (and next (subtypep next type))
1227 :collect type) 'vector))
1228 (defparameter +max-character-type-index+ (1- (length +character-types+)))
1229 (defconstant +non-base-chars-exist-p+ (plusp +max-character-type-index+))
1230 (when +non-base-chars-exist-p+ (pushnew :non-base-chars-exist-p *features*)))
1231
1232 (with-upgradability ()
1233 (defun character-type-index (x)
1234 (declare (ignorable x))
1235 #.(case +max-character-type-index+
1236 (0 0)
1237 (1 '(etypecase x
1238 (character (if (typep x 'base-char) 0 1))
1239 (symbol (if (subtypep x 'base-char) 0 1))))
1240 (otherwise
1241 '(or (position-if (etypecase x
1242 (character #'(lambda (type) (typep x type)))
1243 (symbol #'(lambda (type) (subtypep x type))))
1244 +character-types+)
1245 (error "Not a character or character type: ~S" x))))))
1246
1247
1248 ;;; Strings
1249 (with-upgradability ()
1250 (defun base-string-p (string)
1251 "Does the STRING only contain BASE-CHARs?"
1252 (declare (ignorable string))
1253 (and #+non-base-chars-exist-p (eq 'base-char (array-element-type string))))
1254
1255 (defun strings-common-element-type (strings)
1256 "What least subtype of CHARACTER can contain all the elements of all the STRINGS?"
1257 (declare (ignorable strings))
1258 #.(if +non-base-chars-exist-p+
1259 `(aref +character-types+
1260 (loop :with index = 0 :for s :in strings :do
1261 (flet ((consider (i)
1262 (cond ((= i ,+max-character-type-index+) (return i))
1263 ,@(when (> +max-character-type-index+ 1) `(((> i index) (setf index i)))))))
1264 (cond
1265 ((emptyp s)) ;; NIL or empty string
1266 ((characterp s) (consider (character-type-index s)))
1267 ((stringp s) (let ((string-type-index
1268 (character-type-index (array-element-type s))))
1269 (unless (>= index string-type-index)
1270 (loop :for c :across s :for i = (character-type-index c)
1271 :do (consider i)
1272 ,@(when (> +max-character-type-index+ 1)
1273 `((when (= i string-type-index) (return))))))))
1274 (t (error "Invalid string designator ~S for ~S" s 'strings-common-element-type))))
1275 :finally (return index)))
1276 ''character))
1277
1278 (defun reduce/strcat (strings &key key start end)
1279 "Reduce a list as if by STRCAT, accepting KEY START and END keywords like REDUCE.
1280 NIL is interpreted as an empty string. A character is interpreted as a string of length one."
1281 (when (or start end) (setf strings (subseq strings start end)))
1282 (when key (setf strings (mapcar key strings)))
1283 (loop :with output = (make-string (loop :for s :in strings
1284 :sum (if (characterp s) 1 (length s)))
1285 :element-type (strings-common-element-type strings))
1286 :with pos = 0
1287 :for input :in strings
1288 :do (etypecase input
1289 (null)
1290 (character (setf (char output pos) input) (incf pos))
1291 (string (replace output input :start1 pos) (incf pos (length input))))
1292 :finally (return output)))
1293
1294 (defun strcat (&rest strings)
1295 "Concatenate strings.
1296 NIL is interpreted as an empty string, a character as a string of length one."
1297 (reduce/strcat strings))
1298
1299 (defun first-char (s)
1300 "Return the first character of a non-empty string S, or NIL"
1301 (and (stringp s) (plusp (length s)) (char s 0)))
1302
1303 (defun last-char (s)
1304 "Return the last character of a non-empty string S, or NIL"
1305 (and (stringp s) (plusp (length s)) (char s (1- (length s)))))
1306
1307 (defun split-string (string &key max (separator '(#\Space #\Tab)))
1308 "Split STRING into a list of components separated by
1309 any of the characters in the sequence SEPARATOR.
1310 If MAX is specified, then no more than max(1,MAX) components will be returned,
1311 starting the separation from the end, e.g. when called with arguments
1312 \"a.b.c.d.e\" :max 3 :separator \".\" it will return (\"a.b.c\" \"d\" \"e\")."
1313 (block ()
1314 (let ((list nil) (words 0) (end (length string)))
1315 (when (zerop end) (return nil))
1316 (flet ((separatorp (char) (find char separator))
1317 (done () (return (cons (subseq string 0 end) list))))
1318 (loop
1319 :for start = (if (and max (>= words (1- max)))
1320 (done)
1321 (position-if #'separatorp string :end end :from-end t))
1322 :do (when (null start) (done))
1323 (push (subseq string (1+ start) end) list)
1324 (incf words)
1325 (setf end start))))))
1326
1327 (defun string-prefix-p (prefix string)
1328 "Does STRING begin with PREFIX?"
1329 (let* ((x (string prefix))
1330 (y (string string))
1331 (lx (length x))
1332 (ly (length y)))
1333 (and (<= lx ly) (string= x y :end2 lx))))
1334
1335 (defun string-suffix-p (string suffix)
1336 "Does STRING end with SUFFIX?"
1337 (let* ((x (string string))
1338 (y (string suffix))
1339 (lx (length x))
1340 (ly (length y)))
1341 (and (<= ly lx) (string= x y :start1 (- lx ly)))))
1342
1343 (defun string-enclosed-p (prefix string suffix)
1344 "Does STRING begin with PREFIX and end with SUFFIX?"
1345 (and (string-prefix-p prefix string)
1346 (string-suffix-p string suffix)))
1347
1348 (defvar +cr+ (coerce #(#\Return) 'string))
1349 (defvar +lf+ (coerce #(#\Linefeed) 'string))
1350 (defvar +crlf+ (coerce #(#\Return #\Linefeed) 'string))
1351
1352 (defun stripln (x)
1353 "Strip a string X from any ending CR, LF or CRLF.
1354 Return two values, the stripped string and the ending that was stripped,
1355 or the original value and NIL if no stripping took place.
1356 Since our STRCAT accepts NIL as empty string designator,
1357 the two results passed to STRCAT always reconstitute the original string"
1358 (check-type x string)
1359 (block nil
1360 (flet ((c (end) (when (string-suffix-p x end)
1361 (return (values (subseq x 0 (- (length x) (length end))) end)))))
1362 (when x (c +crlf+) (c +lf+) (c +cr+) (values x nil)))))
1363
1364 (defun standard-case-symbol-name (name-designator)
1365 "Given a NAME-DESIGNATOR for a symbol, if it is a symbol, convert it to a string using STRING;
1366 if it is a string, use STRING-UPCASE on an ANSI CL platform, or STRING on a so-called \"modern\"
1367 platform such as Allegro with modern syntax."
1368 (check-type name-designator (or string symbol))
1369 (cond
1370 ((or (symbolp name-designator) #+allegro (eq excl:*current-case-mode* :case-sensitive-lower))
1371 (string name-designator))
1372 ;; Should we be doing something on CLISP?
1373 (t (string-upcase name-designator))))
1374
1375 (defun find-standard-case-symbol (name-designator package-designator &optional (error t))
1376 "Find a symbol designated by NAME-DESIGNATOR in a package designated by PACKAGE-DESIGNATOR,
1377 where STANDARD-CASE-SYMBOL-NAME is used to transform them if these designators are strings.
1378 If optional ERROR argument is NIL, return NIL instead of an error when the symbol is not found."
1379 (find-symbol* (standard-case-symbol-name name-designator)
1380 (etypecase package-designator
1381 ((or package symbol) package-designator)
1382 (string (standard-case-symbol-name package-designator)))
1383 error)))
1384
1385 ;;; stamps: a REAL or a boolean where NIL=-infinity, T=+infinity
1386 (eval-when (#-lispworks :compile-toplevel :load-toplevel :execute)
1387 (deftype stamp () '(or real boolean)))
1388 (with-upgradability ()
1389 (defun stamp< (x y)
1390 (etypecase x
1391 (null (and y t))
1392 ((eql t) nil)
1393 (real (etypecase y
1394 (null nil)
1395 ((eql t) t)
1396 (real (< x y))))))
1397 (defun stamps< (list) (loop :for y :in list :for x = nil :then y :always (stamp< x y)))
1398 (defun stamp*< (&rest list) (stamps< list))
1399 (defun stamp<= (x y) (not (stamp< y x)))
1400 (defun earlier-stamp (x y) (if (stamp< x y) x y))
1401 (defun stamps-earliest (list) (reduce 'earlier-stamp list :initial-value t))
1402 (defun earliest-stamp (&rest list) (stamps-earliest list))
1403 (defun later-stamp (x y) (if (stamp< x y) y x))
1404 (defun stamps-latest (list) (reduce 'later-stamp list :initial-value nil))
1405 (defun latest-stamp (&rest list) (stamps-latest list))
1406 (define-modify-macro latest-stamp-f (&rest stamps) latest-stamp))
1407
1408
1409 ;;; Function designators
1410 (with-upgradability ()
1411 (defun ensure-function (fun &key (package :cl))
1412 "Coerce the object FUN into a function.
1413
1414 If FUN is a FUNCTION, return it.
1415 If the FUN is a non-sequence literal constant, return constantly that,
1416 i.e. for a boolean keyword character number or pathname.
1417 Otherwise if FUN is a non-literally constant symbol, return its FDEFINITION.
1418 If FUN is a CONS, return the function that applies its CAR
1419 to the appended list of the rest of its CDR and the arguments,
1420 unless the CAR is LAMBDA, in which case the expression is evaluated.
1421 If FUN is a string, READ a form from it in the specified PACKAGE (default: CL)
1422 and EVAL that in a (FUNCTION ...) context."
1423 (etypecase fun
1424 (function fun)
1425 ((or boolean keyword character number pathname) (constantly fun))
1426 (hash-table #'(lambda (x) (gethash x fun)))
1427 (symbol (fdefinition fun))
1428 (cons (if (eq 'lambda (car fun))
1429 (eval fun)
1430 #'(lambda (&rest args) (apply (car fun) (append (cdr fun) args)))))
1431 (string (eval `(function ,(with-standard-io-syntax
1432 (let ((*package* (find-package package)))
1433 (read-from-string fun))))))))
1434
1435 (defun access-at (object at)
1436 "Given an OBJECT and an AT specifier, list of successive accessors,
1437 call each accessor on the result of the previous calls.
1438 An accessor may be an integer, meaning a call to ELT,
1439 a keyword, meaning a call to GETF,
1440 NIL, meaning identity,
1441 a function or other symbol, meaning itself,
1442 or a list of a function designator and arguments, interpreted as per ENSURE-FUNCTION.
1443 As a degenerate case, the AT specifier may be an atom of a single such accessor
1444 instead of a list."
1445 (flet ((access (object accessor)
1446 (etypecase accessor
1447 (function (funcall accessor object))
1448 (integer (elt object accessor))
1449 (keyword (getf object accessor))
1450 (null object)
1451 (symbol (funcall accessor object))
1452 (cons (funcall (ensure-function accessor) object)))))
1453 (if (listp at)
1454 (dolist (accessor at object)
1455 (setf object (access object accessor)))
1456 (access object at))))
1457
1458 (defun access-at-count (at)
1459 "From an AT specification, extract a COUNT of maximum number
1460 of sub-objects to read as per ACCESS-AT"
1461 (cond
1462 ((integerp at)
1463 (1+ at))
1464 ((and (consp at) (integerp (first at)))
1465 (1+ (first at)))))
1466
1467 (defun call-function (function-spec &rest arguments)
1468 "Call the function designated by FUNCTION-SPEC as per ENSURE-FUNCTION,
1469 with the given ARGUMENTS"
1470 (apply (ensure-function function-spec) arguments))
1471
1472 (defun call-functions (function-specs)
1473 "For each function in the list FUNCTION-SPECS, in order, call the function as per CALL-FUNCTION"
1474 (map () 'call-function function-specs))
1475
1476 (defun register-hook-function (variable hook &optional call-now-p)
1477 "Push the HOOK function (a designator as per ENSURE-FUNCTION) onto the hook VARIABLE.
1478 When CALL-NOW-P is true, also call the function immediately."
1479 (pushnew hook (symbol-value variable) :test 'equal)
1480 (when call-now-p (call-function hook))))
1481
1482
1483 ;;; CLOS
1484 (with-upgradability ()
1485 (defun coerce-class (class &key (package :cl) (super t) (error 'error))
1486 "Coerce CLASS to a class that is subclass of SUPER if specified,
1487 or invoke ERROR handler as per CALL-FUNCTION.
1488
1489 A keyword designates the name a symbol, which when found in either PACKAGE, designates a class.
1490 -- for backward compatibility, *PACKAGE* is also accepted for now, but this may go in the future.
1491 A string is read as a symbol while in PACKAGE, the symbol designates a class.
1492
1493 A class object designates itself.
1494 NIL designates itself (no class).
1495 A symbol otherwise designates a class by name."
1496 (let* ((normalized
1497 (typecase class
1498 (keyword (or (find-symbol* class package nil)
1499 (find-symbol* class *package* nil)))
1500 (string (symbol-call :uiop :safe-read-from-string class :package package))
1501 (t class)))
1502 (found
1503 (etypecase normalized
1504 ((or standard-class built-in-class) normalized)
1505 ((or null keyword) nil)
1506 (symbol (find-class normalized nil nil)))))
1507 (or (and found
1508 (or (eq super t) (#-cormanlisp subtypep #+cormanlisp cl::subclassp found super))
1509 found)
1510 (call-function error "Can't coerce ~S to a ~:[class~;subclass of ~:*~S~]" class super)))))
1511
1512
1513 ;;; Hash-tables
1514 (with-upgradability ()
1515 (defun ensure-gethash (key table default)
1516 "Lookup the TABLE for a KEY as by GETHASH, but if not present,
1517 call the (possibly constant) function designated by DEFAULT as per CALL-FUNCTION,
1518 set the corresponding entry to the result in the table.
1519 Return two values: the entry after its optional computation, and whether it was found"
1520 (multiple-value-bind (value foundp) (gethash key table)
1521 (values
1522 (if foundp
1523 value
1524 (setf (gethash key table) (call-function default)))
1525 foundp)))
1526
1527 (defun list-to-hash-set (list &aux (h (make-hash-table :test 'equal)))
1528 "Convert a LIST into hash-table that has the same elements when viewed as a set,
1529 up to the given equality TEST"
1530 (dolist (x list h) (setf (gethash x h) t))))
1531
1532
1533 ;;; Version handling
1534 (with-upgradability ()
1535 (defun unparse-version (version-list)
1536 "From a parsed version (a list of natural numbers), compute the version string"
1537 (format nil "~{~D~^.~}" version-list))
1538
1539 (defun parse-version (version-string &optional on-error)
1540 "Parse a VERSION-STRING as a series of natural numbers separated by dots.
1541 Return a (non-null) list of integers if the string is valid;
1542 otherwise return NIL.
1543
1544 When invalid, ON-ERROR is called as per CALL-FUNCTION before to return NIL,
1545 with format arguments explaining why the version is invalid.
1546 ON-ERROR is also called if the version is not canonical
1547 in that it doesn't print back to itself, but the list is returned anyway."
1548 (block nil
1549 (unless (stringp version-string)
1550 (call-function on-error "~S: ~S is not a string" 'parse-version version-string)
1551 (return))
1552 (unless (loop :for prev = nil :then c :for c :across version-string
1553 :always (or (digit-char-p c)
1554 (and (eql c #\.) prev (not (eql prev #\.))))
1555 :finally (return (and c (digit-char-p c))))
1556 (call-function on-error "~S: ~S doesn't follow asdf version numbering convention"
1557 'parse-version version-string)
1558 (return))
1559 (let* ((version-list
1560 (mapcar #'parse-integer (split-string version-string :separator ".")))
1561 (normalized-version (unparse-version version-list)))
1562 (unless (equal version-string normalized-version)
1563 (call-function on-error "~S: ~S contains leading zeros" 'parse-version version-string))
1564 version-list)))
1565
1566 (defun lexicographic< (element< x y)
1567 "Lexicographically compare two lists of using the function element< to compare elements.
1568 element< is a strict total order; the resulting order on X and Y will also be strict."
1569 (cond ((null y) nil)
1570 ((null x) t)
1571 ((funcall element< (car x) (car y)) t)
1572 ((funcall element< (car y) (car x)) nil)
1573 (t (lexicographic< element< (cdr x) (cdr y)))))
1574
1575 (defun lexicographic<= (element< x y)
1576 "Lexicographically compare two lists of using the function element< to compare elements.
1577 element< is a strict total order; the resulting order on X and Y will be a non-strict total order."
1578 (not (lexicographic< element< y x)))
1579
1580 (defun version< (version1 version2)
1581 "Compare two version strings"
1582 (let ((v1 (parse-version version1 nil))
1583 (v2 (parse-version version2 nil)))
1584 (lexicographic< '< v1 v2)))
1585
1586 (defun version<= (version1 version2)
1587 "Compare two version strings"
1588 (not (version< version2 version1)))
1589
1590 (defun version-compatible-p (provided-version required-version)
1591 "Is the provided version a compatible substitution for the required-version?
1592 If major versions differ, it's not compatible.
1593 If they are equal, then any later version is compatible,
1594 with later being determined by a lexicographical comparison of minor numbers."
1595 (let ((x (parse-version provided-version nil))
1596 (y (parse-version required-version nil)))
1597 (and x y (= (car x) (car y)) (lexicographic<= '< (cdr y) (cdr x))))))
1598
1599
1600 ;;; Condition control
1601
1602 (with-upgradability ()
1603 (defparameter +simple-condition-format-control-slot+
1604 #+abcl 'system::format-control
1605 #+allegro 'excl::format-control
1606 #+(or clasp ecl mkcl) 'si::format-control
1607 #+clisp 'system::$format-control
1608 #+clozure 'ccl::format-control
1609 #+(or cmucl scl) 'conditions::format-control
1610 #+(or gcl lispworks) 'conditions::format-string
1611 #+sbcl 'sb-kernel:format-control
1612 #-(or abcl allegro clasp clisp clozure cmucl ecl gcl lispworks mkcl sbcl scl) nil
1613 "Name of the slot for FORMAT-CONTROL in simple-condition")
1614
1615 (defun match-condition-p (x condition)
1616 "Compare received CONDITION to some pattern X:
1617 a symbol naming a condition class,
1618 a simple vector of length 2, arguments to find-symbol* with result as above,
1619 or a string describing the format-control of a simple-condition."
1620 (etypecase x
1621 (symbol (typep condition x))
1622 ((simple-vector 2)
1623 (ignore-errors (typep condition (find-symbol* (svref x 0) (svref x 1) nil))))
1624 (function (funcall x condition))
1625 (string (and (typep condition 'simple-condition)
1626 ;; On SBCL, it's always set and the check triggers a warning
1627 #+(or allegro clozure cmucl lispworks scl)
1628 (slot-boundp condition +simple-condition-format-control-slot+)
1629 (ignore-errors (equal (simple-condition-format-control condition) x))))))
1630
1631 (defun match-any-condition-p (condition conditions)
1632 "match CONDITION against any of the patterns of CONDITIONS supplied"
1633 (loop :for x :in conditions :thereis (match-condition-p x condition)))
1634
1635 (defun call-with-muffled-conditions (thunk conditions)
1636 "calls the THUNK in a context where the CONDITIONS are muffled"
1637 (handler-bind ((t #'(lambda (c) (when (match-any-condition-p c conditions)
1638 (muffle-warning c)))))
1639 (funcall thunk)))
1640
1641 (defmacro with-muffled-conditions ((conditions) &body body)
1642 "Shorthand syntax for CALL-WITH-MUFFLED-CONDITIONS"
1643 `(call-with-muffled-conditions #'(lambda () ,@body) ,conditions)))
1644
1645 ;;; Conditions
1646
1647 (with-upgradability ()
1648 (define-condition not-implemented-error (error)
1649 ((functionality :initarg :functionality)
1650 (format-control :initarg :format-control)
1651 (format-arguments :initarg :format-arguments))
1652 (:report (lambda (condition stream)
1653 (format stream "Not implemented: ~s~@[ ~?~]"
1654 (slot-value condition 'functionality)
1655 (slot-value condition 'format-control)
1656 (slot-value condition 'format-arguments)))))
1657
1658 (defun not-implemented-error (functionality &optional format-control &rest format-arguments)
1659 "Signal an error because some FUNCTIONALITY is not implemented in the current version
1660 of the software on the current platform; it may or may not be implemented in different combinations
1661 of version of the software and of the underlying platform. Optionally, report a formatted error
1662 message."
1663 (error 'not-implemented-error
1664 :functionality functionality
1665 :format-control format-control
1666 :format-arguments format-arguments))
1667
1668 (define-condition parameter-error (error)
1669 ((functionality :initarg :functionality)
1670 (format-control :initarg :format-control)
1671 (format-arguments :initarg :format-arguments))
1672 (:report (lambda (condition stream)
1673 (apply 'format stream
1674 (slot-value condition 'format-control)
1675 (slot-value condition 'functionality)
1676 (slot-value condition 'format-arguments)))))
1677
1678 ;; Note that functionality MUST be passed as the second argument to parameter-error, just after
1679 ;; the format-control. If you want it to not appear in first position in actual message, use
1680 ;; ~* and ~:* to adjust parameter order.
1681 (defun parameter-error (format-control functionality &rest format-arguments)
1682 "Signal an error because some FUNCTIONALITY or its specific implementation on a given underlying
1683 platform does not accept a given parameter or combination of parameters. Report a formatted error
1684 message, that takes the functionality as its first argument (that can be skipped with ~*)."
1685 (error 'parameter-error
1686 :functionality functionality
1687 :format-control format-control
1688 :format-arguments format-arguments)))
1689
1690 ;;;; ---------------------------------------------------------------------------
1691 ;;;; Access to the Operating System
1692
1693 (uiop/package:define-package :uiop/os
1694 (:nicknames :asdf/os)
1695 (:recycle :uiop/os :asdf/os :asdf)
1696 (:use :uiop/common-lisp :uiop/package :uiop/utility)
1697 (:export
1698 #:featurep #:os-unix-p #:os-macosx-p #:os-windows-p #:os-genera-p #:detect-os ;; features
1699 #:os-cond
1700 #:getenv #:getenvp ;; environment variables
1701 #:implementation-identifier ;; implementation identifier
1702 #:implementation-type #:*implementation-type*
1703 #:operating-system #:architecture #:lisp-version-string
1704 #:hostname #:getcwd #:chdir
1705 ;; Windows shortcut support
1706 #:read-null-terminated-string #:read-little-endian
1707 #:parse-file-location-info #:parse-windows-shortcut))
1708 (in-package :uiop/os)
1709
1710 ;;; Features
1711 (with-upgradability ()
1712 (defun featurep (x &optional (*features* *features*))
1713 "Checks whether a feature expression X is true with respect to the *FEATURES* set,
1714 as per the CLHS standard for #+ and #-. Beware that just like the CLHS,
1715 we assume symbols from the KEYWORD package are used, but that unless you're using #+/#-
1716 your reader will not have magically used the KEYWORD package, so you need specify
1717 keywords explicitly."
1718 (cond
1719 ((atom x) (and (member x *features*) t))
1720 ((eq :not (car x)) (assert (null (cddr x))) (not (featurep (cadr x))))
1721 ((eq :or (car x)) (some #'featurep (cdr x)))
1722 ((eq :and (car x)) (every #'featurep (cdr x)))
1723 (t (error "Malformed feature specification ~S" x))))
1724
1725 ;; Starting with UIOP 3.1.5, these are runtime tests.
1726 ;; You may bind *features* with a copy of what your target system offers to test its properties.
1727 (defun os-macosx-p ()
1728 "Is the underlying operating system MacOS X?"
1729 ;; OS-MACOSX is not mutually exclusive with OS-UNIX,
1730 ;; in fact the former implies the latter.
1731 (featurep '(:or :darwin (:and :allegro :macosx) (:and :clisp :macos))))
1732
1733 (defun os-unix-p ()
1734 "Is the underlying operating system some Unix variant?"
1735 (or (featurep '(:or :unix :cygwin :haiku :linux)) (os-macosx-p)))
1736
1737 (defun os-windows-p ()
1738 "Is the underlying operating system Microsoft Windows?"
1739 (and (not (os-unix-p)) (featurep '(:or :win32 :windows :mswindows :mingw32 :mingw64))))
1740
1741 (defun os-genera-p ()
1742 "Is the underlying operating system Genera (running on a Symbolics Lisp Machine)?"
1743 (featurep :genera))
1744
1745 (defun os-oldmac-p ()
1746 "Is the underlying operating system an (emulated?) MacOS 9 or earlier?"
1747 (featurep :mcl))
1748
1749 (defun os-haiku-p ()
1750 "Is the underlying operating system Haiku?"
1751 (featurep :haiku))
1752
1753 (defun detect-os ()
1754 "Detects the current operating system. Only needs be run at compile-time,
1755 except on ABCL where it might change between FASL compilation and runtime."
1756 (loop* :with o
1757 :for (feature . detect) :in '((:os-unix . os-unix-p) (:os-macosx . os-macosx-p)
1758 (:os-windows . os-windows-p)
1759 (:genera . os-genera-p) (:os-oldmac . os-oldmac-p)
1760 (:haiku . os-haiku-p))
1761 :when (and (or (not o) (eq feature :os-macosx)) (funcall detect))
1762 :do (setf o feature) (pushnew feature *features*)
1763 :else :do (setf *features* (remove feature *features*))
1764 :finally
1765 (return (or o (error "Congratulations for trying ASDF on an operating system~%~
1766 that is neither Unix, nor Windows, nor Genera, nor even old MacOS.~%Now you port it.")))))
1767
1768 (defmacro os-cond (&rest clauses)
1769 #+abcl `(cond ,@clauses)
1770 #-abcl (loop* :for (test . body) :in clauses :when (eval test) :return `(progn ,@body)))
1771
1772 (detect-os))
1773
1774 ;;;; Environment variables: getting them, and parsing them.
1775 (with-upgradability ()
1776 (defun getenv (x)
1777 "Query the environment, as in C getenv.
1778 Beware: may return empty string if a variable is present but empty;
1779 use getenvp to return NIL in such a case."
1780 (declare (ignorable x))
1781 #+(or abcl clasp clisp ecl xcl) (ext:getenv x)
1782 #+allegro (sys:getenv x)
1783 #+clozure (ccl:getenv x)
1784 #+cmucl (unix:unix-getenv x)
1785 #+scl (cdr (assoc x ext:*environment-list* :test #'string=))
1786 #+cormanlisp
1787 (let* ((buffer (ct:malloc 1))
1788 (cname (ct:lisp-string-to-c-string x))
1789 (needed-size (win:getenvironmentvariable cname buffer 0))
1790 (buffer1 (ct:malloc (1+ needed-size))))
1791 (prog1 (if (zerop (win:getenvironmentvariable cname buffer1 needed-size))
1792 nil
1793 (ct:c-string-to-lisp-string buffer1))
1794 (ct:free buffer)
1795 (ct:free buffer1)))
1796 #+gcl (system:getenv x)
1797 #+genera nil
1798 #+lispworks (lispworks:environment-variable x)
1799 #+mcl (ccl:with-cstrs ((name x))
1800 (let ((value (_getenv name)))
1801 (unless (ccl:%null-ptr-p value)
1802 (ccl:%get-cstring value))))
1803 #+mkcl (#.(or (find-symbol* 'getenv :si nil) (find-symbol* 'getenv :mk-ext nil)) x)
1804 #+sbcl (sb-ext:posix-getenv x)
1805 #-(or abcl allegro clasp clisp clozure cmucl cormanlisp ecl gcl genera lispworks mcl mkcl sbcl scl xcl)
1806 (error "~S is not supported on your implementation" 'getenv))
1807
1808 (defsetf getenv (x) (val)
1809 "Set an environment variable."
1810 (declare (ignorable x val))
1811 #+allegro `(setf (sys:getenv ,x) ,val)
1812 #+clisp `(system::setenv ,x ,val)
1813 #+clozure `(ccl:setenv ,x ,val)
1814 #+cmucl `(unix:unix-setenv ,x ,val 1)
1815 #+ecl `(ext:setenv ,x ,val)
1816 #+lispworks `(hcl:setenv ,x ,val)
1817 #+mkcl `(mkcl:setenv ,x ,val)
1818 #+sbcl `(progn (require :sb-posix) (symbol-call :sb-posix :setenv ,x ,val 1))
1819 #-(or allegro clisp clozure cmucl ecl lispworks mkcl sbcl)
1820 '(error "~S ~S is not supported on your implementation" 'setf 'getenv))
1821
1822 (defun getenvp (x)
1823 "Predicate that is true if the named variable is present in the libc environment,
1824 then returning the non-empty string value of the variable"
1825 (let ((g (getenv x))) (and (not (emptyp g)) g))))
1826
1827
1828 ;;;; implementation-identifier
1829 ;;
1830 ;; produce a string to identify current implementation.
1831 ;; Initially stolen from SLIME's SWANK, completely rewritten since.
1832 ;; We're back to runtime checking, for the sake of e.g. ABCL.
1833
1834 (with-upgradability ()
1835 (defun first-feature (feature-sets)
1836 "A helper for various feature detection functions"
1837 (dolist (x feature-sets)
1838 (multiple-value-bind (short long feature-expr)
1839 (if (consp x)
1840 (values (first x) (second x) (cons :or (rest x)))
1841 (values x x x))
1842 (when (featurep feature-expr)
1843 (return (values short long))))))
1844
1845 (defun implementation-type ()
1846 "The type of Lisp implementation used, as a short UIOP-standardized keyword"
1847 (first-feature
1848 '(:abcl (:acl :allegro) (:ccl :clozure) :clisp (:corman :cormanlisp)
1849 (:cmu :cmucl :cmu) :clasp :ecl :gcl
1850 (:lwpe :lispworks-personal-edition) (:lw :lispworks)
1851 :mcl :mkcl :sbcl :scl (:smbx :symbolics) :xcl)))
1852
1853 (defvar *implementation-type* (implementation-type)
1854 "The type of Lisp implementation used, as a short UIOP-standardized keyword")
1855
1856 (defun operating-system ()
1857 "The operating system of the current host"
1858 (first-feature
1859 '(:cygwin
1860 (:win :windows :mswindows :win32 :mingw32) ;; try cygwin first!
1861 (:linux :linux :linux-target) ;; for GCL at least, must appear before :bsd
1862 (:macosx :macosx :darwin :darwin-target :apple) ; also before :bsd
1863 (:solaris :solaris :sunos)
1864 (:bsd :bsd :freebsd :netbsd :openbsd :dragonfly)
1865 :unix
1866 :genera)))
1867
1868 (defun architecture ()
1869 "The CPU architecture of the current host"
1870 (first-feature
1871 '((:x64 :x86-64 :x86_64 :x8664-target :amd64 (:and :word-size=64 :pc386))
1872 (:x86 :x86 :i386 :i486 :i586 :i686 :pentium3 :pentium4 :pc386 :iapx386 :x8632-target)
1873 (:ppc64 :ppc64 :ppc64-target) (:ppc32 :ppc32 :ppc32-target :ppc :powerpc)
1874 :hppa64 :hppa :sparc64 (:sparc32 :sparc32 :sparc)
1875 :mipsel :mipseb :mips :alpha (:arm :arm :arm-target) :imach
1876 ;; Java comes last: if someone uses C via CFFI or otherwise JNA or JNI,
1877 ;; we may have to segregate the code still by architecture.
1878 (:java :java :java-1.4 :java-1.5 :java-1.6 :java-1.7))))
1879
1880 #+clozure
1881 (defun ccl-fasl-version ()
1882 ;; the fasl version is target-dependent from CCL 1.8 on.
1883 (or (let ((s 'ccl::target-fasl-version))
1884 (and (fboundp s) (funcall s)))
1885 (and (boundp 'ccl::fasl-version)
1886 (symbol-value 'ccl::fasl-version))
1887 (error "Can't determine fasl version.")))
1888
1889 (defun lisp-version-string ()
1890 "return a string that identifies the current Lisp implementation version"
1891 (let ((s (lisp-implementation-version)))
1892 (car ; as opposed to OR, this idiom prevents some unreachable code warning
1893 (list
1894 #+allegro
1895 (format nil "~A~@[~A~]~@[~A~]~@[~A~]"
1896 excl::*common-lisp-version-number*
1897 ;; M means "modern", as opposed to ANSI-compatible mode (which I consider default)
1898 (and (eq excl:*current-case-mode* :case-sensitive-lower) "M")
1899 ;; Note if not using International ACL
1900 ;; see http://www.franz.com/support/documentation/8.1/doc/operators/excl/ics-target-case.htm
1901 (excl:ics-target-case (:-ics "8"))
1902 (and (member :smp *features*) "S"))
1903 #+armedbear (format nil "~a-fasl~a" s system::*fasl-version*)
1904 #+clisp
1905 (subseq s 0 (position #\space s)) ; strip build information (date, etc.)
1906 #+clozure
1907 (format nil "~d.~d-f~d" ; shorten for windows
1908 ccl::*openmcl-major-version*
1909 ccl::*openmcl-minor-version*
1910 (logand (ccl-fasl-version) #xFF))
1911 #+cmucl (substitute #\- #\/ s)
1912 #+scl (format nil "~A~A" s
1913 ;; ANSI upper case vs lower case.
1914 (ecase ext:*case-mode* (:upper "") (:lower "l")))
1915 #+ecl (format nil "~A~@[-~A~]" s
1916 (let ((vcs-id (ext:lisp-implementation-vcs-id)))
1917 (subseq vcs-id 0 (min (length vcs-id) 8))))
1918 #+gcl (subseq s (1+ (position #\space s)))
1919 #+genera
1920 (multiple-value-bind (major minor) (sct:get-system-version "System")
1921 (format nil "~D.~D" major minor))
1922 #+mcl (subseq s 8) ; strip the leading "Version "
1923 ;; seems like there should be a shorter way to do this, like ACALL.
1924 #+mkcl (or
1925 (let ((fname (find-symbol* '#:git-describe-this-mkcl :mkcl nil)))
1926 (when (and fname (fboundp fname))
1927 (funcall fname)))
1928 s)
1929 s))))
1930
1931 (defun implementation-identifier ()
1932 "Return a string that identifies the ABI of the current implementation,
1933 suitable for use as a directory name to segregate Lisp FASLs, C dynamic libraries, etc."
1934 (substitute-if
1935 #\_ #'(lambda (x) (find x " /:;&^\\|?<>(){}[]$#`'\""))
1936 (format nil "~(~a~@{~@[-~a~]~}~)"
1937 (or (implementation-type) (lisp-implementation-type))
1938 (lisp-version-string)
1939 (or (operating-system) (software-type))
1940 (or (architecture) (machine-type))))))
1941
1942
1943 ;;;; Other system information
1944
1945 (with-upgradability ()
1946 (defun hostname ()
1947 "return the hostname of the current host"
1948 ;; Note: untested on RMCL
1949 #+(or abcl clasp clozure cmucl ecl genera lispworks mcl mkcl sbcl scl xcl) (machine-instance)
1950 #+cormanlisp "localhost" ;; is there a better way? Does it matter?
1951 #+allegro (symbol-call :excl.osi :gethostname)
1952 #+clisp (first (split-string (machine-instance) :separator " "))
1953 #+gcl (system:gethostname)))
1954
1955
1956 ;;; Current directory
1957 (with-upgradability ()
1958
1959 #+cmucl
1960 (defun parse-unix-namestring* (unix-namestring)
1961 "variant of LISP::PARSE-UNIX-NAMESTRING that returns a pathname object"
1962 (multiple-value-bind (host device directory name type version)
1963 (lisp::parse-unix-namestring unix-namestring 0 (length unix-namestring))
1964 (make-pathname :host (or host lisp::*unix-host*) :device device
1965 :directory directory :name name :type type :version version)))
1966
1967 (defun getcwd ()
1968 "Get the current working directory as per POSIX getcwd(3), as a pathname object"
1969 (or #+(or abcl genera xcl) (truename *default-pathname-defaults*) ;; d-p-d is canonical!
1970 #+allegro (excl::current-directory)
1971 #+clisp (ext:default-directory)
1972 #+clozure (ccl:current-directory)
1973 #+(or cmucl scl) (#+cmucl parse-unix-namestring* #+scl lisp::parse-unix-namestring
1974 (strcat (nth-value 1 (unix:unix-current-directory)) "/"))
1975 #+cormanlisp (pathname (pl::get-current-directory)) ;; Q: what type does it return?
1976 #+(or clasp ecl) (ext:getcwd)
1977 #+gcl (let ((*default-pathname-defaults* #p"")) (truename #p""))
1978 #+lispworks (hcl:get-working-directory)
1979 #+mkcl (mk-ext:getcwd)
1980 #+sbcl (sb-ext:parse-native-namestring (sb-unix:posix-getcwd/))
1981 #+xcl (extensions:current-directory)
1982 (error "getcwd not supported on your implementation")))
1983
1984 (defun chdir (x)
1985 "Change current directory, as per POSIX chdir(2), to a given pathname object"
1986 (if-let (x (pathname x))
1987 #+(or abcl genera xcl) (setf *default-pathname-defaults* (truename x)) ;; d-p-d is canonical!
1988 #+allegro (excl:chdir x)
1989 #+clisp (ext:cd x)
1990 #+clozure (setf (ccl:current-directory) x)
1991 #+(or cmucl scl) (unix:unix-chdir (ext:unix-namestring x))
1992 #+cormanlisp (unless (zerop (win32::_chdir (namestring x)))
1993 (error "Could not set current directory to ~A" x))
1994 #+(or clasp ecl) (ext:chdir x)
1995 #+gcl (system:chdir x)
1996 #+lispworks (hcl:change-directory x)
1997 #+mkcl (mk-ext:chdir x)
1998 #+sbcl (progn (require :sb-posix) (symbol-call :sb-posix :chdir (sb-ext:native-namestring x)))
1999 #-(or abcl allegro clasp clisp clozure cmucl cormanlisp ecl gcl genera lispworks mkcl sbcl scl xcl)
2000 (error "chdir not supported on your implementation"))))
2001
2002
2003 ;;;; -----------------------------------------------------------------
2004 ;;;; Windows shortcut support. Based on:
2005 ;;;;
2006 ;;;; Jesse Hager: The Windows Shortcut File Format.
2007 ;;;; http://www.wotsit.org/list.asp?fc=13
2008
2009 #-(or clisp genera) ; CLISP doesn't need it, and READ-SEQUENCE annoys old Genera that doesn't need it
2010 (with-upgradability ()
2011 (defparameter *link-initial-dword* 76)
2012 (defparameter *link-guid* #(1 20 2 0 0 0 0 0 192 0 0 0 0 0 0 70))
2013
2014 (defun read-null-terminated-string (s)
2015 "Read a null-terminated string from an octet stream S"
2016 ;; note: doesn't play well with UNICODE
2017 (with-output-to-string (out)
2018 (loop :for code = (read-byte s)
2019 :until (zerop code)
2020 :do (write-char (code-char code) out))))
2021
2022 (defun read-little-endian (s &optional (bytes 4))
2023 "Read a number in little-endian format from an byte (octet) stream S,
2024 the number having BYTES octets (defaulting to 4)."
2025 (loop :for i :from 0 :below bytes
2026 :sum (ash (read-byte s) (* 8 i))))
2027
2028 (defun parse-file-location-info (s)
2029 "helper to parse-windows-shortcut"
2030 (let ((start (file-position s))
2031 (total-length (read-little-endian s))
2032 (end-of-header (read-little-endian s))
2033 (fli-flags (read-little-endian s))
2034 (local-volume-offset (read-little-endian s))
2035 (local-offset (read-little-endian s))
2036 (network-volume-offset (read-little-endian s))
2037 (remaining-offset (read-little-endian s)))
2038 (declare (ignore total-length end-of-header local-volume-offset))
2039 (unless (zerop fli-flags)
2040 (cond
2041 ((logbitp 0 fli-flags)
2042 (file-position s (+ start local-offset)))
2043 ((logbitp 1 fli-flags)
2044 (file-position s (+ start
2045 network-volume-offset
2046 #x14))))
2047 (strcat (read-null-terminated-string s)
2048 (progn
2049 (file-position s (+ start remaining-offset))
2050 (read-null-terminated-string s))))))
2051
2052 (defun parse-windows-shortcut (pathname)
2053 "From a .lnk windows shortcut, extract the pathname linked to"
2054 ;; NB: doesn't do much checking & doesn't look like it will work well with UNICODE.
2055 (with-open-file (s pathname :element-type '(unsigned-byte 8))
2056 (handler-case
2057 (when (and (= (read-little-endian s) *link-initial-dword*)
2058 (let ((header (make-array (length *link-guid*))))
2059 (read-sequence header s)
2060 (equalp header *link-guid*)))
2061 (let ((flags (read-little-endian s)))
2062 (file-position s 76) ;skip rest of header
2063 (when (logbitp 0 flags)
2064 ;; skip shell item id list
2065 (let ((length (read-little-endian s 2)))
2066 (file-position s (+ length (file-position s)))))
2067 (cond
2068 ((logbitp 1 flags)
2069 (parse-file-location-info s))
2070 (t
2071 (when (logbitp 2 flags)
2072 ;; skip description string
2073 (let ((length (read-little-endian s 2)))
2074 (file-position s (+ length (file-position s)))))
2075 (when (logbitp 3 flags)
2076 ;; finally, our pathname
2077 (let* ((length (read-little-endian s 2))
2078 (buffer (make-array length)))
2079 (read-sequence buffer s)
2080 (map 'string #'code-char buffer)))))))
2081 (end-of-file (c)
2082 (declare (ignore c))
2083 nil)))))
2084
2085
2086 ;;;; -------------------------------------------------------------------------
2087 ;;;; Portability layer around Common Lisp pathnames
2088 ;; This layer allows for portable manipulation of pathname objects themselves,
2089 ;; which all is necessary prior to any access the filesystem or environment.
2090
2091 (uiop/package:define-package :uiop/pathname
2092 (:nicknames :asdf/pathname)
2093 (:recycle :uiop/pathname :asdf/pathname :asdf)
2094 (:use :uiop/common-lisp :uiop/package :uiop/utility :uiop/os)
2095 (:export
2096 ;; Making and merging pathnames, portably
2097 #:normalize-pathname-directory-component #:denormalize-pathname-directory-component
2098 #:merge-pathname-directory-components #:*unspecific-pathname-type* #:make-pathname*
2099 #:make-pathname-component-logical #:make-pathname-logical
2100 #:merge-pathnames*
2101 #:nil-pathname #:*nil-pathname* #:with-pathname-defaults
2102 ;; Predicates
2103 #:pathname-equal #:logical-pathname-p #:physical-pathname-p #:physicalize-pathname
2104 #:absolute-pathname-p #:relative-pathname-p #:hidden-pathname-p #:file-pathname-p
2105 ;; Directories
2106 #:pathname-directory-pathname #:pathname-parent-directory-pathname
2107 #:directory-pathname-p #:ensure-directory-pathname
2108 ;; Parsing filenames
2109 #:component-name-to-pathname-components
2110 #:split-name-type #:parse-unix-namestring #:unix-namestring
2111 #:split-unix-namestring-directory-components
2112 ;; Absolute and relative pathnames
2113 #:subpathname #:subpathname*
2114 #:ensure-absolute-pathname
2115 #:pathname-root #:pathname-host-pathname
2116 #:subpathp #:enough-pathname #:with-enough-pathname #:call-with-enough-pathname
2117 ;; Checking constraints
2118 #:ensure-pathname ;; implemented in filesystem.lisp to accommodate for existence constraints
2119 ;; Wildcard pathnames
2120 #:*wild* #:*wild-file* #:*wild-file-for-directory* #:*wild-directory*
2121 #:*wild-inferiors* #:*wild-path* #:wilden
2122 ;; Translate a pathname
2123 #:relativize-directory-component #:relativize-pathname-directory
2124 #:directory-separator-for-host #:directorize-pathname-host-device
2125 #:translate-pathname*
2126 #:*output-translation-function*))
2127 (in-package :uiop/pathname)
2128
2129 ;;; Normalizing pathnames across implementations
2130
2131 (with-upgradability ()
2132 (defun normalize-pathname-directory-component (directory)
2133 "Convert the DIRECTORY component from a format usable by the underlying
2134 implementation's MAKE-PATHNAME and other primitives to a CLHS-standard format
2135 that is a list and not a string."
2136 (cond
2137 #-(or cmucl sbcl scl) ;; these implementations already normalize directory components.
2138 ((stringp directory) `(:absolute ,directory))
2139 ((or (null directory)
2140 (and (consp directory) (member (first directory) '(:absolute :relative))))
2141 directory)
2142 #+gcl
2143 ((consp directory)
2144 (cons :relative directory))
2145 (t
2146 (error (compatfmt "~@<Unrecognized pathname directory component ~S~@:>") directory))))
2147
2148 (defun denormalize-pathname-directory-component (directory-component)
2149 "Convert the DIRECTORY-COMPONENT from a CLHS-standard format to a format usable
2150 by the underlying implementation's MAKE-PATHNAME and other primitives"
2151 directory-component)
2152
2153 (defun merge-pathname-directory-components (specified defaults)
2154 "Helper for MERGE-PATHNAMES* that handles directory components"
2155 (let ((directory (normalize-pathname-directory-component specified)))
2156 (ecase (first directory)
2157 ((nil) defaults)
2158 (:absolute specified)
2159 (:relative
2160 (let ((defdir (normalize-pathname-directory-component defaults))
2161 (reldir (cdr directory)))
2162 (cond
2163 ((null defdir)
2164 directory)
2165 ((not (eq :back (first reldir)))
2166 (append defdir reldir))
2167 (t
2168 (loop :with defabs = (first defdir)
2169 :with defrev = (reverse (rest defdir))
2170 :while (and (eq :back (car reldir))
2171 (or (and (eq :absolute defabs) (null defrev))
2172 (stringp (car defrev))))
2173 :do (pop reldir) (pop defrev)
2174 :finally (return (cons defabs (append (reverse defrev) reldir)))))))))))
2175
2176 ;; Giving :unspecific as :type argument to make-pathname is not portable.
2177 ;; See CLHS make-pathname and 19.2.2.2.3.
2178 ;; This will be :unspecific if supported, or NIL if not.
2179 (defparameter *unspecific-pathname-type*
2180 #+(or abcl allegro clozure cmucl genera lispworks sbcl scl) :unspecific
2181 #+(or clasp clisp ecl mkcl gcl xcl #|These haven't been tested:|# cormanlisp mcl) nil
2182 "Unspecific type component to use with the underlying implementation's MAKE-PATHNAME")
2183
2184 (defun make-pathname* (&rest keys &key directory host device name type version defaults
2185 #+scl &allow-other-keys)
2186 "Takes arguments like CL:MAKE-PATHNAME in the CLHS, and
2187 tries hard to make a pathname that will actually behave as documented,
2188 despite the peculiarities of each implementation. DEPRECATED: just use MAKE-PATHNAME."
2189 (declare (ignore host device directory name type version defaults))
2190 (apply 'make-pathname keys))
2191
2192 (defun make-pathname-component-logical (x)
2193 "Make a pathname component suitable for use in a logical-pathname"
2194 (typecase x
2195 ((eql :unspecific) nil)
2196 #+clisp (string (string-upcase x))
2197 #+clisp (cons (mapcar 'make-pathname-component-logical x))
2198 (t x)))
2199
2200 (defun make-pathname-logical (pathname host)
2201 "Take a PATHNAME's directory, name, type and version components,
2202 and make a new pathname with corresponding components and specified logical HOST"
2203 (make-pathname
2204 :host host
2205 :directory (make-pathname-component-logical (pathname-directory pathname))
2206 :name (make-pathname-component-logical (pathname-name pathname))
2207 :type (make-pathname-component-logical (pathname-type pathname))
2208 :version (make-pathname-component-logical (pathname-version pathname))))
2209
2210 (defun merge-pathnames* (specified &optional (defaults *default-pathname-defaults*))
2211 "MERGE-PATHNAMES* is like MERGE-PATHNAMES except that
2212 if the SPECIFIED pathname does not have an absolute directory,
2213 then the HOST and DEVICE both come from the DEFAULTS, whereas
2214 if the SPECIFIED pathname does have an absolute directory,
2215 then the HOST and DEVICE both come from the SPECIFIED pathname.
2216 This is what users want on a modern Unix or Windows operating system,
2217 unlike the MERGE-PATHNAMES behavior.
2218 Also, if either argument is NIL, then the other argument is returned unmodified;
2219 this is unlike MERGE-PATHNAMES which always merges with a pathname,
2220 by default *DEFAULT-PATHNAME-DEFAULTS*, which cannot be NIL."
2221 (when (null specified) (return-from merge-pathnames* defaults))
2222 (when (null defaults) (return-from merge-pathnames* specified))
2223 #+scl
2224 (ext:resolve-pathname specified defaults)
2225 #-scl
2226 (let* ((specified (pathname specified))
2227 (defaults (pathname defaults))
2228 (directory (normalize-pathname-directory-component (pathname-directory specified)))
2229 (name (or (pathname-name specified) (pathname-name defaults)))
2230 (type (or (pathname-type specified) (pathname-type defaults)))
2231 (version (or (pathname-version specified) (pathname-version defaults))))
2232 (labels ((unspecific-handler (p)
2233 (if (typep p 'logical-pathname) #'make-pathname-component-logical #'identity)))
2234 (multiple-value-bind (host device directory unspecific-handler)
2235 (ecase (first directory)
2236 ((:absolute)
2237 (values (pathname-host specified)
2238 (pathname-device specified)
2239 directory
2240 (unspecific-handler specified)))
2241 ((nil :relative)
2242 (values (pathname-host defaults)
2243 (pathname-device defaults)
2244 (merge-pathname-directory-components directory (pathname-directory defaults))
2245 (unspecific-handler defaults))))
2246 (make-pathname :host host :device device :directory directory
2247 :name (funcall unspecific-handler name)
2248 :type (funcall unspecific-handler type)
2249 :version (funcall unspecific-handler version))))))
2250
2251 (defun logical-pathname-p (x)
2252 "is X a logical-pathname?"
2253 (typep x 'logical-pathname))
2254
2255 (defun physical-pathname-p (x)
2256 "is X a pathname that is not a logical-pathname?"
2257 (and (pathnamep x) (not (logical-pathname-p x))))
2258
2259 (defun physicalize-pathname (x)
2260 "if X is a logical pathname, use translate-logical-pathname on it."
2261 ;; Ought to be the same as translate-logical-pathname, except the latter borks on CLISP
2262 (let ((p (when x (pathname x))))
2263 (if (logical-pathname-p p) (translate-logical-pathname p) p)))
2264
2265 (defun nil-pathname (&optional (defaults *default-pathname-defaults*))
2266 "A pathname that is as neutral as possible for use as defaults
2267 when merging, making or parsing pathnames"
2268 ;; 19.2.2.2.1 says a NIL host can mean a default host;
2269 ;; see also "valid physical pathname host" in the CLHS glossary, that suggests
2270 ;; strings and lists of strings or :unspecific
2271 ;; But CMUCL decides to die on NIL.
2272 ;; MCL has issues with make-pathname, nil and defaulting
2273 (declare (ignorable defaults))
2274 #.`(make-pathname :directory nil :name nil :type nil :version nil
2275 :device (or #+(and mkcl unix) :unspecific)
2276 :host (or #+cmucl lisp::*unix-host* #+(and mkcl unix) "localhost")
2277 #+scl ,@'(:scheme nil :scheme-specific-part nil
2278 :username nil :password nil :parameters nil :query nil :fragment nil)
2279 ;; the default shouldn't matter, but we really want something physical
2280 #-mcl ,@'(:defaults defaults)))
2281
2282 (defvar *nil-pathname* (nil-pathname (physicalize-pathname (user-homedir-pathname)))
2283 "A pathname that is as neutral as possible for use as defaults
2284 when merging, making or parsing pathnames")
2285
2286 (defmacro with-pathname-defaults ((&optional defaults) &body body)
2287 "Execute BODY in a context where the *DEFAULT-PATHNAME-DEFAULTS* is as specified,
2288 where leaving the defaults NIL or unspecified means a (NIL-PATHNAME), except
2289 on ABCL, Genera and XCL, where it remains unchanged for it doubles as current-directory."
2290 `(let ((*default-pathname-defaults*
2291 ,(or defaults
2292 #-(or abcl genera xcl) '*nil-pathname*
2293 #+(or abcl genera xcl) '*default-pathname-defaults*)))
2294 ,@body)))
2295
2296
2297 ;;; Some pathname predicates
2298 (with-upgradability ()
2299 (defun pathname-equal (p1 p2)
2300 "Are the two pathnames P1 and P2 reasonably equal in the paths they denote?"
2301 (when (stringp p1) (setf p1 (pathname p1)))
2302 (when (stringp p2) (setf p2 (pathname p2)))
2303 (flet ((normalize-component (x)
2304 (unless (member x '(nil :unspecific :newest (:relative)) :test 'equal)
2305 x)))
2306 (macrolet ((=? (&rest accessors)
2307 (flet ((frob (x)
2308 (reduce 'list (cons 'normalize-component accessors)
2309 :initial-value x :from-end t)))
2310 `(equal ,(frob 'p1) ,(frob 'p2)))))
2311 (or (and (null p1) (null p2))
2312 (and (pathnamep p1) (pathnamep p2)
2313 (and (=? pathname-host)
2314 #-(and mkcl unix) (=? pathname-device)
2315 (=? normalize-pathname-directory-component pathname-directory)
2316 (=? pathname-name)
2317 (=? pathname-type)
2318 #-mkcl (=? pathname-version)))))))
2319
2320 (defun absolute-pathname-p (pathspec)
2321 "If PATHSPEC is a pathname or namestring object that parses as a pathname
2322 possessing an :ABSOLUTE directory component, return the (parsed) pathname.
2323 Otherwise return NIL"
2324 (and pathspec
2325 (typep pathspec '(or null pathname string))
2326 (let ((pathname (pathname pathspec)))
2327 (and (eq :absolute (car (normalize-pathname-directory-component
2328 (pathname-directory pathname))))
2329 pathname))))
2330
2331 (defun relative-pathname-p (pathspec)
2332 "If PATHSPEC is a pathname or namestring object that parses as a pathname
2333 possessing a :RELATIVE or NIL directory component, return the (parsed) pathname.
2334 Otherwise return NIL"
2335 (and pathspec
2336 (typep pathspec '(or null pathname string))
2337 (let* ((pathname (pathname pathspec))
2338 (directory (normalize-pathname-directory-component
2339 (pathname-directory pathname))))
2340 (when (or (null directory) (eq :relative (car directory)))
2341 pathname))))
2342
2343 (defun hidden-pathname-p (pathname)
2344 "Return a boolean that is true if the pathname is hidden as per Unix style,
2345 i.e. its name starts with a dot."
2346 (and pathname (equal (first-char (pathname-name pathname)) #\.)))
2347
2348 (defun file-pathname-p (pathname)
2349 "Does PATHNAME represent a file, i.e. has a non-null NAME component?
2350
2351 Accepts NIL, a string (converted through PARSE-NAMESTRING) or a PATHNAME.
2352
2353 Note that this does _not_ check to see that PATHNAME points to an
2354 actually-existing file.
2355
2356 Returns the (parsed) PATHNAME when true"
2357 (when pathname
2358 (let ((pathname (pathname pathname)))
2359 (unless (and (member (pathname-name pathname) '(nil :unspecific "") :test 'equal)
2360 (member (pathname-type pathname) '(nil :unspecific "") :test 'equal))
2361 pathname)))))
2362
2363
2364 ;;; Directory pathnames
2365 (with-upgradability ()
2366 (defun pathname-directory-pathname (pathname)
2367 "Returns a new pathname with same HOST, DEVICE, DIRECTORY as PATHNAME,
2368 and NIL NAME, TYPE and VERSION components"
2369 (when pathname
2370 (make-pathname :name nil :type nil :version nil :defaults pathname)))
2371
2372 (defun pathname-parent-directory-pathname (pathname)
2373 "Returns a new pathname that corresponds to the parent of the current pathname's directory,
2374 i.e. removing one level of depth in the DIRECTORY component. e.g. if pathname is
2375 Unix pathname /foo/bar/baz/file.type then return /foo/bar/"
2376 (when pathname
2377 (make-pathname :name nil :type nil :version nil
2378 :directory (merge-pathname-directory-components
2379 '(:relative :back) (pathname-directory pathname))
2380 :defaults pathname)))
2381
2382 (defun directory-pathname-p (pathname)
2383 "Does PATHNAME represent a directory?
2384
2385 A directory-pathname is a pathname _without_ a filename. The three
2386 ways that the filename components can be missing are for it to be NIL,
2387 :UNSPECIFIC or the empty string.
2388
2389 Note that this does _not_ check to see that PATHNAME points to an
2390 actually-existing directory."
2391 (when pathname
2392 ;; I tried using Allegro's excl:file-directory-p, but this cannot be done,
2393 ;; because it rejects apparently legal pathnames as
2394 ;; ill-formed. [2014/02/10:rpg]
2395 (let ((pathname (pathname pathname)))
2396 (flet ((check-one (x)
2397 (member x '(nil :unspecific) :test 'equal)))
2398 (and (not (wild-pathname-p pathname))
2399 (check-one (pathname-name pathname))
2400 (check-one (pathname-type pathname))
2401 t)))))
2402
2403 (defun ensure-directory-pathname (pathspec &optional (on-error 'error))
2404 "Converts the non-wild pathname designator PATHSPEC to directory form."
2405 (cond
2406 ((stringp pathspec)
2407 (ensure-directory-pathname (pathname pathspec)))
2408 ((not (pathnamep pathspec))
2409 (call-function on-error (compatfmt "~@<Invalid pathname designator ~S~@:>") pathspec))
2410 ((wild-pathname-p pathspec)
2411 (call-function on-error (compatfmt "~@<Can't reliably convert wild pathname ~3i~_~S~@:>") pathspec))
2412 ((directory-pathname-p pathspec)
2413 pathspec)
2414 (t
2415 (handler-case
2416 (make-pathname :directory (append (or (normalize-pathname-directory-component
2417 (pathname-directory pathspec))
2418 (list :relative))
2419 (list (file-namestring pathspec)))
2420 :name nil :type nil :version nil :defaults pathspec)
2421 (error (c) (call-function on-error (compatfmt "~@<error while trying to create a directory pathname for ~S: ~A~@:>") pathspec c)))))))
2422
2423
2424 ;;; Parsing filenames
2425 (with-upgradability ()
2426 (defun split-unix-namestring-directory-components
2427 (unix-namestring &key ensure-directory dot-dot)
2428 "Splits the path string UNIX-NAMESTRING, returning four values:
2429 A flag that is either :absolute or :relative, indicating
2430 how the rest of the values are to be interpreted.
2431 A directory path --- a list of strings and keywords, suitable for
2432 use with MAKE-PATHNAME when prepended with the flag value.
2433 Directory components with an empty name or the name . are removed.
2434 Any directory named .. is read as DOT-DOT, or :BACK if it's NIL (not :UP).
2435 A last-component, either a file-namestring including type extension,
2436 or NIL in the case of a directory pathname.
2437 A flag that is true iff the unix-style-pathname was just
2438 a file-namestring without / path specification.
2439 ENSURE-DIRECTORY forces the namestring to be interpreted as a directory pathname:
2440 the third return value will be NIL, and final component of the namestring
2441 will be treated as part of the directory path.
2442
2443 An empty string is thus read as meaning a pathname object with all fields nil.
2444
2445 Note that colon characters #\: will NOT be interpreted as host specification.
2446 Absolute pathnames are only appropriate on Unix-style systems.
2447
2448 The intention of this function is to support structured component names,
2449 e.g., \(:file \"foo/bar\"\), which will be unpacked to relative pathnames."
2450 (check-type unix-namestring string)
2451 (check-type dot-dot (member nil :back :up))
2452 (if (and (not (find #\/ unix-namestring)) (not ensure-directory)
2453 (plusp (length unix-namestring)))
2454 (values :relative () unix-namestring t)
2455 (let* ((components (split-string unix-namestring :separator "/"))
2456 (last-comp (car (last components))))
2457 (multiple-value-bind (relative components)
2458 (if (equal (first components) "")
2459 (if (equal (first-char unix-namestring) #\/)
2460 (values :absolute (cdr components))
2461 (values :relative nil))
2462 (values :relative components))
2463 (setf components (remove-if #'(lambda (x) (member x '("" ".") :test #'equal))
2464 components))
2465 (setf components (substitute (or dot-dot :back) ".." components :test #'equal))
2466 (cond
2467 ((equal last-comp "")
2468 (values relative components nil nil)) ; "" already removed from components
2469 (ensure-directory
2470 (values relative components nil nil))
2471 (t
2472 (values relative (butlast components) last-comp nil)))))))
2473
2474 (defun split-name-type (filename)
2475 "Split a filename into two values NAME and TYPE that are returned.
2476 We assume filename has no directory component.
2477 The last . if any separates name and type from from type,
2478 except that if there is only one . and it is in first position,
2479 the whole filename is the NAME with an empty type.
2480 NAME is always a string.
2481 For an empty type, *UNSPECIFIC-PATHNAME-TYPE* is returned."
2482 (check-type filename string)
2483 (assert (plusp (length filename)))
2484 (destructuring-bind (name &optional (type *unspecific-pathname-type*))
2485 (split-string filename :max 2 :separator ".")
2486 (if (equal name "")
2487 (values filename *unspecific-pathname-type*)
2488 (values name type))))
2489
2490 (defun parse-unix-namestring (name &rest keys &key type defaults dot-dot ensure-directory
2491 &allow-other-keys)
2492 "Coerce NAME into a PATHNAME using standard Unix syntax.
2493
2494 Unix syntax is used whether or not the underlying system is Unix;
2495 on such non-Unix systems it is reliably usable only for relative pathnames.
2496 This function is especially useful to manipulate relative pathnames portably,
2497 where it is of crucial to possess a portable pathname syntax independent of the underlying OS.
2498 This is what PARSE-UNIX-NAMESTRING provides, and why we use it in ASDF.
2499
2500 When given a PATHNAME object, just return it untouched.
2501 When given NIL, just return NIL.
2502 When given a non-null SYMBOL, first downcase its name and treat it as a string.
2503 When given a STRING, portably decompose it into a pathname as below.
2504
2505 #\\/ separates directory components.
2506
2507 The last #\\/-separated substring is interpreted as follows:
2508 1- If TYPE is :DIRECTORY or ENSURE-DIRECTORY is true,
2509 the string is made the last directory component, and NAME and TYPE are NIL.
2510 if the string is empty, it's the empty pathname with all slots NIL.
2511 2- If TYPE is NIL, the substring is a file-namestring, and its NAME and TYPE
2512 are separated by SPLIT-NAME-TYPE.
2513 3- If TYPE is a string, it is the given TYPE, and the whole string is the NAME.
2514
2515 Directory components with an empty name or the name \".\" are removed.
2516 Any directory named \"..\" is read as DOT-DOT,
2517 which must be one of :BACK or :UP and defaults to :BACK.
2518
2519 HOST, DEVICE and VERSION components are taken from DEFAULTS,
2520 which itself defaults to *NIL-PATHNAME*, also used if DEFAULTS is NIL.
2521 No host or device can be specified in the string itself,
2522 which makes it unsuitable for absolute pathnames outside Unix.
2523
2524 For relative pathnames, these components (and hence the defaults) won't matter
2525 if you use MERGE-PATHNAMES* but will matter if you use MERGE-PATHNAMES,
2526 which is an important reason to always use MERGE-PATHNAMES*.
2527
2528 Arbitrary keys are accepted, and the parse result is passed to ENSURE-PATHNAME
2529 with those keys, removing TYPE DEFAULTS and DOT-DOT.
2530 When you're manipulating pathnames that are supposed to make sense portably
2531 even though the OS may not be Unixish, we recommend you use :WANT-RELATIVE T
2532 to throw an error if the pathname is absolute"
2533 (block nil
2534 (check-type type (or null string (eql :directory)))
2535 (when ensure-directory
2536 (setf type :directory))
2537 (etypecase name
2538 ((or null pathname) (return name))
2539 (symbol
2540 (setf name (string-downcase name)))
2541 (string))
2542 (multiple-value-bind (relative path filename file-only)
2543 (split-unix-namestring-directory-components
2544 name :dot-dot dot-dot :ensure-directory (eq type :directory))
2545 (multiple-value-bind (name type)
2546 (cond
2547 ((or (eq type :directory) (null filename))
2548 (values nil nil))
2549 (type
2550 (values filename type))
2551 (t
2552 (split-name-type filename)))
2553 (apply 'ensure-pathname
2554 (make-pathname
2555 :directory (unless file-only (cons relative path))
2556 :name name :type type
2557 :defaults (or #-mcl defaults *nil-pathname*))
2558 (remove-plist-keys '(:type :dot-dot :defaults) keys))))))
2559
2560 (defun unix-namestring (pathname)
2561 "Given a non-wild PATHNAME, return a Unix-style namestring for it.
2562 If the PATHNAME is NIL or a STRING, return it unchanged.
2563
2564 This only considers the DIRECTORY, NAME and TYPE components of the pathname.
2565 This is a portable solution for representing relative pathnames,
2566 But unless you are running on a Unix system, it is not a general solution
2567 to representing native pathnames.
2568
2569 An error is signaled if the argument is not NULL, a STRING or a PATHNAME,
2570 or if it is a PATHNAME but some of its components are not recognized."
2571 (etypecase pathname
2572 ((or null string) pathname)
2573 (pathname
2574 (with-output-to-string (s)
2575 (flet ((err () #+lispworks (describe pathname) (error "Not a valid unix-namestring ~S" pathname)))
2576 (let* ((dir (normalize-pathname-directory-component (pathname-directory pathname)))
2577 (name (pathname-name pathname))
2578 (name (and (not (eq name :unspecific)) name))
2579 (type (pathname-type pathname))
2580 (type (and (not (eq type :unspecific)) type)))
2581 (cond
2582 ((member dir '(nil :unspecific)))
2583 ((eq dir '(:relative)) (princ "./" s))
2584 ((consp dir)
2585 (destructuring-bind (relabs &rest dirs) dir
2586 (or (member relabs '(:relative :absolute)) (err))
2587 (when (eq relabs :absolute) (princ #\/ s))
2588 (loop :for x :in dirs :do
2589 (cond
2590 ((member x '(:back :up)) (princ "../" s))
2591 ((equal x "") (err))
2592 ;;((member x '("." "..") :test 'equal) (err))
2593 ((stringp x) (format s "~A/" x))
2594 (t (err))))))
2595 (t (err)))
2596 (cond
2597 (name
2598 (unless (and (stringp name) (or (null type) (stringp type))) (err))
2599 (format s "~A~@[.~A~]" name type))
2600 (t
2601 (or (null type) (err)))))))))))
2602
2603 ;;; Absolute and relative pathnames
2604 (with-upgradability ()
2605 (defun subpathname (pathname subpath &key type)
2606 "This function takes a PATHNAME and a SUBPATH and a TYPE.
2607 If SUBPATH is already a PATHNAME object (not namestring),
2608 and is an absolute pathname at that, it is returned unchanged;
2609 otherwise, SUBPATH is turned into a relative pathname with given TYPE
2610 as per PARSE-UNIX-NAMESTRING with :WANT-RELATIVE T :TYPE TYPE,
2611 then it is merged with the PATHNAME-DIRECTORY-PATHNAME of PATHNAME."
2612 (or (and (pathnamep subpath) (absolute-pathname-p subpath))
2613 (merge-pathnames* (parse-unix-namestring subpath :type type :want-relative t)
2614 (pathname-directory-pathname pathname))))
2615
2616 (defun subpathname* (pathname subpath &key type)
2617 "returns NIL if the base pathname is NIL, otherwise like SUBPATHNAME."
2618 (and pathname
2619 (subpathname (ensure-directory-pathname pathname) subpath :type type)))
2620
2621 (defun pathname-root (pathname)
2622 "return the root directory for the host and device of given PATHNAME"
2623 (make-pathname :directory '(:absolute)
2624 :name nil :type nil :version nil
2625 :defaults pathname ;; host device, and on scl, *some*
2626 ;; scheme-specific parts: port username password, not others:
2627 . #.(or #+scl '(:parameters nil :query nil :fragment nil))))
2628
2629 (defun pathname-host-pathname (pathname)
2630 "return a pathname with the same host as given PATHNAME, and all other fields NIL"
2631 (make-pathname :directory nil
2632 :name nil :type nil :version nil :device nil
2633 :defaults pathname ;; host device, and on scl, *some*
2634 ;; scheme-specific parts: port username password, not others:
2635 . #.(or #+scl '(:parameters nil :query nil :fragment nil))))
2636
2637 (defun ensure-absolute-pathname (path &optional defaults (on-error 'error))
2638 "Given a pathname designator PATH, return an absolute pathname as specified by PATH
2639 considering the DEFAULTS, or, if not possible, use CALL-FUNCTION on the specified ON-ERROR behavior,
2640 with a format control-string and other arguments as arguments"
2641 (cond
2642 ((absolute-pathname-p path))
2643 ((stringp path) (ensure-absolute-pathname (pathname path) defaults on-error))
2644 ((not (pathnamep path)) (call-function on-error "not a valid pathname designator ~S" path))
2645 ((let ((default-pathname (if (pathnamep defaults) defaults (call-function defaults))))
2646 (or (if (absolute-pathname-p default-pathname)
2647 (absolute-pathname-p (merge-pathnames* path default-pathname))
2648 (call-function on-error "Default pathname ~S is not an absolute pathname"
2649 default-pathname))
2650 (call-function on-error "Failed to merge ~S with ~S into an absolute pathname"
2651 path default-pathname))))
2652 (t (call-function on-error
2653 "Cannot ensure ~S is evaluated as an absolute pathname with defaults ~S"
2654 path defaults))))
2655
2656 (defun subpathp (maybe-subpath base-pathname)
2657 "if MAYBE-SUBPATH is a pathname that is under BASE-PATHNAME, return a pathname object that
2658 when used with MERGE-PATHNAMES* with defaults BASE-PATHNAME, returns MAYBE-SUBPATH."
2659 (and (pathnamep maybe-subpath) (pathnamep base-pathname)
2660 (absolute-pathname-p maybe-subpath) (absolute-pathname-p base-pathname)
2661 (directory-pathname-p base-pathname) (not (wild-pathname-p base-pathname))
2662 (pathname-equal (pathname-root maybe-subpath) (pathname-root base-pathname))
2663 (with-pathname-defaults (*nil-pathname*)
2664 (let ((enough (enough-namestring maybe-subpath base-pathname)))
2665 (and (relative-pathname-p enough) (pathname enough))))))
2666
2667 (defun enough-pathname (maybe-subpath base-pathname)
2668 "if MAYBE-SUBPATH is a pathname that is under BASE-PATHNAME, return a pathname object that
2669 when used with MERGE-PATHNAMES* with defaults BASE-PATHNAME, returns MAYBE-SUBPATH."
2670 (let ((sub (when maybe-subpath (pathname maybe-subpath)))
2671 (base (when base-pathname (ensure-absolute-pathname (pathname base-pathname)))))
2672 (or (and base (subpathp sub base)) sub)))
2673
2674 (defun call-with-enough-pathname (maybe-subpath defaults-pathname thunk)
2675 "In a context where *DEFAULT-PATHNAME-DEFAULTS* is bound to DEFAULTS-PATHNAME (if not null,
2676 or else to its current value), call THUNK with ENOUGH-PATHNAME for MAYBE-SUBPATH
2677 given DEFAULTS-PATHNAME as a base pathname."
2678 (let ((enough (enough-pathname maybe-subpath defaults-pathname))
2679 (*default-pathname-defaults* (or defaults-pathname *default-pathname-defaults*)))
2680 (funcall thunk enough)))
2681
2682 (defmacro with-enough-pathname ((pathname-var &key (pathname pathname-var)
2683 (defaults *default-pathname-defaults*))
2684 &body body)
2685 "Shorthand syntax for CALL-WITH-ENOUGH-PATHNAME"
2686 `(call-with-enough-pathname ,pathname ,defaults #'(lambda (,pathname-var) ,@body))))
2687
2688
2689 ;;; Wildcard pathnames
2690 (with-upgradability ()
2691 (defparameter *wild* (or #+cormanlisp "*" :wild)
2692 "Wild component for use with MAKE-PATHNAME")
2693 (defparameter *wild-directory-component* (or :wild)
2694 "Wild directory component for use with MAKE-PATHNAME")
2695 (defparameter *wild-inferiors-component* (or :wild-inferiors)
2696 "Wild-inferiors directory component for use with MAKE-PATHNAME")
2697 (defparameter *wild-file*
2698 (make-pathname :directory nil :name *wild* :type *wild*
2699 :version (or #-(or allegro abcl xcl) *wild*))
2700 "A pathname object with wildcards for matching any file with TRANSLATE-PATHNAME")
2701 (defparameter *wild-file-for-directory*
2702 (make-pathname :directory nil :name *wild* :type (or #-(or clisp gcl) *wild*)
2703 :version (or #-(or allegro abcl clisp gcl xcl) *wild*))
2704 "A pathname object with wildcards for matching any file with DIRECTORY")
2705 (defparameter *wild-directory*
2706 (make-pathname :directory `(:relative ,*wild-directory-component*)
2707 :name nil :type nil :version nil)
2708 "A pathname object with wildcards for matching any subdirectory")
2709 (defparameter *wild-inferiors*
2710 (make-pathname :directory `(:relative ,*wild-inferiors-component*)
2711 :name nil :type nil :version nil)
2712 "A pathname object with wildcards for matching any recursive subdirectory")
2713 (defparameter *wild-path*
2714 (merge-pathnames* *wild-file* *wild-inferiors*)
2715 "A pathname object with wildcards for matching any file in any recursive subdirectory")
2716
2717 (defun wilden (path)
2718 "From a pathname, return a wildcard pathname matching any file in any subdirectory of given pathname's directory"
2719 (merge-pathnames* *wild-path* path)))
2720
2721
2722 ;;; Translate a pathname
2723 (with-upgradability ()
2724 (defun relativize-directory-component (directory-component)
2725 "Given the DIRECTORY-COMPONENT of a pathname, return an otherwise similar relative directory component"
2726 (let ((directory (normalize-pathname-directory-component directory-component)))
2727 (cond
2728 ((stringp directory)
2729 (list :relative directory))
2730 ((eq (car directory) :absolute)
2731 (cons :relative (cdr directory)))
2732 (t
2733 directory))))
2734
2735 (defun relativize-pathname-directory (pathspec)
2736 "Given a PATHNAME, return a relative pathname with otherwise the same components"
2737 (let ((p (pathname pathspec)))
2738 (make-pathname
2739 :directory (relativize-directory-component (pathname-directory p))
2740 :defaults p)))
2741
2742 (defun directory-separator-for-host (&optional (pathname *default-pathname-defaults*))
2743 "Given a PATHNAME, return the character used to delimit directory names on this host and device."
2744 (let ((foo (make-pathname :directory '(:absolute "FOO") :defaults pathname)))
2745 (last-char (namestring foo))))
2746
2747 #-scl
2748 (defun directorize-pathname-host-device (pathname)
2749 "Given a PATHNAME, return a pathname that has representations of its HOST and DEVICE components
2750 added to its DIRECTORY component. This is useful for output translations."
2751 (os-cond
2752 ((os-unix-p)
2753 (when (physical-pathname-p pathname)
2754 (return-from directorize-pathname-host-device pathname))))
2755 (let* ((root (pathname-root pathname))
2756 (wild-root (wilden root))
2757 (absolute-pathname (merge-pathnames* pathname root))
2758 (separator (directory-separator-for-host root))
2759 (root-namestring (namestring root))
2760 (root-string
2761 (substitute-if #\/
2762 #'(lambda (x) (or (eql x #\:)
2763 (eql x separator)))
2764 root-namestring)))
2765 (multiple-value-bind (relative path filename)
2766 (split-unix-namestring-directory-components root-string :ensure-directory t)
2767 (declare (ignore relative filename))
2768 (let ((new-base (make-pathname :defaults root :directory `(:absolute ,@path))))
2769 (translate-pathname absolute-pathname wild-root (wilden new-base))))))
2770
2771 #+scl
2772 (defun directorize-pathname-host-device (pathname)
2773 (let ((scheme (ext:pathname-scheme pathname))
2774 (host (pathname-host pathname))
2775 (port (ext:pathname-port pathname))
2776 (directory (pathname-directory pathname)))
2777 (flet ((specificp (x) (and x (not (eq x :unspecific)))))
2778 (if (or (specificp port)
2779 (and (specificp host) (plusp (length host)))
2780 (specificp scheme))
2781 (let ((prefix ""))
2782 (when (specificp port)
2783 (setf prefix (format nil ":~D" port)))
2784 (when (and (specificp host) (plusp (length host)))
2785 (setf prefix (strcat host prefix)))
2786 (setf prefix (strcat ":" prefix))
2787 (when (specificp scheme)
2788 (setf prefix (strcat scheme prefix)))
2789 (assert (and directory (eq (first directory) :absolute)))
2790 (make-pathname :directory `(:absolute ,prefix ,@(rest directory))
2791 :defaults pathname)))
2792 pathname)))
2793
2794 (defun* (translate-pathname*) (path absolute-source destination &optional root source)
2795 "A wrapper around TRANSLATE-PATHNAME to be used by the ASDF output-translations facility.
2796 PATH is the pathname to be translated.
2797 ABSOLUTE-SOURCE is an absolute pathname to use as source for translate-pathname,
2798 DESTINATION is either a function, to be called with PATH and ABSOLUTE-SOURCE,
2799 or a relative pathname, to be merged with ROOT and used as destination for translate-pathname
2800 or an absolute pathname, to be used as destination for translate-pathname.
2801 In that last case, if ROOT is non-NIL, PATH is first transformated by DIRECTORIZE-PATHNAME-HOST-DEVICE."
2802 (declare (ignore source))
2803 (cond
2804 ((functionp destination)
2805 (funcall destination path absolute-source))
2806 ((eq destination t)
2807 path)
2808 ((not (pathnamep destination))
2809 (error "Invalid destination"))
2810 ((not (absolute-pathname-p destination))
2811 (translate-pathname path absolute-source (merge-pathnames* destination root)))
2812 (root
2813 (translate-pathname (directorize-pathname-host-device path) absolute-source destination))
2814 (t
2815 (translate-pathname path absolute-source destination))))
2816
2817 (defvar *output-translation-function* 'identity
2818 "Hook for output translations.
2819
2820 This function needs to be idempotent, so that actions can work
2821 whether their inputs were translated or not,
2822 which they will be if we are composing operations. e.g. if some
2823 create-lisp-op creates a lisp file from some higher-level input,
2824 you need to still be able to use compile-op on that lisp file."))
2825
2826 ;;;; -------------------------------------------------------------------------
2827 ;;;; Portability layer around Common Lisp filesystem access
2828
2829 (uiop/package:define-package :uiop/filesystem
2830 (:nicknames :asdf/filesystem)
2831 (:recycle :uiop/filesystem :asdf/pathname :asdf)
2832 (:use :uiop/common-lisp :uiop/package :uiop/utility :uiop/os :uiop/pathname)
2833 (:export
2834 ;; Native namestrings
2835 #:native-namestring #:parse-native-namestring
2836 ;; Probing the filesystem
2837 #:truename* #:safe-file-write-date #:probe-file* #:directory-exists-p #:file-exists-p
2838 #:directory* #:filter-logical-directory-results #:directory-files #:subdirectories
2839 #:collect-sub*directories
2840 ;; Resolving symlinks somewhat
2841 #:truenamize #:resolve-symlinks #:*resolve-symlinks* #:resolve-symlinks*
2842 ;; merging with cwd
2843 #:get-pathname-defaults #:call-with-current-directory #:with-current-directory
2844 ;; Environment pathnames
2845 #:inter-directory-separator #:split-native-pathnames-string
2846 #:getenv-pathname #:getenv-pathnames
2847 #:getenv-absolute-directory #:getenv-absolute-directories
2848 #:lisp-implementation-directory #:lisp-implementation-pathname-p
2849 ;; Simple filesystem operations
2850 #:ensure-all-directories-exist
2851 #:rename-file-overwriting-target
2852 #:delete-file-if-exists #:delete-empty-directory #:delete-directory-tree))
2853 (in-package :uiop/filesystem)
2854
2855 ;;; Native namestrings, as seen by the operating system calls rather than Lisp
2856 (with-upgradability ()
2857 (defun native-namestring (x)
2858 "From a non-wildcard CL pathname, a return namestring suitable for passing to the operating system"
2859 (when x
2860 (let ((p (pathname x)))
2861 #+clozure (with-pathname-defaults () (ccl:native-translated-namestring p)) ; see ccl bug 978
2862 #+(or cmucl scl) (ext:unix-namestring p nil)
2863 #+sbcl (sb-ext:native-namestring p)
2864 #-(or clozure cmucl sbcl scl)
2865 (os-cond
2866 ((os-unix-p) (unix-namestring p))
2867 (t (namestring p))))))
2868
2869 (defun parse-native-namestring (string &rest constraints &key ensure-directory &allow-other-keys)
2870 "From a native namestring suitable for use by the operating system, return
2871 a CL pathname satisfying all the specified constraints as per ENSURE-PATHNAME"
2872 (check-type string (or string null))
2873 (let* ((pathname
2874 (when string
2875 (with-pathname-defaults ()
2876 #+clozure (ccl:native-to-pathname string)
2877 #+cmucl (uiop/os::parse-unix-namestring* string)
2878 #+sbcl (sb-ext:parse-native-namestring string)
2879 #+scl (lisp::parse-unix-namestring string)
2880 #-(or clozure cmucl sbcl scl)
2881 (os-cond
2882 ((os-unix-p) (parse-unix-namestring string :ensure-directory ensure-directory))
2883 (t (parse-namestring string))))))
2884 (pathname
2885 (if ensure-directory
2886 (and pathname (ensure-directory-pathname pathname))
2887 pathname)))
2888 (apply 'ensure-pathname pathname constraints))))
2889
2890
2891 ;;; Probing the filesystem
2892 (with-upgradability ()
2893 (defun truename* (p)
2894 "Nicer variant of TRUENAME that plays well with NIL, avoids logical pathname contexts, and tries both files and directories"
2895 (when p
2896 (when (stringp p) (setf p (with-pathname-defaults () (parse-namestring p))))
2897 (values
2898 (or (ignore-errors (truename p))
2899 ;; this is here because trying to find the truename of a directory pathname WITHOUT supplying
2900 ;; a trailing directory separator, causes an error on some lisps.
2901 #+(or clisp gcl) (if-let (d (ensure-directory-pathname p nil)) (ignore-errors (truename d)))))))
2902
2903 (defun safe-file-write-date (pathname)
2904 "Safe variant of FILE-WRITE-DATE that may return NIL rather than raise an error."
2905 ;; If FILE-WRITE-DATE returns NIL, it's possible that
2906 ;; the user or some other agent has deleted an input file.
2907 ;; Also, generated files will not exist at the time planning is done
2908 ;; and calls compute-action-stamp which calls safe-file-write-date.
2909 ;; So it is very possible that we can't get a valid file-write-date,
2910 ;; and we can survive and we will continue the planning
2911 ;; as if the file were very old.
2912 ;; (or should we treat the case in a different, special way?)
2913 (and pathname
2914 (handler-case (file-write-date (physicalize-pathname pathname))
2915 (file-error () nil))))
2916
2917 (defun probe-file* (p &key truename)
2918 "when given a pathname P (designated by a string as per PARSE-NAMESTRING),
2919 probes the filesystem for a file or directory with given pathname.
2920 If it exists, return its truename is ENSURE-PATHNAME is true,
2921 or the original (parsed) pathname if it is false (the default)."
2922 (values
2923 (ignore-errors
2924 (setf p (funcall 'ensure-pathname p
2925 :namestring :lisp
2926 :ensure-physical t
2927 :ensure-absolute t :defaults 'get-pathname-defaults
2928 :want-non-wild t
2929 :on-error nil))
2930 (when p
2931 #+allegro
2932 (probe-file p :follow-symlinks truename)
2933 #+gcl
2934 (if truename
2935 (truename* p)
2936 (let ((kind (car (si::stat p))))
2937 (when (eq kind :link)
2938 (setf kind (ignore-errors (car (si::stat (truename* p))))))
2939 (ecase kind
2940 ((nil) nil)
2941 ((:file :link)
2942 (cond
2943 ((file-pathname-p p) p)
2944 ((directory-pathname-p p)
2945 (subpathname p (car (last (pathname-directory p)))))))
2946 (:directory (ensure-directory-pathname p)))))
2947 #+clisp
2948 #.(let* ((fs (or #-os-windows (find-symbol* '#:file-stat :posix nil)))
2949 (pp (find-symbol* '#:probe-pathname :ext nil)))
2950 `(if truename
2951 ,(if pp
2952 `(values (,pp p))
2953 '(or (truename* p)
2954 (truename* (ignore-errors (ensure-directory-pathname p)))))
2955 ,(cond
2956 (fs `(and (,fs p) p))
2957 (pp `(nth-value 1 (,pp p)))
2958 (t '(or (and (truename* p) p)
2959 (if-let (d (ensure-directory-pathname p))
2960 (and (truename* d) d)))))))
2961 #-(or allegro clisp gcl)
2962 (if truename
2963 (probe-file p)
2964 (and
2965 #+(or cmucl scl) (unix:unix-stat (ext:unix-namestring p))
2966 #+(and lispworks unix) (system:get-file-stat p)
2967 #+sbcl (sb-unix:unix-stat (sb-ext:native-namestring p))
2968 #-(or cmucl (and lispworks unix) sbcl scl) (file-write-date p)
2969 p))))))
2970
2971 (defun directory-exists-p (x)
2972 "Is X the name of a directory that exists on the filesystem?"
2973 #+allegro
2974 (excl:probe-directory x)
2975 #+clisp
2976 (handler-case (ext:probe-directory x)
2977 (sys::simple-file-error ()
2978 nil))
2979 #-(or allegro clisp)
2980 (let ((p (probe-file* x :truename t)))
2981 (and (directory-pathname-p p) p)))
2982
2983 (defun file-exists-p (x)
2984 "Is X the name of a file that exists on the filesystem?"
2985 (let ((p (probe-file* x :truename t)))
2986 (and (file-pathname-p p) p)))
2987
2988 (defun directory* (pathname-spec &rest keys &key &allow-other-keys)
2989 "Return a list of the entries in a directory by calling DIRECTORY.
2990 Try to override the defaults to not resolving symlinks, if implementation allows."
2991 (apply 'directory pathname-spec
2992 (append keys '#.(or #+allegro '(:directories-are-files nil :follow-symbolic-links nil)
2993 #+(or clozure digitool) '(:follow-links nil)
2994 #+clisp '(:circle t :if-does-not-exist :ignore)
2995 #+(or cmucl scl) '(:follow-links nil :truenamep nil)
2996 #+lispworks '(:link-transparency nil)
2997 #+sbcl (when (find-symbol* :resolve-symlinks '#:sb-impl nil)
2998 '(:resolve-symlinks nil))))))
2999
3000 (defun filter-logical-directory-results (directory entries merger)
3001 "If DIRECTORY isn't a logical pathname, return ENTRIES. If it is,
3002 given ENTRIES in the DIRECTORY, remove the entries which are physical yet
3003 when transformed by MERGER have a different TRUENAME.
3004 Also remove duplicates as may appear with some translation rules.
3005 This function is used as a helper to DIRECTORY-FILES to avoid invalid entries
3006 when using logical-pathnames."
3007 (if (logical-pathname-p directory)
3008 (remove-duplicates ;; on CLISP, querying ~/ will return duplicates
3009 ;; Try hard to not resolve logical-pathname into physical pathnames;
3010 ;; otherwise logical-pathname users/lovers will be disappointed.
3011 ;; If directory* could use some implementation-dependent magic,
3012 ;; we will have logical pathnames already; otherwise,
3013 ;; we only keep pathnames for which specifying the name and
3014 ;; translating the LPN commute.
3015 (loop :for f :in entries
3016 :for p = (or (and (logical-pathname-p f) f)
3017 (let* ((u (ignore-errors (call-function merger f))))
3018 ;; The first u avoids a cumbersome (truename u) error.
3019 ;; At this point f should already be a truename,
3020 ;; but isn't quite in CLISP, for it doesn't have :version :newest
3021 (and u (equal (truename* u) (truename* f)) u)))
3022 :when p :collect p)
3023 :test 'pathname-equal)
3024 entries))
3025
3026 (defun directory-files (directory &optional (pattern *wild-file-for-directory*))
3027 "Return a list of the files in a directory according to the PATTERN.
3028 Subdirectories should NOT be returned.
3029 PATTERN defaults to a pattern carefully chosen based on the implementation;
3030 override the default at your own risk.
3031 DIRECTORY-FILES tries NOT to resolve symlinks if the implementation permits this,
3032 but the behavior in presence of symlinks is not portable. Use IOlib to handle such situations."
3033 (let ((dir (pathname directory)))
3034 (when (logical-pathname-p dir)
3035 ;; Because of the filtering we do below,
3036 ;; logical pathnames have restrictions on wild patterns.
3037 ;; Not that the results are very portable when you use these patterns on physical pathnames.
3038 (when (wild-pathname-p dir)
3039 (error "Invalid wild pattern in logical directory ~S" directory))
3040 (unless (member (pathname-directory pattern) '(() (:relative)) :test 'equal)
3041 (error "Invalid file pattern ~S for logical directory ~S" pattern directory))
3042 (setf pattern (make-pathname-logical pattern (pathname-host dir))))
3043 (let* ((pat (merge-pathnames* pattern dir))
3044 (entries (ignore-errors (directory* pat))))
3045 (remove-if 'directory-pathname-p
3046 (filter-logical-directory-results
3047 directory entries
3048 #'(lambda (f)
3049 (make-pathname :defaults dir
3050 :name (make-pathname-component-logical (pathname-name f))
3051 :type (make-pathname-component-logical (pathname-type f))
3052 :version (make-pathname-component-logical (pathname-version f)))))))))
3053
3054 (defun subdirectories (directory)
3055 "Given a DIRECTORY pathname designator, return a list of the subdirectories under it.
3056 The behavior in presence of symlinks is not portable. Use IOlib to handle such situations."
3057 (let* ((directory (ensure-directory-pathname directory))
3058 #-(or abcl cormanlisp genera xcl)
3059 (wild (merge-pathnames*
3060 #-(or abcl allegro cmucl lispworks sbcl scl xcl)
3061 *wild-directory*
3062 #+(or abcl allegro cmucl lispworks sbcl scl xcl) "*.*"
3063 directory))
3064 (dirs
3065 #-(or abcl cormanlisp genera xcl)
3066 (ignore-errors
3067 (directory* wild . #.(or #+clozure '(:directories t :files nil)
3068 #+mcl '(:directories t))))
3069 #+(or abcl xcl) (system:list-directory directory)
3070 #+cormanlisp (cl::directory-subdirs directory)
3071 #+genera (handler-case (fs:directory-list directory) (fs:directory-not-found () nil)))
3072 #+(or abcl allegro cmucl genera lispworks sbcl scl xcl)
3073 (dirs (loop :for x :in dirs
3074 :for d = #+(or abcl xcl) (extensions:probe-directory x)
3075 #+allegro (excl:probe-directory x)
3076 #+(or cmucl sbcl scl) (directory-pathname-p x)
3077 #+genera (getf (cdr x) :directory)
3078 #+lispworks (lw:file-directory-p x)
3079 :when d :collect #+(or abcl allegro xcl) (ensure-directory-pathname d)
3080 #+genera (ensure-directory-pathname (first x))
3081 #+(or cmucl lispworks sbcl scl) x)))
3082 (filter-logical-directory-results
3083 directory dirs
3084 (let ((prefix (or (normalize-pathname-directory-component (pathname-directory directory))
3085 '(:absolute)))) ; because allegro returns NIL for #p"FOO:"
3086 #'(lambda (d)
3087 (let ((dir (normalize-pathname-directory-component (pathname-directory d))))
3088 (and (consp dir) (consp (cdr dir))
3089 (make-pathname
3090 :defaults directory :name nil :type nil :version nil
3091 :directory (append prefix (make-pathname-component-logical (last dir)))))))))))
3092
3093 (defun collect-sub*directories (directory collectp recursep collector)
3094 "Given a DIRECTORY, when COLLECTP returns true when CALL-FUNCTION'ed with the directory,
3095 call-function the COLLECTOR function designator on the directory,
3096 and recurse each of its subdirectories on which the RECURSEP returns true when CALL-FUNCTION'ed with them.
3097 This function will thus let you traverse a filesystem hierarchy,
3098 superseding the functionality of CL-FAD:WALK-DIRECTORY.
3099 The behavior in presence of symlinks is not portable. Use IOlib to handle such situations."
3100 (when (call-function collectp directory)
3101 (call-function collector directory)
3102 (dolist (subdir (subdirectories directory))
3103 (when (call-function recursep subdir)
3104 (collect-sub*directories subdir collectp recursep collector))))))
3105
3106 ;;; Resolving symlinks somewhat
3107 (with-upgradability ()
3108 (defun truenamize (pathname)
3109 "Resolve as much of a pathname as possible"
3110 (block nil
3111 (when (typep pathname '(or null logical-pathname)) (return pathname))
3112 (let ((p pathname))
3113 (unless (absolute-pathname-p p)
3114 (setf p (or (absolute-pathname-p (ensure-absolute-pathname p 'get-pathname-defaults nil))
3115 (return p))))
3116 (when (logical-pathname-p p) (return p))
3117 (let ((found (probe-file* p :truename t)))
3118 (when found (return found)))
3119 (let* ((directory (normalize-pathname-directory-component (pathname-directory p)))
3120 (up-components (reverse (rest directory)))
3121 (down-components ()))
3122 (assert (eq :absolute (first directory)))
3123 (loop :while up-components :do
3124 (if-let (parent
3125 (ignore-errors
3126 (probe-file* (make-pathname :directory `(:absolute ,@(reverse up-components))
3127 :name nil :type nil :version nil :defaults p))))
3128 (if-let (simplified
3129 (ignore-errors
3130 (merge-pathnames*
3131 (make-pathname :directory `(:relative ,@down-components)
3132 :defaults p)
3133 (ensure-directory-pathname parent))))
3134 (return simplified)))
3135 (push (pop up-components) down-components)
3136 :finally (return p))))))
3137
3138 (defun resolve-symlinks (path)
3139 "Do a best effort at resolving symlinks in PATH, returning a partially or totally resolved PATH."
3140 #-allegro (truenamize path)
3141 #+allegro
3142 (if (physical-pathname-p path)
3143 (or (ignore-errors (excl:pathname-resolve-symbolic-links path)) path)
3144 path))
3145
3146 (defvar *resolve-symlinks* t
3147 "Determine whether or not ASDF resolves symlinks when defining systems.
3148 Defaults to T.")
3149
3150 (defun resolve-symlinks* (path)
3151 "RESOLVE-SYMLINKS in PATH iff *RESOLVE-SYMLINKS* is T (the default)."
3152 (if *resolve-symlinks*
3153 (and path (resolve-symlinks path))
3154 path)))
3155
3156
3157 ;;; Check pathname constraints
3158 (with-upgradability ()
3159 (defun ensure-pathname
3160 (pathname &key
3161 on-error
3162 defaults type dot-dot namestring
3163 empty-is-nil
3164 want-pathname
3165 want-logical want-physical ensure-physical
3166 want-relative want-absolute ensure-absolute ensure-subpath
3167 want-non-wild want-wild wilden
3168 want-file want-directory ensure-directory
3169 want-existing ensure-directories-exist
3170 truename resolve-symlinks truenamize
3171 &aux (p pathname)) ;; mutable working copy, preserve original
3172 "Coerces its argument into a PATHNAME,
3173 optionally doing some transformations and checking specified constraints.
3174
3175 If the argument is NIL, then NIL is returned unless the WANT-PATHNAME constraint is specified.
3176
3177 If the argument is a STRING, it is first converted to a pathname via
3178 PARSE-UNIX-NAMESTRING, PARSE-NAMESTRING or PARSE-NATIVE-NAMESTRING respectively
3179 depending on the NAMESTRING argument being :UNIX, :LISP or :NATIVE respectively,
3180 or else by using CALL-FUNCTION on the NAMESTRING argument;
3181 if :UNIX is specified (or NIL, the default, which specifies the same thing),
3182 then PARSE-UNIX-NAMESTRING it is called with the keywords
3183 DEFAULTS TYPE DOT-DOT ENSURE-DIRECTORY WANT-RELATIVE, and
3184 the result is optionally merged into the DEFAULTS if ENSURE-ABSOLUTE is true.
3185
3186 The pathname passed or resulting from parsing the string
3187 is then subjected to all the checks and transformations below are run.
3188
3189 Each non-nil constraint argument can be one of the symbols T, ERROR, CERROR or IGNORE.
3190 The boolean T is an alias for ERROR.
3191 ERROR means that an error will be raised if the constraint is not satisfied.
3192 CERROR means that an continuable error will be raised if the constraint is not satisfied.
3193 IGNORE means just return NIL instead of the pathname.
3194
3195 The ON-ERROR argument, if not NIL, is a function designator (as per CALL-FUNCTION)
3196 that will be called with the the following arguments:
3197 a generic format string for ensure pathname, the pathname,
3198 the keyword argument corresponding to the failed check or transformation,
3199 a format string for the reason ENSURE-PATHNAME failed,
3200 and a list with arguments to that format string.
3201 If ON-ERROR is NIL, ERROR is used instead, which does the right thing.
3202 You could also pass (CERROR \"CONTINUE DESPITE FAILED CHECK\").
3203
3204 The transformations and constraint checks are done in this order,
3205 which is also the order in the lambda-list:
3206
3207 EMPTY-IS-NIL returns NIL if the argument is an empty string.
3208 WANT-PATHNAME checks that pathname (after parsing if needed) is not null.
3209 Otherwise, if the pathname is NIL, ensure-pathname returns NIL.
3210 WANT-LOGICAL checks that pathname is a LOGICAL-PATHNAME
3211 WANT-PHYSICAL checks that pathname is not a LOGICAL-PATHNAME
3212 ENSURE-PHYSICAL ensures that pathname is physical via TRANSLATE-LOGICAL-PATHNAME
3213 WANT-RELATIVE checks that pathname has a relative directory component
3214 WANT-ABSOLUTE checks that pathname does have an absolute directory component
3215 ENSURE-ABSOLUTE merges with the DEFAULTS, then checks again
3216 that the result absolute is an absolute pathname indeed.
3217 ENSURE-SUBPATH checks that the pathname is a subpath of the DEFAULTS.
3218 WANT-FILE checks that pathname has a non-nil FILE component
3219 WANT-DIRECTORY checks that pathname has nil FILE and TYPE components
3220 ENSURE-DIRECTORY uses ENSURE-DIRECTORY-PATHNAME to interpret
3221 any file and type components as being actually a last directory component.
3222 WANT-NON-WILD checks that pathname is not a wild pathname
3223 WANT-WILD checks that pathname is a wild pathname
3224 WILDEN merges the pathname with **/*.*.* if it is not wild
3225 WANT-EXISTING checks that a file (or directory) exists with that pathname.
3226 ENSURE-DIRECTORIES-EXIST creates any parent directory with ENSURE-DIRECTORIES-EXIST.
3227 TRUENAME replaces the pathname by its truename, or errors if not possible.
3228 RESOLVE-SYMLINKS replaces the pathname by a variant with symlinks resolved by RESOLVE-SYMLINKS.
3229 TRUENAMIZE uses TRUENAMIZE to resolve as many symlinks as possible."
3230 (block nil
3231 (flet ((report-error (keyword description &rest arguments)
3232 (call-function (or on-error 'error)
3233 "Invalid pathname ~S: ~*~?"
3234 pathname keyword description arguments)))
3235 (macrolet ((err (constraint &rest arguments)
3236 `(report-error ',(intern* constraint :keyword) ,@arguments))
3237 (check (constraint condition &rest arguments)
3238 `(when ,constraint
3239 (unless ,condition (err ,constraint ,@arguments))))
3240 (transform (transform condition expr)
3241 `(when ,transform
3242 (,@(if condition `(when ,condition) '(progn))
3243 (setf p ,expr)))))
3244 (etypecase p
3245 ((or null pathname))
3246 (string
3247 (when (and (emptyp p) empty-is-nil)
3248 (return-from ensure-pathname nil))
3249 (setf p (case namestring
3250 ((:unix nil)
3251 (parse-unix-namestring
3252 p :defaults defaults :type type :dot-dot dot-dot
3253 :ensure-directory ensure-directory :want-relative want-relative))
3254 ((:native)
3255 (parse-native-namestring p))
3256 ((:lisp)
3257 (parse-namestring p))
3258 (t
3259 (call-function namestring p))))))
3260 (etypecase p
3261 (pathname)
3262 (null
3263 (check want-pathname (pathnamep p) "Expected a pathname, not NIL")
3264 (return nil)))
3265 (check want-logical (logical-pathname-p p) "Expected a logical pathname")
3266 (check want-physical (physical-pathname-p p) "Expected a physical pathname")
3267 (transform ensure-physical () (physicalize-pathname p))
3268 (check ensure-physical (physical-pathname-p p) "Could not translate to a physical pathname")
3269 (check want-relative (relative-pathname-p p) "Expected a relative pathname")
3270 (check want-absolute (absolute-pathname-p p) "Expected an absolute pathname")
3271 (transform ensure-absolute (not (absolute-pathname-p p))
3272 (ensure-absolute-pathname p defaults (list #'report-error :ensure-absolute "~@?")))
3273 (check ensure-absolute (absolute-pathname-p p)
3274 "Could not make into an absolute pathname even after merging with ~S" defaults)
3275 (check ensure-subpath (absolute-pathname-p defaults)
3276 "cannot be checked to be a subpath of non-absolute pathname ~S" defaults)
3277 (check ensure-subpath (subpathp p defaults) "is not a sub pathname of ~S" defaults)
3278 (check want-file (file-pathname-p p) "Expected a file pathname")
3279 (check want-directory (directory-pathname-p p) "Expected a directory pathname")
3280 (transform ensure-directory (not (directory-pathname-p p)) (ensure-directory-pathname p))
3281 (check want-non-wild (not (wild-pathname-p p)) "Expected a non-wildcard pathname")
3282 (check want-wild (wild-pathname-p p) "Expected a wildcard pathname")
3283 (transform wilden (not (wild-pathname-p p)) (wilden p))
3284 (when want-existing
3285 (let ((existing (probe-file* p :truename truename)))
3286 (if existing
3287 (when truename
3288 (return existing))
3289 (err want-existing "Expected an existing pathname"))))
3290 (when ensure-directories-exist (ensure-directories-exist p))
3291 (when truename
3292 (let ((truename (truename* p)))
3293 (if truename
3294 (return truename)
3295 (err truename "Can't get a truename for pathname"))))
3296 (transform resolve-symlinks () (resolve-symlinks p))
3297 (transform truenamize () (truenamize p))
3298 p)))))
3299
3300
3301 ;;; Pathname defaults
3302 (with-upgradability ()
3303 (defun get-pathname-defaults (&optional (defaults *default-pathname-defaults*))
3304 "Find the actual DEFAULTS to use for pathnames, including
3305 resolving them with respect to GETCWD if the DEFAULTS were relative"
3306 (or (absolute-pathname-p defaults)
3307 (merge-pathnames* defaults (getcwd))))
3308
3309 (defun call-with-current-directory (dir thunk)
3310 "call the THUNK in a context where the current directory was changed to DIR, if not NIL.
3311 Note that this operation is usually NOT thread-safe."
3312 (if dir
3313 (let* ((dir (resolve-symlinks* (get-pathname-defaults (pathname-directory-pathname dir))))
3314 (cwd (getcwd))
3315 (*default-pathname-defaults* dir))
3316 (chdir dir)
3317 (unwind-protect
3318 (funcall thunk)
3319 (chdir cwd)))
3320 (funcall thunk)))
3321
3322 (defmacro with-current-directory ((&optional dir) &body body)
3323 "Call BODY while the POSIX current working directory is set to DIR"
3324 `(call-with-current-directory ,dir #'(lambda () ,@body))))
3325
3326
3327 ;;; Environment pathnames
3328 (with-upgradability ()
3329 (defun inter-directory-separator ()
3330 "What character does the current OS conventionally uses to separate directories?"
3331 (os-cond ((os-unix-p) #\:) (t #\;)))
3332
3333 (defun split-native-pathnames-string (string &rest constraints &key &allow-other-keys)
3334 "Given a string of pathnames specified in native OS syntax, separate them in a list,
3335 check constraints and normalize each one as per ENSURE-PATHNAME,
3336 where an empty string denotes NIL."
3337 (loop :for namestring :in (split-string string :separator (string (inter-directory-separator)))
3338 :collect (unless (emptyp namestring) (apply 'parse-native-namestring namestring constraints))))
3339
3340 (defun getenv-pathname (x &rest constraints &key ensure-directory want-directory on-error &allow-other-keys)
3341 "Extract a pathname from a user-configured environment variable, as per native OS,
3342 check constraints and normalize as per ENSURE-PATHNAME."
3343 ;; For backward compatibility with ASDF 2, want-directory implies ensure-directory
3344 (apply 'parse-native-namestring (getenvp x)
3345 :ensure-directory (or ensure-directory want-directory)
3346 :on-error (or on-error
3347 `(error "In (~S ~S), invalid pathname ~*~S: ~*~?" getenv-pathname ,x))
3348 constraints))
3349 (defun getenv-pathnames (x &rest constraints &key on-error &allow-other-keys)
3350 "Extract a list of pathname from a user-configured environment variable, as per native OS,
3351 check constraints and normalize each one as per ENSURE-PATHNAME.
3352 Any empty entries in the environment variable X will be returned as NILs."
3353 (unless (getf constraints :empty-is-nil t)
3354 (error "Cannot have EMPTY-IS-NIL false for GETENV-PATHNAMES."))
3355 (apply 'split-native-pathnames-string (getenvp x)
3356 :on-error (or on-error
3357 `(error "In (~S ~S), invalid pathname ~*~S: ~*~?" getenv-pathnames ,x))
3358 :empty-is-nil t
3359 constraints))
3360 (defun getenv-absolute-directory (x)
3361 "Extract an absolute directory pathname from a user-configured environment variable,
3362 as per native OS"
3363 (getenv-pathname x :want-absolute t :ensure-directory t))
3364 (defun getenv-absolute-directories (x)
3365 "Extract a list of absolute directories from a user-configured environment variable,
3366 as per native OS. Any empty entries in the environment variable X will be returned as
3367 NILs."
3368 (getenv-pathnames x :want-absolute t :ensure-directory t))
3369
3370 (defun lisp-implementation-directory (&key truename)
3371 "Where are the system files of the current installation of the CL implementation?"
3372 (declare (ignorable truename))
3373 (let ((dir
3374 #+abcl extensions:*lisp-home*
3375 #+(or allegro clasp ecl mkcl) #p"SYS:"
3376 #+clisp custom:*lib-directory*
3377 #+clozure #p"ccl:"
3378 #+cmucl (ignore-errors (pathname-parent-directory-pathname (truename #p"modules:")))
3379 #+gcl system::*system-directory*
3380 #+lispworks lispworks:*lispworks-directory*
3381 #+sbcl (if-let (it (find-symbol* :sbcl-homedir-pathname :sb-int nil))
3382 (funcall it)
3383 (getenv-pathname "SBCL_HOME" :ensure-directory t))
3384 #+scl (ignore-errors (pathname-parent-directory-pathname (truename #p"file://modules/")))
3385 #+xcl ext:*xcl-home*))
3386 (if (and dir truename)
3387 (truename* dir)
3388 dir)))
3389
3390 (defun lisp-implementation-pathname-p (pathname)
3391 "Is the PATHNAME under the current installation of the CL implementation?"
3392 ;; Other builtin systems are those under the implementation directory
3393 (and (when pathname
3394 (if-let (impdir (lisp-implementation-directory))
3395 (or (subpathp pathname impdir)
3396 (when *resolve-symlinks*
3397 (if-let (truename (truename* pathname))
3398 (if-let (trueimpdir (truename* impdir))
3399 (subpathp truename trueimpdir)))))))
3400 t)))
3401
3402
3403 ;;; Simple filesystem operations
3404 (with-upgradability ()
3405 (defun ensure-all-directories-exist (pathnames)
3406 "Ensure that for every pathname in PATHNAMES, we ensure its directories exist"
3407 (dolist (pathname pathnames)
3408 (when pathname
3409 (ensure-directories-exist (physicalize-pathname pathname)))))
3410
3411 (defun delete-file-if-exists (x)
3412 "Delete a file X if it already exists"
3413 (when x (handler-case (delete-file x) (file-error () nil))))
3414
3415 (defun rename-file-overwriting-target (source target)
3416 "Rename a file, overwriting any previous file with the TARGET name,
3417 in an atomic way if the implementation allows."
3418 (let ((source (ensure-pathname source :namestring :lisp :ensure-physical t :want-file t))
3419 (target (ensure-pathname target :namestring :lisp :ensure-physical t :want-file t)))
3420 #+clisp ;; in recent enough versions of CLISP, :if-exists :overwrite would make it atomic
3421 (progn (funcall 'require "syscalls")
3422 (symbol-call :posix :copy-file source target :method :rename))
3423 #+(and sbcl os-windows) (delete-file-if-exists target) ;; not atomic
3424 #-clisp
3425 (rename-file source target
3426 #+(or clasp clozure ecl) :if-exists
3427 #+clozure :rename-and-delete #+(or clasp ecl) t)))
3428
3429 (defun delete-empty-directory (directory-pathname)
3430 "Delete an empty directory"
3431 #+(or abcl digitool gcl) (delete-file directory-pathname)
3432 #+allegro (excl:delete-directory directory-pathname)
3433 #+clisp (ext:delete-directory directory-pathname)
3434 #+clozure (ccl::delete-empty-directory directory-pathname)
3435 #+(or cmucl scl) (multiple-value-bind (ok errno)
3436 (unix:unix-rmdir (native-namestring directory-pathname))
3437 (unless ok
3438 #+cmucl (error "Error number ~A when trying to delete directory ~A"
3439 errno directory-pathname)
3440 #+scl (error "~@<Error deleting ~S: ~A~@:>"
3441 directory-pathname (unix:get-unix-error-msg errno))))
3442 #+cormanlisp (win32:delete-directory directory-pathname)
3443 #+(or clasp ecl) (si:rmdir directory-pathname)
3444 #+genera (fs:delete-directory directory-pathname)
3445 #+lispworks (lw:delete-directory directory-pathname)
3446 #+mkcl (mkcl:rmdir directory-pathname)
3447 #+sbcl #.(if-let (dd (find-symbol* :delete-directory :sb-ext nil))
3448 `(,dd directory-pathname) ;; requires SBCL 1.0.44 or later
3449 `(progn (require :sb-posix) (symbol-call :sb-posix :rmdir directory-pathname)))
3450 #+xcl (symbol-call :uiop :run-program `("rmdir" ,(native-namestring directory-pathname)))
3451 #-(or abcl allegro clasp clisp clozure cmucl cormanlisp digitool ecl gcl genera lispworks mkcl sbcl scl xcl)
3452 (not-implemented-error 'delete-empty-directory "(on your platform)")) ; genera
3453
3454 (defun delete-directory-tree (directory-pathname &key (validate nil validatep) (if-does-not-exist :error))
3455 "Delete a directory including all its recursive contents, aka rm -rf.
3456
3457 To reduce the risk of infortunate mistakes, DIRECTORY-PATHNAME must be
3458 a physical non-wildcard directory pathname (not namestring).
3459
3460 If the directory does not exist, the IF-DOES-NOT-EXIST argument specifies what happens:
3461 if it is :ERROR (the default), an error is signaled, whereas if it is :IGNORE, nothing is done.
3462
3463 Furthermore, before any deletion is attempted, the DIRECTORY-PATHNAME must pass
3464 the validation function designated (as per ENSURE-FUNCTION) by the VALIDATE keyword argument
3465 which in practice is thus compulsory, and validates by returning a non-NIL result.
3466 If you're suicidal or extremely confident, just use :VALIDATE T."
3467 (check-type if-does-not-exist (member :error :ignore))
3468 (cond
3469 ((not (and (pathnamep directory-pathname) (directory-pathname-p directory-pathname)
3470 (physical-pathname-p directory-pathname) (not (wild-pathname-p directory-pathname))))
3471 (error "~S was asked to delete ~S but it is not a physical non-wildcard directory pathname"
3472 'delete-directory-tree directory-pathname))
3473 ((not validatep)
3474 (error "~S was asked to delete ~S but was not provided a validation predicate"
3475 'delete-directory-tree directory-pathname))
3476 ((not (call-function validate directory-pathname))
3477 (error "~S was asked to delete ~S but it is not valid ~@[according to ~S~]"
3478 'delete-directory-tree directory-pathname validate))
3479 ((not (directory-exists-p directory-pathname))
3480 (ecase if-does-not-exist
3481 (:error
3482 (error "~S was asked to delete ~S but the directory does not exist"
3483 'delete-directory-tree directory-pathname))
3484 (:ignore nil)))
3485 #-(or allegro cmucl clozure genera sbcl scl)
3486 ((os-unix-p) ;; On Unix, don't recursively walk the directory and delete everything in Lisp,
3487 ;; except on implementations where we can prevent DIRECTORY from following symlinks;
3488 ;; instead spawn a standard external program to do the dirty work.
3489 (symbol-call :uiop :run-program `("rm" "-rf" ,(native-namestring directory-pathname))))
3490 (t
3491 ;; On supported implementation, call supported system functions
3492 #+allegro (symbol-call :excl.osi :delete-directory-and-files
3493 directory-pathname :if-does-not-exist if-does-not-exist)
3494 #+clozure (ccl:delete-directory directory-pathname)
3495 #+genera (fs:delete-directory directory-pathname :confirm nil)
3496 #+sbcl #.(if-let (dd (find-symbol* :delete-directory :sb-ext nil))
3497 `(,dd directory-pathname :recursive t) ;; requires SBCL 1.0.44 or later
3498 '(error "~S requires SBCL 1.0.44 or later" 'delete-directory-tree))
3499 ;; Outside Unix or on CMUCL and SCL that can avoid following symlinks,
3500 ;; do things the hard way.
3501 #-(or allegro clozure genera sbcl)
3502 (let ((sub*directories
3503 (while-collecting (c)
3504 (collect-sub*directories directory-pathname t t #'c))))
3505 (dolist (d (nreverse sub*directories))
3506 (map () 'delete-file (directory-files d))
3507 (delete-empty-directory d)))))))
3508 ;;;; ---------------------------------------------------------------------------
3509 ;;;; Utilities related to streams
3510
3511 (uiop/package:define-package :uiop/stream
3512 (:nicknames :asdf/stream)
3513 (:recycle :uiop/stream :asdf/stream :asdf)
3514 (:use :uiop/common-lisp :uiop/package :uiop/utility :uiop/os :uiop/pathname :uiop/filesystem)
3515 (:export
3516 #:*default-stream-element-type*
3517 #:*stdin* #:setup-stdin #:*stdout* #:setup-stdout #:*stderr* #:setup-stderr
3518 #:detect-encoding #:*encoding-detection-hook* #:always-default-encoding
3519 #:encoding-external-format #:*encoding-external-format-hook* #:default-encoding-external-format
3520 #:*default-encoding* #:*utf-8-external-format*
3521 #:with-safe-io-syntax #:call-with-safe-io-syntax #:safe-read-from-string
3522 #:with-output #:output-string #:with-input #:input-string
3523 #:with-input-file #:call-with-input-file #:with-output-file #:call-with-output-file
3524 #:null-device-pathname #:call-with-null-input #:with-null-input
3525 #:call-with-null-output #:with-null-output
3526 #:finish-outputs #:format! #:safe-format!
3527 #:copy-stream-to-stream #:concatenate-files #:copy-file
3528 #:slurp-stream-string #:slurp-stream-lines #:slurp-stream-line
3529 #:slurp-stream-forms #:slurp-stream-form
3530 #:read-file-string #:read-file-line #:read-file-lines #:safe-read-file-line
3531 #:read-file-forms #:read-file-form #:safe-read-file-form
3532 #:eval-input #:eval-thunk #:standard-eval-thunk
3533 #:println #:writeln
3534 #:file-stream-p #:file-or-synonym-stream-p
3535 ;; Temporary files
3536 #:*temporary-directory* #:temporary-directory #:default-temporary-directory
3537 #:setup-temporary-directory
3538 #:call-with-temporary-file #:with-temporary-file
3539 #:add-pathname-suffix #:tmpize-pathname
3540 #:call-with-staging-pathname #:with-staging-pathname))
3541 (in-package :uiop/stream)
3542
3543 (with-upgradability ()
3544 (defvar *default-stream-element-type*
3545 (or #+(or abcl cmucl cormanlisp scl xcl) 'character
3546 #+lispworks 'lw:simple-char
3547 :default)
3548 "default element-type for open (depends on the current CL implementation)")
3549
3550 (defvar *stdin* *standard-input*
3551 "the original standard input stream at startup")
3552
3553 (defun setup-stdin ()
3554 (setf *stdin*
3555 #.(or #+clozure 'ccl::*stdin*
3556 #+(or cmucl scl) 'system:*stdin*
3557 #+(or clasp ecl) 'ext::+process-standard-input+
3558 #+sbcl 'sb-sys:*stdin*
3559 '*standard-input*)))
3560
3561 (defvar *stdout* *standard-output*
3562 "the original standard output stream at startup")
3563
3564 (defun setup-stdout ()
3565 (setf *stdout*
3566 #.(or #+clozure 'ccl::*stdout*
3567 #+(or cmucl scl) 'system:*stdout*
3568 #+(or clasp ecl) 'ext::+process-standard-output+
3569 #+sbcl 'sb-sys:*stdout*
3570 '*standard-output*)))
3571
3572 (defvar *stderr* *error-output*
3573 "the original error output stream at startup")
3574
3575 (defun setup-stderr ()
3576 (setf *stderr*
3577 #.(or #+allegro 'excl::*stderr*
3578 #+clozure 'ccl::*stderr*
3579 #+(or cmucl scl) 'system:*stderr*
3580 #+(or clasp ecl) 'ext::+process-error-output+
3581 #+sbcl 'sb-sys:*stderr*
3582 '*error-output*)))
3583
3584 ;; Run them now. In image.lisp, we'll register them to be run at image restart.
3585 (setup-stdin) (setup-stdout) (setup-stderr))
3586
3587
3588 ;;; Encodings (mostly hooks only; full support requires asdf-encodings)
3589 (with-upgradability ()
3590 (defparameter *default-encoding*
3591 ;; preserve explicit user changes to something other than the legacy default :default
3592 (or (if-let (previous (and (boundp '*default-encoding*) (symbol-value '*default-encoding*)))
3593 (unless (eq previous :default) previous))
3594 :utf-8)
3595 "Default encoding for source files.
3596 The default value :utf-8 is the portable thing.
3597 The legacy behavior was :default.
3598 If you (asdf:load-system :asdf-encodings) then
3599 you will have autodetection via *encoding-detection-hook* below,
3600 reading emacs-style -*- coding: utf-8 -*- specifications,
3601 and falling back to utf-8 or latin1 if nothing is specified.")
3602
3603 (defparameter *utf-8-external-format*
3604 (if (featurep :asdf-unicode)
3605 (or #+clisp charset:utf-8 :utf-8)
3606 :default)
3607 "Default :external-format argument to pass to CL:OPEN and also
3608 CL:LOAD or CL:COMPILE-FILE to best process a UTF-8 encoded file.
3609 On modern implementations, this will decode UTF-8 code points as CL characters.
3610 On legacy implementations, it may fall back on some 8-bit encoding,
3611 with non-ASCII code points being read as several CL characters;
3612 hopefully, if done consistently, that won't affect program behavior too much.")
3613
3614 (defun always-default-encoding (pathname)
3615 "Trivial function to use as *encoding-detection-hook*,
3616 always 'detects' the *default-encoding*"
3617 (declare (ignore pathname))
3618 *default-encoding*)
3619
3620 (defvar *encoding-detection-hook* #'always-default-encoding
3621 "Hook for an extension to define a function to automatically detect a file's encoding")
3622
3623 (defun detect-encoding (pathname)
3624 "Detects the encoding of a specified file, going through user-configurable hooks"
3625 (if (and pathname (not (directory-pathname-p pathname)) (probe-file* pathname))
3626 (funcall *encoding-detection-hook* pathname)
3627 *default-encoding*))
3628
3629 (defun default-encoding-external-format (encoding)
3630 "Default, ignorant, function to transform a character ENCODING as a
3631 portable keyword to an implementation-dependent EXTERNAL-FORMAT specification.
3632 Load system ASDF-ENCODINGS to hook in a better one."
3633 (case encoding
3634 (:default :default) ;; for backward-compatibility only. Explicit usage discouraged.
3635 (:utf-8 *utf-8-external-format*)
3636 (otherwise
3637 (cerror "Continue using :external-format :default" (compatfmt "~@<Your ASDF component is using encoding ~S but it isn't recognized. Your system should :defsystem-depends-on (:asdf-encodings).~:>") encoding)
3638 :default)))
3639
3640 (defvar *encoding-external-format-hook*
3641 #'default-encoding-external-format
3642 "Hook for an extension (e.g. ASDF-ENCODINGS) to define a better mapping
3643 from non-default encodings to and implementation-defined external-format's")
3644
3645 (defun encoding-external-format (encoding)
3646 "Transform a portable ENCODING keyword to an implementation-dependent EXTERNAL-FORMAT,
3647 going through all the proper hooks."
3648 (funcall *encoding-external-format-hook* (or encoding *default-encoding*))))
3649
3650
3651 ;;; Safe syntax
3652 (with-upgradability ()
3653 (defvar *standard-readtable* (with-standard-io-syntax *readtable*)
3654 "The standard readtable, implementing the syntax specified by the CLHS.
3655 It must never be modified, though only good implementations will even enforce that.")
3656
3657 (defmacro with-safe-io-syntax ((&key (package :cl)) &body body)
3658 "Establish safe CL reader options around the evaluation of BODY"
3659 `(call-with-safe-io-syntax #'(lambda () (let ((*package* (find-package ,package))) ,@body))))
3660
3661 (defun call-with-safe-io-syntax (thunk &key (package :cl))
3662 (with-standard-io-syntax
3663 (let ((*package* (find-package package))
3664 (*read-default-float-format* 'double-float)
3665 (*print-readably* nil)
3666 (*read-eval* nil))
3667 (funcall thunk))))
3668
3669 (defun safe-read-from-string (string &key (package :cl) (eof-error-p t) eof-value (start 0) end preserve-whitespace)
3670 "Read from STRING using a safe syntax, as per WITH-SAFE-IO-SYNTAX"
3671 (with-safe-io-syntax (:package package)
3672 (read-from-string string eof-error-p eof-value :start start :end end :preserve-whitespace preserve-whitespace))))
3673
3674 ;;; Output helpers
3675 (with-upgradability ()
3676 (defun call-with-output-file (pathname thunk
3677 &key
3678 (element-type *default-stream-element-type*)
3679 (external-format *utf-8-external-format*)
3680 (if-exists :error)
3681 (if-does-not-exist :create))
3682 "Open FILE for input with given recognizes options, call THUNK with the resulting stream.
3683 Other keys are accepted but discarded."
3684 (with-open-file (s pathname :direction :output
3685 :element-type element-type
3686 :external-format external-format
3687 :if-exists if-exists
3688 :if-does-not-exist if-does-not-exist)
3689 (funcall thunk s)))
3690
3691 (defmacro with-output-file ((var pathname &rest keys
3692 &key element-type external-format if-exists if-does-not-exist)
3693 &body body)
3694 (declare (ignore element-type external-format if-exists if-does-not-exist))
3695 `(call-with-output-file ,pathname #'(lambda (,var) ,@body) ,@keys))
3696
3697 (defun call-with-output (output function &key keys)
3698 "Calls FUNCTION with an actual stream argument,
3699 behaving like FORMAT with respect to how stream designators are interpreted:
3700 If OUTPUT is a STREAM, use it as the stream.
3701 If OUTPUT is NIL, use a STRING-OUTPUT-STREAM as the stream, and return the resulting string.
3702 If OUTPUT is T, use *STANDARD-OUTPUT* as the stream.
3703 If OUTPUT is a STRING with a fill-pointer, use it as a string-output-stream.
3704 If OUTPUT is a PATHNAME, open the file and write to it, passing KEYS to WITH-OUTPUT-FILE
3705 -- this latter as an extension since ASDF 3.1.
3706 Otherwise, signal an error."
3707 (etypecase output
3708 (null
3709 (with-output-to-string (stream) (funcall function stream)))
3710 ((eql t)
3711 (funcall function *standard-output*))
3712 (stream
3713 (funcall function output))
3714 (string
3715 (assert (fill-pointer output))
3716 (with-output-to-string (stream output) (funcall function stream)))
3717 (pathname
3718 (apply 'call-with-output-file output function keys))))
3719
3720 (defmacro with-output ((output-var &optional (value output-var)) &body body)
3721 "Bind OUTPUT-VAR to an output stream, coercing VALUE (default: previous binding of OUTPUT-VAR)
3722 as per FORMAT, and evaluate BODY within the scope of this binding."
3723 `(call-with-output ,value #'(lambda (,output-var) ,@body)))
3724
3725 (defun output-string (string &optional output)
3726 "If the desired OUTPUT is not NIL, print the string to the output; otherwise return the string"
3727 (if output
3728 (with-output (output) (princ string output))
3729 string)))
3730
3731
3732 ;;; Input helpers
3733 (with-upgradability ()
3734 (defun call-with-input-file (pathname thunk
3735 &key
3736 (element-type *default-stream-element-type*)
3737 (external-format *utf-8-external-format*)
3738 (if-does-not-exist :error))
3739 "Open FILE for input with given recognizes options, call THUNK with the resulting stream.
3740 Other keys are accepted but discarded."
3741 (with-open-file (s pathname :direction :input
3742 :element-type element-type
3743 :external-format external-format
3744 :if-does-not-exist if-does-not-exist)
3745 (funcall thunk s)))
3746
3747 (defmacro with-input-file ((var pathname &rest keys
3748 &key element-type external-format if-does-not-exist)
3749 &body body)
3750 (declare (ignore element-type external-format if-does-not-exist))
3751 `(call-with-input-file ,pathname #'(lambda (,var) ,@body) ,@keys))
3752
3753 (defun call-with-input (input function &key keys)
3754 "Calls FUNCTION with an actual stream argument, interpreting
3755 stream designators like READ, but also coercing strings to STRING-INPUT-STREAM,
3756 and PATHNAME to FILE-STREAM.
3757 If INPUT is a STREAM, use it as the stream.
3758 If INPUT is NIL, use a *STANDARD-INPUT* as the stream.
3759 If INPUT is T, use *TERMINAL-IO* as the stream.
3760 If INPUT is a STRING, use it as a string-input-stream.
3761 If INPUT is a PATHNAME, open it, passing KEYS to WITH-INPUT-FILE
3762 -- the latter is an extension since ASDF 3.1.
3763 Otherwise, signal an error."
3764 (etypecase input
3765 (null (funcall function *standard-input*))
3766 ((eql t) (funcall function *terminal-io*))
3767 (stream (funcall function input))
3768 (string (with-input-from-string (stream input) (funcall function stream)))
3769 (pathname (apply 'call-with-input-file input function keys))))
3770
3771 (defmacro with-input ((input-var &optional (value input-var)) &body body)
3772 "Bind INPUT-VAR to an input stream, coercing VALUE (default: previous binding of INPUT-VAR)
3773 as per CALL-WITH-INPUT, and evaluate BODY within the scope of this binding."
3774 `(call-with-input ,value #'(lambda (,input-var) ,@body)))
3775
3776 (defun input-string (&optional input)
3777 "If the desired INPUT is a string, return that string; otherwise slurp the INPUT into a string
3778 and return that"
3779 (if (stringp input)
3780 input
3781 (with-input (input) (funcall 'slurp-stream-string input)))))
3782
3783 ;;; Null device
3784 (with-upgradability ()
3785 (defun null-device-pathname ()
3786 "Pathname to a bit bucket device that discards any information written to it
3787 and always returns EOF when read from"
3788 (os-cond
3789 ((os-unix-p) #p"/dev/null")
3790 ((os-windows-p) #p"NUL") ;; Q: how many Lisps accept the #p"NUL:" syntax?
3791 (t (error "No /dev/null on your OS"))))
3792 (defun call-with-null-input (fun &rest keys &key element-type external-format if-does-not-exist)
3793 "Call FUN with an input stream from the null device; pass keyword arguments to OPEN."
3794 (declare (ignore element-type external-format if-does-not-exist))
3795 (apply 'call-with-input-file (null-device-pathname) fun keys))
3796 (defmacro with-null-input ((var &rest keys
3797 &key element-type external-format if-does-not-exist)
3798 &body body)
3799 (declare (ignore element-type external-format if-does-not-exist))
3800 "Evaluate BODY in a context when VAR is bound to an input stream accessing the null device.
3801 Pass keyword arguments to OPEN."
3802 `(call-with-null-input #'(lambda (,var) ,@body) ,@keys))
3803 (defun call-with-null-output (fun
3804 &key (element-type *default-stream-element-type*)
3805 (external-format *utf-8-external-format*)
3806 (if-exists :overwrite)
3807 (if-does-not-exist :error))
3808 "Call FUN with an output stream to the null device; pass keyword arguments to OPEN."
3809 (call-with-output-file
3810 (null-device-pathname) fun
3811 :element-type element-type :external-format external-format
3812 :if-exists if-exists :if-does-not-exist if-does-not-exist))
3813 (defmacro with-null-output ((var &rest keys
3814 &key element-type external-format if-does-not-exist if-exists)
3815 &body body)
3816 "Evaluate BODY in a context when VAR is bound to an output stream accessing the null device.
3817 Pass keyword arguments to OPEN."
3818 (declare (ignore element-type external-format if-exists if-does-not-exist))
3819 `(call-with-null-output #'(lambda (,var) ,@body) ,@keys)))
3820
3821 ;;; Ensure output buffers are flushed
3822 (with-upgradability ()
3823 (defun finish-outputs (&rest streams)
3824 "Finish output on the main output streams as well as any specified one.
3825 Useful for portably flushing I/O before user input or program exit."
3826 ;; CCL notably buffers its stream output by default.
3827 (dolist (s (append streams
3828 (list *stdout* *stderr* *error-output* *standard-output* *trace-output*
3829 *debug-io* *terminal-io* *query-io*)))
3830 (ignore-errors (finish-output s)))
3831 (values))
3832
3833 (defun format! (stream format &rest args)
3834 "Just like format, but call finish-outputs before and after the output."
3835 (finish-outputs stream)
3836 (apply 'format stream format args)
3837 (finish-outputs stream))
3838
3839 (defun safe-format! (stream format &rest args)
3840 "Variant of FORMAT that is safe against both
3841 dangerous syntax configuration and errors while printing."
3842 (with-safe-io-syntax ()
3843 (ignore-errors (apply 'format! stream format args))
3844 (finish-outputs stream)))) ; just in case format failed
3845
3846
3847 ;;; Simple Whole-Stream processing
3848 (with-upgradability ()
3849 (defun copy-stream-to-stream (input output &key element-type buffer-size linewise prefix)
3850 "Copy the contents of the INPUT stream into the OUTPUT stream.
3851 If LINEWISE is true, then read and copy the stream line by line, with an optional PREFIX.
3852 Otherwise, using WRITE-SEQUENCE using a buffer of size BUFFER-SIZE."
3853 (with-open-stream (input input)
3854 (if linewise
3855 (loop* :for (line eof) = (multiple-value-list (read-line input nil nil))
3856 :while line :do
3857 (when prefix (princ prefix output))
3858 (princ line output)
3859 (unless eof (terpri output))
3860 (finish-output output)
3861 (when eof (return)))
3862 (loop
3863 :with buffer-size = (or buffer-size 8192)
3864 :with buffer = (make-array (list buffer-size) :element-type (or element-type 'character))
3865 :for end = (read-sequence buffer input)
3866 :until (zerop end)
3867 :do (write-sequence buffer output :end end)
3868 (when (< end buffer-size) (return))))))
3869
3870 (defun concatenate-files (inputs output)
3871 "create a new OUTPUT file the contents of which a the concatenate of the INPUTS files."
3872 (with-open-file (o output :element-type '(unsigned-byte 8)
3873 :direction :output :if-exists :rename-and-delete)
3874 (dolist (input inputs)
3875 (with-open-file (i input :element-type '(unsigned-byte 8)
3876 :direction :input :if-does-not-exist :error)
3877 (copy-stream-to-stream i o :element-type '(unsigned-byte 8))))))
3878
3879 (defun copy-file (input output)
3880 "Copy contents of the INPUT file to the OUTPUT file"
3881 ;; Not available on LW personal edition or LW 6.0 on Mac: (lispworks:copy-file i f)
3882 #+allegro
3883 (excl.osi:copy-file input output)
3884 #+ecl
3885 (ext:copy-file input output)
3886 #-(or allegro ecl)
3887 (concatenate-files (list input) output))
3888
3889 (defun slurp-stream-string (input &key (element-type 'character) stripped)
3890 "Read the contents of the INPUT stream as a string"
3891 (let ((string
3892 (with-open-stream (input input)
3893 (with-output-to-string (output)
3894 (copy-stream-to-stream input output :element-type element-type)))))
3895 (if stripped (stripln string) string)))
3896
3897 (defun slurp-stream-lines (input &key count)
3898 "Read the contents of the INPUT stream as a list of lines, return those lines.
3899
3900 Note: relies on the Lisp's READ-LINE, but additionally removes any remaining CR
3901 from the line-ending if the file or stream had CR+LF but Lisp only removed LF.
3902
3903 Read no more than COUNT lines."
3904 (check-type count (or null integer))
3905 (with-open-stream (input input)
3906 (loop :for n :from 0
3907 :for l = (and (or (not count) (< n count))
3908 (read-line input nil nil))
3909 ;; stripln: to remove CR when the OS sends CRLF and Lisp only remove LF
3910 :while l :collect (stripln l))))
3911
3912 (defun slurp-stream-line (input &key (at 0))
3913 "Read the contents of the INPUT stream as a list of lines,
3914 then return the ACCESS-AT of that list of lines using the AT specifier.
3915 PATH defaults to 0, i.e. return the first line.
3916 PATH is typically an integer, or a list of an integer and a function.
3917 If PATH is NIL, it will return all the lines in the file.
3918
3919 The stream will not be read beyond the Nth lines,
3920 where N is the index specified by path
3921 if path is either an integer or a list that starts with an integer."
3922 (access-at (slurp-stream-lines input :count (access-at-count at)) at))
3923
3924 (defun slurp-stream-forms (input &key count)
3925 "Read the contents of the INPUT stream as a list of forms,
3926 and return those forms.
3927
3928 If COUNT is null, read to the end of the stream;
3929 if COUNT is an integer, stop after COUNT forms were read.
3930
3931 BEWARE: be sure to use WITH-SAFE-IO-SYNTAX, or some variant thereof"
3932 (check-type count (or null integer))
3933 (loop :with eof = '#:eof
3934 :for n :from 0
3935 :for form = (if (and count (>= n count))
3936 eof
3937 (read-preserving-whitespace input nil eof))
3938 :until (eq form eof) :collect form))
3939
3940 (defun slurp-stream-form (input &key (at 0))
3941 "Read the contents of the INPUT stream as a list of forms,
3942 then return the ACCESS-AT of these forms following the AT.
3943 AT defaults to 0, i.e. return the first form.
3944 AT is typically a list of integers.
3945 If AT is NIL, it will return all the forms in the file.
3946
3947 The stream will not be read beyond the Nth form,
3948 where N is the index specified by path,
3949 if path is either an integer or a list that starts with an integer.
3950
3951 BEWARE: be sure to use WITH-SAFE-IO-SYNTAX, or some variant thereof"
3952 (access-at (slurp-stream-forms input :count (access-at-count at)) at))
3953
3954 (defun read-file-string (file &rest keys)
3955 "Open FILE with option KEYS, read its contents as a string"
3956 (apply 'call-with-input-file file 'slurp-stream-string keys))
3957
3958 (defun read-file-lines (file &rest keys)
3959 "Open FILE with option KEYS, read its contents as a list of lines
3960 BEWARE: be sure to use WITH-SAFE-IO-SYNTAX, or some variant thereof"
3961 (apply 'call-with-input-file file 'slurp-stream-lines keys))
3962
3963 (defun read-file-line (file &rest keys &key (at 0) &allow-other-keys)
3964 "Open input FILE with option KEYS (except AT),
3965 and read its contents as per SLURP-STREAM-LINE with given AT specifier.
3966 BEWARE: be sure to use WITH-SAFE-IO-SYNTAX, or some variant thereof"
3967 (apply 'call-with-input-file file
3968 #'(lambda (input) (slurp-stream-line input :at at))
3969 (remove-plist-key :at keys)))
3970
3971 (defun read-file-forms (file &rest keys &key count &allow-other-keys)
3972 "Open input FILE with option KEYS (except COUNT),
3973 and read its contents as per SLURP-STREAM-FORMS with given COUNT.
3974 BEWARE: be sure to use WITH-SAFE-IO-SYNTAX, or some variant thereof"
3975 (apply 'call-with-input-file file
3976 #'(lambda (input) (slurp-stream-forms input :count count))
3977 (remove-plist-key :count keys)))
3978
3979 (defun read-file-form (file &rest keys &key (at 0) &allow-other-keys)
3980 "Open input FILE with option KEYS (except AT),
3981 and read its contents as per SLURP-STREAM-FORM with given AT specifier.
3982 BEWARE: be sure to use WITH-SAFE-IO-SYNTAX, or some variant thereof"
3983 (apply 'call-with-input-file file
3984 #'(lambda (input) (slurp-stream-form input :at at))
3985 (remove-plist-key :at keys)))
3986
3987 (defun safe-read-file-line (pathname &rest keys &key (package :cl) &allow-other-keys)
3988 "Reads the specified line from the top of a file using a safe standardized syntax.
3989 Extracts the line using READ-FILE-LINE,
3990 within an WITH-SAFE-IO-SYNTAX using the specified PACKAGE."
3991 (with-safe-io-syntax (:package package)
3992 (apply 'read-file-line pathname (remove-plist-key :package keys))))
3993
3994 (defun safe-read-file-form (pathname &rest keys &key (package :cl) &allow-other-keys)
3995 "Reads the specified form from the top of a file using a safe standardized syntax.
3996 Extracts the form using READ-FILE-FORM,
3997 within an WITH-SAFE-IO-SYNTAX using the specified PACKAGE."
3998 (with-safe-io-syntax (:package package)
3999 (apply 'read-file-form pathname (remove-plist-key :package keys))))
4000
4001 (defun eval-input (input)
4002 "Portably read and evaluate forms from INPUT, return the last values."
4003 (with-input (input)
4004 (loop :with results :with eof ='#:eof
4005 :for form = (read input nil eof)
4006 :until (eq form eof)
4007 :do (setf results (multiple-value-list (eval form)))
4008 :finally (return (apply 'values results)))))
4009
4010 (defun eval-thunk (thunk)
4011 "Evaluate a THUNK of code:
4012 If a function, FUNCALL it without arguments.
4013 If a constant literal and not a sequence, return it.
4014 If a cons or a symbol, EVAL it.
4015 If a string, repeatedly read and evaluate from it, returning the last values."
4016 (etypecase thunk
4017 ((or boolean keyword number character pathname) thunk)
4018 ((or cons symbol) (eval thunk))
4019 (function (funcall thunk))
4020 (string (eval-input thunk))))
4021
4022 (defun standard-eval-thunk (thunk &key (package :cl))
4023 "Like EVAL-THUNK, but in a more standardized evaluation context."
4024 ;; Note: it's "standard-" not "safe-", because evaluation is never safe.
4025 (when thunk
4026 (with-safe-io-syntax (:package package)
4027 (let ((*read-eval* t))
4028 (eval-thunk thunk))))))
4029
4030 (with-upgradability ()
4031 (defun println (x &optional (stream *standard-output*))
4032 "Variant of PRINC that also calls TERPRI afterwards"
4033 (princ x stream) (terpri stream) (finish-output stream) (values))
4034
4035 (defun writeln (x &rest keys &key (stream *standard-output*) &allow-other-keys)
4036 "Variant of WRITE that also calls TERPRI afterwards"
4037 (apply 'write x keys) (terpri stream) (finish-output stream) (values)))
4038
4039
4040 ;;; Using temporary files
4041 (with-upgradability ()
4042 (defun default-temporary-directory ()
4043 "Return a default directory to use for temporary files"
4044 (os-cond
4045 ((os-unix-p)
4046 (or (getenv-pathname "TMPDIR" :ensure-directory t)
4047 (parse-native-namestring "/tmp/")))
4048 ((os-windows-p)
4049 (getenv-pathname "TEMP" :ensure-directory t))
4050 (t (subpathname (user-homedir-pathname) "tmp/"))))
4051
4052 (defvar *temporary-directory* nil "User-configurable location for temporary files")
4053
4054 (defun temporary-directory ()
4055 "Return a directory to use for temporary files"
4056 (or *temporary-directory* (default-temporary-directory)))
4057
4058 (defun setup-temporary-directory ()
4059 "Configure a default temporary directory to use."
4060 (setf *temporary-directory* (default-temporary-directory))
4061 #+gcl (setf system::*tmp-dir* *temporary-directory*))
4062
4063 (defun call-with-temporary-file
4064 (thunk &key
4065 (want-stream-p t) (want-pathname-p t) (direction :io) keep after
4066 directory (type "tmp" typep) prefix (suffix (when typep "-tmp"))
4067 (element-type *default-stream-element-type*)
4068 (external-format *utf-8-external-format*))
4069 "Call a THUNK with stream and/or pathname arguments identifying a temporary file.
4070
4071 The temporary file's pathname will be based on concatenating
4072 PREFIX (or \"tmp\" if it's NIL), a random alphanumeric string,
4073 and optional SUFFIX (defaults to \"-tmp\" if a type was provided)
4074 and TYPE (defaults to \"tmp\", using a dot as separator if not NIL),
4075 within DIRECTORY (defaulting to the TEMPORARY-DIRECTORY) if the PREFIX isn't absolute.
4076
4077 The file will be open with specified DIRECTION (defaults to :IO),
4078 ELEMENT-TYPE (defaults to *DEFAULT-STREAM-ELEMENT-TYPE*) and
4079 EXTERNAL-FORMAT (defaults to *UTF-8-EXTERNAL-FORMAT*).
4080 If WANT-STREAM-P is true (the defaults to T), then THUNK will then be CALL-FUNCTION'ed
4081 with the stream and the pathname (if WANT-PATHNAME-P is true, defaults to T),
4082 and stream will be closed after the THUNK exits (either normally or abnormally).
4083 If WANT-STREAM-P is false, then WANT-PATHAME-P must be true, and then
4084 THUNK is only CALL-FUNCTION'ed after the stream is closed, with the pathname as argument.
4085 Upon exit of THUNK, the AFTER thunk if defined is CALL-FUNCTION'ed with the pathname as argument.
4086 If AFTER is defined, its results are returned, otherwise, the results of THUNK are returned.
4087 Finally, the file will be deleted, unless the KEEP argument when CALL-FUNCTION'ed returns true."
4088 #+xcl (declare (ignorable typep))
4089 (check-type direction (member :output :io))
4090 (assert (or want-stream-p want-pathname-p))
4091 (loop
4092 :with prefix-pn = (ensure-absolute-pathname
4093 (or prefix "tmp")
4094 (or (ensure-pathname
4095 directory
4096 :namestring :native
4097 :ensure-directory t
4098 :ensure-physical t)
4099 #'temporary-directory))
4100 :with prefix-nns = (native-namestring prefix-pn)
4101 :with results = (progn (ensure-directories-exist prefix-pn)
4102 ())
4103 :for counter :from (random (expt 36 #-gcl 8 #+gcl 5))
4104 :for pathname = (parse-native-namestring
4105 (format nil "~A~36R~@[~A~]~@[.~A~]"
4106 prefix-nns counter suffix (unless (eq type :unspecific) type)))
4107 :for okp = nil :do
4108 ;; TODO: on Unix, do something about umask
4109 ;; TODO: on Unix, audit the code so we make sure it uses O_CREAT|O_EXCL
4110 ;; TODO: on Unix, use CFFI and mkstemp --
4111 ;; except UIOP is precisely meant to not depend on CFFI or on anything! Grrrr.
4112 ;; Can we at least design some hook?
4113 (unwind-protect
4114 (progn
4115 (ensure-directories-exist pathname)
4116 (with-open-file (stream pathname
4117 :direction direction
4118 :element-type element-type
4119 :external-format external-format
4120 :if-exists nil :if-does-not-exist :create)
4121 (when stream
4122 (setf okp pathname)
4123 (when want-stream-p
4124 ;; Note: can't return directly from within with-open-file
4125 ;; or the non-local return causes the file creation to be undone.
4126 (setf results (multiple-value-list
4127 (if want-pathname-p
4128 (funcall thunk stream pathname)
4129 (funcall thunk stream)))))))
4130 (cond
4131 ((not okp) nil)
4132 (after (return (call-function after okp)))
4133 ((and want-pathname-p (not want-stream-p)) (return (call-function thunk okp)))
4134 (t (return (apply 'values results)))))
4135 (when (and okp (not (call-function keep)))
4136 (ignore-errors (delete-file-if-exists okp))))))
4137
4138 (defmacro with-temporary-file ((&key (stream (gensym "STREAM") streamp)
4139 (pathname (gensym "PATHNAME") pathnamep)
4140 directory prefix suffix type
4141 keep direction element-type external-format)
4142 &body body)
4143 "Evaluate BODY where the symbols specified by keyword arguments
4144 STREAM and PATHNAME (if respectively specified) are bound corresponding
4145 to a newly created temporary file ready for I/O, as per CALL-WITH-TEMPORARY-FILE.
4146 At least one of STREAM or PATHNAME must be specified.
4147 If the STREAM is not specified, it will be closed before the BODY is evaluated.
4148 If STREAM is specified, then the :CLOSE-STREAM label if it appears in the BODY,
4149 separates forms run before and after the stream is closed.
4150 The values of the last form of the BODY (not counting the separating :CLOSE-STREAM) are returned.
4151 Upon success, the KEEP form is evaluated and the file is is deleted unless it evaluates to TRUE."
4152 (check-type stream symbol)
4153 (check-type pathname symbol)
4154 (assert (or streamp pathnamep))
4155 (let* ((afterp (position :close-stream body))
4156 (before (if afterp (subseq body 0 afterp) body))
4157 (after (when afterp (subseq body (1+ afterp))))
4158 (beforef (gensym "BEFORE"))
4159 (afterf (gensym "AFTER")))
4160 `(flet (,@(when before
4161 `((,beforef (,@(when streamp `(,stream)) ,@(when pathnamep `(,pathname)))
4162 ,@(when after `((declare (ignorable ,pathname))))
4163 ,@before)))
4164 ,@(when after
4165 (assert pathnamep)
4166 `((,afterf (,pathname) ,@after))))
4167 #-gcl (declare (dynamic-extent ,@(when before `(#',beforef)) ,@(when after `(#',afterf))))
4168 (call-with-temporary-file
4169 ,(when before `#',beforef)
4170 :want-stream-p ,streamp
4171 :want-pathname-p ,pathnamep
4172 ,@(when direction `(:direction ,direction))
4173 ,@(when directory `(:directory ,directory))
4174 ,@(when prefix `(:prefix ,prefix))
4175 ,@(when suffix `(:suffix ,suffix))
4176 ,@(when type `(:type ,type))
4177 ,@(when keep `(:keep ,keep))
4178 ,@(when after `(:after #',afterf))
4179 ,@(when element-type `(:element-type ,element-type))
4180 ,@(when external-format `(:external-format ,external-format))))))
4181
4182 (defun get-temporary-file (&key directory prefix suffix type)
4183 (with-temporary-file (:pathname pn :keep t
4184 :directory directory :prefix prefix :suffix suffix :type type)
4185 pn))
4186
4187 ;; Temporary pathnames in simple cases where no contention is assumed
4188 (defun add-pathname-suffix (pathname suffix &rest keys)
4189 "Add a SUFFIX to the name of a PATHNAME, return a new pathname.
4190 Further KEYS can be passed to MAKE-PATHNAME."
4191 (apply 'make-pathname :name (strcat (pathname-name pathname) suffix)
4192 :defaults pathname keys))
4193
4194 (defun tmpize-pathname (x)
4195 "Return a new pathname modified from X by adding a trivial random suffix.
4196 A new empty file with said temporary pathname is created, to ensure there is no
4197 clash with any concurrent process attempting the same thing."
4198 (let* ((px (ensure-pathname x :ensure-physical t))
4199 (prefix (if-let (n (pathname-name px)) (strcat n "-tmp") "tmp"))
4200 (directory (pathname-directory-pathname px)))
4201 (get-temporary-file :directory directory :prefix prefix :type (pathname-type px))))
4202
4203 (defun call-with-staging-pathname (pathname fun)
4204 "Calls FUN with a staging pathname, and atomically
4205 renames the staging pathname to the PATHNAME in the end.
4206 NB: this protects only against failure of the program, not against concurrent attempts.
4207 For the latter case, we ought pick a random suffix and atomically open it."
4208 (let* ((pathname (pathname pathname))
4209 (staging (tmpize-pathname pathname)))
4210 (unwind-protect
4211 (multiple-value-prog1
4212 (funcall fun staging)
4213 (rename-file-overwriting-target staging pathname))
4214 (delete-file-if-exists staging))))
4215
4216 (defmacro with-staging-pathname ((pathname-var &optional (pathname-value pathname-var)) &body body)
4217 "Trivial syntax wrapper for CALL-WITH-STAGING-PATHNAME"
4218 `(call-with-staging-pathname ,pathname-value #'(lambda (,pathname-var) ,@body))))
4219
4220 (with-upgradability ()
4221 (defun file-stream-p (stream)
4222 (typep stream 'file-stream))
4223 (defun file-or-synonym-stream-p (stream)
4224 (or (file-stream-p stream)
4225 (and (typep stream 'synonym-stream)
4226 (file-or-synonym-stream-p
4227 (symbol-value (synonym-stream-symbol stream)))))))
4228 ;;;; -------------------------------------------------------------------------
4229 ;;;; Starting, Stopping, Dumping a Lisp image
4230
4231 (uiop/package:define-package :uiop/image
4232 (:nicknames :asdf/image)
4233 (:recycle :uiop/image :asdf/image :xcvb-driver)
4234 (:use :uiop/common-lisp :uiop/package :uiop/utility :uiop/pathname :uiop/stream :uiop/os)
4235 (:export
4236 #:*image-dumped-p* #:raw-command-line-arguments #:*command-line-arguments*
4237 #:command-line-arguments #:raw-command-line-arguments #:setup-command-line-arguments #:argv0
4238 #:*lisp-interaction*
4239 #:fatal-condition #:fatal-condition-p
4240 #:handle-fatal-condition
4241 #:call-with-fatal-condition-handler #:with-fatal-condition-handler
4242 #:*image-restore-hook* #:*image-prelude* #:*image-entry-point*
4243 #:*image-postlude* #:*image-dump-hook*
4244 #:quit #:die #:raw-print-backtrace #:print-backtrace #:print-condition-backtrace
4245 #:shell-boolean-exit
4246 #:register-image-restore-hook #:register-image-dump-hook
4247 #:call-image-restore-hook #:call-image-dump-hook
4248 #:restore-image #:dump-image #:create-image
4249 ))
4250 (in-package :uiop/image)
4251
4252 (with-upgradability ()
4253 (defvar *lisp-interaction* t
4254 "Is this an interactive Lisp environment, or is it batch processing?")
4255
4256 (defvar *command-line-arguments* nil
4257 "Command-line arguments")
4258
4259 (defvar *image-dumped-p* nil ; may matter as to how to get to command-line-arguments
4260 "Is this a dumped image? As a standalone executable?")
4261
4262 (defvar *image-restore-hook* nil
4263 "Functions to call (in reverse order) when the image is restored")
4264
4265 (defvar *image-restored-p* nil
4266 "Has the image been restored? A boolean, or :in-progress while restoring, :in-regress while dumping")
4267
4268 (defvar *image-prelude* nil
4269 "a form to evaluate, or string containing forms to read and evaluate
4270 when the image is restarted, but before the entry point is called.")
4271
4272 (defvar *image-entry-point* nil
4273 "a function with which to restart the dumped image when execution is restored from it.")
4274
4275 (defvar *image-postlude* nil
4276 "a form to evaluate, or string containing forms to read and evaluate
4277 before the image dump hooks are called and before the image is dumped.")
4278
4279 (defvar *image-dump-hook* nil
4280 "Functions to call (in order) when before an image is dumped")
4281
4282 (deftype fatal-condition ()
4283 `(and serious-condition #+clozure (not ccl:process-reset))))
4284
4285 ;;; Exiting properly or im-
4286 (with-upgradability ()
4287 (defun quit (&optional (code 0) (finish-output t))
4288 "Quits from the Lisp world, with the given exit status if provided.
4289 This is designed to abstract away the implementation specific quit forms."
4290 (when finish-output ;; essential, for ClozureCL, and for standard compliance.
4291 (finish-outputs))
4292 #+(or abcl xcl) (ext:quit :status code)
4293 #+allegro (excl:exit code :quiet t)
4294 #+(or clasp ecl) (si:quit code)
4295 #+clisp (ext:quit code)
4296 #+clozure (ccl:quit code)
4297 #+cormanlisp (win32:exitprocess code)
4298 #+(or cmucl scl) (unix:unix-exit code)
4299 #+gcl (system:quit code)
4300 #+genera (error "~S: You probably don't want to Halt Genera. (code: ~S)" 'quit code)
4301 #+lispworks (lispworks:quit :status code :confirm nil :return nil :ignore-errors-p t)
4302 #+mcl (progn code (ccl:quit)) ;; or should we use FFI to call libc's exit(3) ?
4303 #+mkcl (mk-ext:quit :exit-code code)
4304 #+sbcl #.(let ((exit (find-symbol* :exit :sb-ext nil))
4305 (quit (find-symbol* :quit :sb-ext nil)))
4306 (cond
4307 (exit `(,exit :code code :abort (not finish-output)))
4308 (quit `(,quit :unix-status code :recklessly-p (not finish-output)))))
4309 #-(or abcl allegro clasp clisp clozure cmucl ecl gcl genera lispworks mcl mkcl sbcl scl xcl)
4310 (error "~S called with exit code ~S but there's no quitting on this implementation" 'quit code))
4311
4312 (defun die (code format &rest arguments)
4313 "Die in error with some error message"
4314 (with-safe-io-syntax ()
4315 (ignore-errors
4316 (format! *stderr* "~&~?~&" format arguments)))
4317 (quit code))
4318
4319 (defun raw-print-backtrace (&key (stream *debug-io*) count condition)
4320 "Print a backtrace, directly accessing the implementation"
4321 (declare (ignorable stream count condition))
4322 #+abcl
4323 (loop :for i :from 0
4324 :for frame :in (sys:backtrace (or count most-positive-fixnum)) :do
4325 (safe-format! stream "~&~D: ~A~%" i frame))
4326 #+allegro
4327 (let ((*terminal-io* stream)
4328 (*standard-output* stream)
4329 (tpl:*zoom-print-circle* *print-circle*)
4330 (tpl:*zoom-print-level* *print-level*)
4331 (tpl:*zoom-print-length* *print-length*))
4332 (tpl:do-command "zoom"
4333 :from-read-eval-print-loop nil
4334 :count (or count t)
4335 :all t))
4336 #+(or clasp ecl mkcl)
4337 (let* ((top (si:ihs-top))
4338 (repeats (if count (min top count) top))
4339 (backtrace (loop :for ihs :from 0 :below top
4340 :collect (list (si::ihs-fun ihs)
4341 (si::ihs-env ihs)))))
4342 (loop :for i :from 0 :below repeats
4343 :for frame :in (nreverse backtrace) :do
4344 (safe-format! stream "~&~D: ~S~%" i frame)))
4345 #+clisp
4346 (system::print-backtrace :out stream :limit count)
4347 #+(or clozure mcl)
4348 (let ((*debug-io* stream))
4349 #+clozure (ccl:print-call-history :count count :start-frame-number 1)
4350 #+mcl (ccl:print-call-history :detailed-p nil)
4351 (finish-output stream))
4352 #+(or cmucl scl)
4353 (let ((debug:*debug-print-level* *print-level*)
4354 (debug:*debug-print-length* *print-length*))
4355 (debug:backtrace (or count most-positive-fixnum) stream))
4356 #+gcl
4357 (let ((*debug-io* stream))
4358 (ignore-errors
4359 (with-safe-io-syntax ()
4360 (if condition
4361 (conditions::condition-backtrace condition)
4362 (system::simple-backtrace)))))
4363 #+lispworks
4364 (let ((dbg::*debugger-stack*
4365 (dbg::grab-stack nil :how-many (or count most-positive-fixnum)))
4366 (*debug-io* stream)
4367 (dbg:*debug-print-level* *print-level*)
4368 (dbg:*debug-print-length* *print-length*))
4369 (dbg:bug-backtrace nil))
4370 #+sbcl
4371 (sb-debug:print-backtrace :stream stream :count (or count most-positive-fixnum))
4372 #+xcl
4373 (loop :for i :from 0 :below (or count most-positive-fixnum)
4374 :for frame :in (extensions:backtrace-as-list) :do
4375 (safe-format! stream "~&~D: ~S~%" i frame)))
4376
4377 (defun print-backtrace (&rest keys &key stream count condition)
4378 "Print a backtrace"
4379 (declare (ignore stream count condition))
4380 (with-safe-io-syntax (:package :cl)
4381 (let ((*print-readably* nil)
4382 (*print-circle* t)
4383 (*print-miser-width* 75)
4384 (*print-length* nil)
4385 (*print-level* nil)
4386 (*print-pretty* t))
4387 (ignore-errors (apply 'raw-print-backtrace keys)))))
4388
4389 (defun print-condition-backtrace (condition &key (stream *stderr*) count)
4390 "Print a condition after a backtrace triggered by that condition"
4391 ;; We print the condition *after* the backtrace,
4392 ;; for the sake of who sees the backtrace at a terminal.
4393 ;; It is up to the caller to print the condition *before*, with some context.
4394 (print-backtrace :stream stream :count count :condition condition)
4395 (when condition
4396 (safe-format! stream "~&Above backtrace due to this condition:~%~A~&"
4397 condition)))
4398
4399 (defun fatal-condition-p (condition)
4400 "Is the CONDITION fatal?"
4401 (typep condition 'fatal-condition))
4402
4403 (defun handle-fatal-condition (condition)
4404 "Handle a fatal CONDITION:
4405 depending on whether *LISP-INTERACTION* is set, enter debugger or die"
4406 (cond
4407 (*lisp-interaction*
4408 (invoke-debugger condition))
4409 (t
4410 (safe-format! *stderr* "~&Fatal condition:~%~A~%" condition)
4411 (print-condition-backtrace condition :stream *stderr*)
4412 (die 99 "~A" condition))))
4413
4414 (defun call-with-fatal-condition-handler (thunk)
4415 "Call THUNK in a context where fatal conditions are appropriately handled"
4416 (handler-bind ((fatal-condition #'handle-fatal-condition))
4417 (funcall thunk)))
4418
4419 (defmacro with-fatal-condition-handler ((&optional) &body body)
4420 "Execute BODY in a context where fatal conditions are appropriately handled"
4421 `(call-with-fatal-condition-handler #'(lambda () ,@body)))
4422
4423 (defun shell-boolean-exit (x)
4424 "Quit with a return code that is 0 iff argument X is true"
4425 (quit (if x 0 1))))
4426
4427
4428 ;;; Using image hooks
4429 (with-upgradability ()
4430 (defun register-image-restore-hook (hook &optional (call-now-p t))
4431 "Regiter a hook function to be run when restoring a dumped image"
4432 (register-hook-function '*image-restore-hook* hook call-now-p))
4433
4434 (defun register-image-dump-hook (hook &optional (call-now-p nil))
4435 "Register a the hook function to be run before to dump an image"
4436 (register-hook-function '*image-dump-hook* hook call-now-p))
4437
4438 (defun call-image-restore-hook ()
4439 "Call the hook functions registered to be run when restoring a dumped image"
4440 (call-functions (reverse *image-restore-hook*)))
4441
4442 (defun call-image-dump-hook ()
4443 "Call the hook functions registered to be run before to dump an image"
4444 (call-functions *image-dump-hook*)))
4445
4446
4447 ;;; Proper command-line arguments
4448 (with-upgradability ()
4449 (defun raw-command-line-arguments ()
4450 "Find what the actual command line for this process was."
4451 #+abcl ext:*command-line-argument-list* ; Use 1.0.0 or later!
4452 #+allegro (sys:command-line-arguments) ; default: :application t
4453 #+(or clasp ecl) (loop :for i :from 0 :below (si:argc) :collect (si:argv i))
4454 #+clisp (coerce (ext:argv) 'list)
4455 #+clozure ccl:*command-line-argument-list*
4456 #+(or cmucl scl) extensions:*command-line-strings*
4457 #+gcl si:*command-args*
4458 #+(or genera mcl) nil
4459 #+lispworks sys:*line-arguments-list*
4460 #+mkcl (loop :for i :from 0 :below (mkcl:argc) :collect (mkcl:argv i))
4461 #+sbcl sb-ext:*posix-argv*
4462 #+xcl system:*argv*
4463 #-(or abcl allegro clasp clisp clozure cmucl ecl gcl genera lispworks mcl mkcl sbcl scl xcl)
4464 (not-implemented-error 'raw-command-line-arguments))
4465
4466 (defun command-line-arguments (&optional (arguments (raw-command-line-arguments)))
4467 "Extract user arguments from command-line invocation of current process.
4468 Assume the calling conventions of a generated script that uses --
4469 if we are not called from a directly executable image."
4470 (block nil
4471 #+abcl (return arguments)
4472 ;; SBCL and Allegro already separate user arguments from implementation arguments.
4473 #-(or sbcl allegro)
4474 (unless (eq *image-dumped-p* :executable)
4475 ;; LispWorks command-line processing isn't transparent to the user
4476 ;; unless you create a standalone executable; in that case,
4477 ;; we rely on cl-launch or some other script to set the arguments for us.
4478 #+lispworks (return *command-line-arguments*)
4479 ;; On other implementations, on non-standalone executables,
4480 ;; we trust cl-launch or whichever script starts the program
4481 ;; to use -- as a delimiter between implementation arguments and user arguments.
4482 #-lispworks (setf arguments (member "--" arguments :test 'string-equal)))
4483 (rest arguments)))
4484
4485 (defun argv0 ()
4486 "On supported implementations (most that matter), or when invoked by a proper wrapper script,
4487 return a string that for the name with which the program was invoked, i.e. argv[0] in C.
4488 Otherwise, return NIL."
4489 (cond
4490 ((eq *image-dumped-p* :executable) ; yes, this ARGV0 is our argv0 !
4491 ;; NB: not currently available on ABCL, Corman, Genera, MCL
4492 (or #+(or allegro clisp clozure cmucl gcl lispworks sbcl scl xcl)
4493 (first (raw-command-line-arguments))
4494 #+(or clasp ecl) (si:argv 0) #+mkcl (mkcl:argv 0)))
4495 (t ;; argv[0] is the name of the interpreter.
4496 ;; The wrapper script can export __CL_ARGV0. cl-launch does as of 4.0.1.8.
4497 (getenvp "__CL_ARGV0"))))
4498
4499 (defun setup-command-line-arguments ()
4500 (setf *command-line-arguments* (command-line-arguments)))
4501
4502 (defun restore-image (&key
4503 (lisp-interaction *lisp-interaction*)
4504 (restore-hook *image-restore-hook*)
4505 (prelude *image-prelude*)
4506 (entry-point *image-entry-point*)
4507 (if-already-restored '(cerror "RUN RESTORE-IMAGE ANYWAY")))
4508 "From a freshly restarted Lisp image, restore the saved Lisp environment
4509 by setting appropriate variables, running various hooks, and calling any specified entry point.
4510
4511 If the image has already been restored or is already being restored, as per *IMAGE-RESTORED-P*,
4512 call the IF-ALREADY-RESTORED error handler (by default, a continuable error), and do return
4513 immediately to the surrounding restore process if allowed to continue.
4514
4515 Then, comes the restore process itself:
4516 First, call each function in the RESTORE-HOOK,
4517 in the order they were registered with REGISTER-IMAGE-RESTORE-HOOK.
4518 Second, evaluate the prelude, which is often Lisp text that is read,
4519 as per EVAL-INPUT.
4520 Third, call the ENTRY-POINT function, if any is specified, with no argument.
4521
4522 The restore process happens in a WITH-FATAL-CONDITION-HANDLER, so that if LISP-INTERACTION is NIL,
4523 any unhandled error leads to a backtrace and an exit with an error status.
4524 If LISP-INTERACTION is NIL, the process also exits when no error occurs:
4525 if neither restart nor entry function is provided, the program will exit with status 0 (success);
4526 if a function was provided, the program will exit after the function returns (if it returns),
4527 with status 0 if and only if the primary return value of result is generalized boolean true,
4528 and with status 1 if this value is NIL.
4529
4530 If LISP-INTERACTION is true, unhandled errors will take you to the debugger, and the result
4531 of the function will be returned rather than interpreted as a boolean designating an exit code."
4532 (when *image-restored-p*
4533 (if if-already-restored
4534 (call-function if-already-restored "Image already ~:[being ~;~]restored"
4535 (eq *image-restored-p* t))
4536 (return-from restore-image)))
4537 (with-fatal-condition-handler ()
4538 (setf *lisp-interaction* lisp-interaction)
4539 (setf *image-restore-hook* restore-hook)
4540 (setf *image-prelude* prelude)
4541 (setf *image-restored-p* :in-progress)
4542 (call-image-restore-hook)
4543 (standard-eval-thunk prelude)
4544 (setf *image-restored-p* t)
4545 (let ((results (multiple-value-list
4546 (if entry-point
4547 (call-function entry-point)
4548 t))))
4549 (if lisp-interaction
4550 (apply 'values results)
4551 (shell-boolean-exit (first results)))))))
4552
4553
4554 ;;; Dumping an image
4555
4556 (with-upgradability ()
4557 (defun dump-image (filename &key output-name executable
4558 (postlude *image-postlude*)
4559 (dump-hook *image-dump-hook*)
4560 #+clozure prepend-symbols #+clozure (purify t)
4561 #+sbcl compression
4562 #+(and sbcl os-windows) application-type)
4563 "Dump an image of the current Lisp environment at pathname FILENAME, with various options.
4564
4565 First, finalize the image, by evaluating the POSTLUDE as per EVAL-INPUT, then calling each of
4566 the functions in DUMP-HOOK, in reverse order of registration by REGISTER-DUMP-HOOK.
4567
4568 If EXECUTABLE is true, create an standalone executable program that calls RESTORE-IMAGE on startup.
4569
4570 Pass various implementation-defined options, such as PREPEND-SYMBOLS and PURITY on CCL,
4571 or COMPRESSION on SBCL, and APPLICATION-TYPE on SBCL/Windows."
4572 ;; Note: at least SBCL saves only global values of variables in the heap image,
4573 ;; so make sure things you want to dump are NOT just local bindings shadowing the global values.
4574 (declare (ignorable filename output-name executable))
4575 (setf *image-dumped-p* (if executable :executable t))
4576 (setf *image-restored-p* :in-regress)
4577 (setf *image-postlude* postlude)
4578 (standard-eval-thunk *image-postlude*)
4579 (setf *image-dump-hook* dump-hook)
4580 (call-image-dump-hook)
4581 (setf *image-restored-p* nil)
4582 #-(or clisp clozure cmucl lispworks sbcl scl)
4583 (when executable
4584 (error "Dumping an executable is not supported on this implementation! Aborting."))
4585 #+allegro
4586 (progn
4587 (sys:resize-areas :global-gc t :pack-heap t :sift-old-areas t :tenure t) ; :new 5000000
4588 (excl:dumplisp :name filename :suppress-allegro-cl-banner t))
4589 #+clisp
4590 (apply #'ext:saveinitmem filename
4591 :quiet t
4592 :start-package *package*
4593 :keep-global-handlers nil
4594 :executable (if executable 0 t) ;--- requires clisp 2.48 or later, still catches --clisp-x
4595 (when executable
4596 (list
4597 ;; :parse-options nil ;--- requires a non-standard patch to clisp.
4598 :norc t :script nil :init-function #'restore-image)))
4599 #+clozure
4600 (flet ((dump (prepend-kernel)
4601 (ccl:save-application filename :prepend-kernel prepend-kernel :purify purify
4602 :toplevel-function (when executable #'restore-image))))
4603 ;;(setf ccl::*application* (make-instance 'ccl::lisp-development-system))
4604 (if prepend-symbols
4605 (with-temporary-file (:prefix "ccl-symbols-" :direction :output :pathname path)
4606 (require 'elf)
4607 (funcall (fdefinition 'ccl::write-elf-symbols-to-file) path)
4608 (dump path))
4609 (dump t)))
4610 #+(or cmucl scl)
4611 (progn
4612 (ext:gc :full t)
4613 (setf ext:*batch-mode* nil)
4614 (setf ext::*gc-run-time* 0)
4615 (apply 'ext:save-lisp filename
4616 #+cmucl :executable #+cmucl t
4617 (when executable '(:init-function restore-image :process-command-line nil))))
4618 #+gcl
4619 (progn
4620 (si::set-hole-size 500) (si::gbc nil) (si::sgc-on t)
4621 (si::save-system filename))
4622 #+lispworks
4623 (if executable
4624 (lispworks:deliver 'restore-image filename 0 :interface nil)
4625 (hcl:save-image filename :environment nil))
4626 #+sbcl
4627 (progn
4628 ;;(sb-pcl::precompile-random-code-segments) ;--- it is ugly slow at compile-time (!) when the initial core is a big CLOS program. If you want it, do it yourself
4629 (setf sb-ext::*gc-run-time* 0)
4630 (apply 'sb-ext:save-lisp-and-die filename
4631 :executable t ;--- always include the runtime that goes with the core
4632 (append
4633 (when compression (list :compression compression))
4634 ;;--- only save runtime-options for standalone executables
4635 (when executable (list :toplevel #'restore-image :save-runtime-options t))
4636 #+(and sbcl os-windows) ;; passing :application-type :gui will disable the console window.
4637 ;; the default is :console - only works with SBCL 1.1.15 or later.
4638 (when application-type (list :application-type application-type)))))
4639 #-(or allegro clisp clozure cmucl gcl lispworks sbcl scl)
4640 (error "Can't ~S ~S: UIOP doesn't support image dumping with ~A.~%"
4641 'dump-image filename (nth-value 1 (implementation-type))))
4642
4643 (defun create-image (destination lisp-object-files
4644 &key kind output-name prologue-code epilogue-code extra-object-files
4645 (prelude () preludep) (postlude () postludep)
4646 (entry-point () entry-point-p) build-args no-uiop)
4647 (declare (ignorable destination lisp-object-files extra-object-files kind output-name
4648 prologue-code epilogue-code prelude preludep postlude postludep
4649 entry-point entry-point-p build-args no-uiop))
4650 "On ECL, create an executable at pathname DESTINATION from the specified OBJECT-FILES and options"
4651 ;; Is it meaningful to run these in the current environment?
4652 ;; only if we also track the object files that constitute the "current" image,
4653 ;; and otherwise simulate dump-image, including quitting at the end.
4654 #-(or clasp ecl mkcl) (not-implemented-error 'create-image)
4655 #+(or clasp ecl mkcl)
4656 (let ((epilogue-code
4657 (if no-uiop
4658 epilogue-code
4659 (let ((forms
4660 (append
4661 (when epilogue-code `(,epilogue-code))
4662 (when postludep `((setf *image-postlude* ',postlude)))
4663 (when preludep `((setf *image-prelude* ',prelude)))
4664 (when entry-point-p `((setf *image-entry-point* ',entry-point)))
4665 (case kind
4666 ((:image)
4667 (setf kind :program) ;; to ECL, it's just another program.
4668 `((setf *image-dumped-p* t)
4669 (si::top-level #+(or clasp ecl) t) (quit)))
4670 ((:program)
4671 `((setf *image-dumped-p* :executable)
4672 (shell-boolean-exit
4673 (restore-image))))))))
4674 (when forms `(progn ,@forms))))))
4675 #+(or clasp ecl) (when (eql kind :image) (setf kind :program)) ; for no-uiop ubilds
4676 #+(or clasp ecl) (check-type kind (member :dll :lib :static-library :program :object :fasl))
4677 (apply #+clasp 'cmp:builder #+clasp kind
4678 #+(and ecl (not clasp)) 'c::builder #+(and ecl (not clasp)) kind
4679 #+mkcl (ecase kind
4680 ((:dll) 'compiler::build-shared-library)
4681 ((:lib :static-library) 'compiler::build-static-library)
4682 ((:fasl) 'compiler::build-bundle)
4683 ((:program) 'compiler::build-program))
4684 (pathname destination)
4685 #+(or clasp ecl) :lisp-files #+mkcl :lisp-object-files (append lisp-object-files #+(or clasp ecl) extra-object-files)
4686 #+(or clasp ecl) :init-name #+(or clasp ecl) (getf build-args :init-name)
4687 (append
4688 (when prologue-code `(:prologue-code ,prologue-code))
4689 (when epilogue-code `(:epilogue-code ,epilogue-code))
4690 #+mkcl (when extra-object-files `(:object-files ,extra-object-files))
4691 build-args)))))
4692
4693
4694 ;;; Some universal image restore hooks
4695 (with-upgradability ()
4696 (map () 'register-image-restore-hook
4697 '(setup-stdin setup-stdout setup-stderr
4698 setup-command-line-arguments setup-temporary-directory
4699 #+abcl detect-os)))
4700 ;;;; -------------------------------------------------------------------------
4701 ;;;; run-program initially from xcvb-driver.
4702
4703 (uiop/package:define-package :uiop/run-program
4704 (:nicknames :asdf/run-program)
4705 (:recycle :uiop/run-program :asdf/run-program :xcvb-driver)
4706 (:use :uiop/common-lisp :uiop/package :uiop/utility
4707 :uiop/pathname :uiop/os :uiop/filesystem :uiop/stream)
4708 (:export
4709 ;;; Escaping the command invocation madness
4710 #:easy-sh-character-p #:escape-sh-token #:escape-sh-command
4711 #:escape-windows-token #:escape-windows-command
4712 #:escape-token #:escape-command
4713
4714 ;;; run-program
4715 #:slurp-input-stream #:vomit-output-stream
4716 #:close-streams #:launch-program #:process-alive-p #:run-program
4717 #:terminate-process #:wait-process
4718 #:process-info-error-output #:process-info-input #:process-info-output
4719 #:process-info-pid
4720 #:subprocess-error
4721 #:subprocess-error-code #:subprocess-error-command #:subprocess-error-process
4722 ))
4723 (in-package :uiop/run-program)
4724
4725 ;;;; ----- Escaping strings for the shell -----
4726
4727 (with-upgradability ()
4728 (defun requires-escaping-p (token &key good-chars bad-chars)
4729 "Does this token require escaping, given the specification of
4730 either good chars that don't need escaping or bad chars that do need escaping,
4731 as either a recognizing function or a sequence of characters."
4732 (some
4733 (cond
4734 ((and good-chars bad-chars)
4735 (error "only one of good-chars and bad-chars can be provided"))
4736 ((typep good-chars 'function)
4737 (complement good-chars))
4738 ((typep bad-chars 'function)
4739 bad-chars)
4740 ((and good-chars (typep good-chars 'sequence))
4741 #'(lambda (c) (not (find c good-chars))))
4742 ((and bad-chars (typep bad-chars 'sequence))
4743 #'(lambda (c) (find c bad-chars)))
4744 (t (error "requires-escaping-p: no good-char criterion")))
4745 token))
4746
4747 (defun escape-token (token &key stream quote good-chars bad-chars escaper)
4748 "Call the ESCAPER function on TOKEN string if it needs escaping as per
4749 REQUIRES-ESCAPING-P using GOOD-CHARS and BAD-CHARS, otherwise output TOKEN,
4750 using STREAM as output (or returning result as a string if NIL)"
4751 (if (requires-escaping-p token :good-chars good-chars :bad-chars bad-chars)
4752 (with-output (stream)
4753 (apply escaper token stream (when quote `(:quote ,quote))))
4754 (output-string token stream)))
4755
4756 (defun escape-windows-token-within-double-quotes (x &optional s)
4757 "Escape a string token X within double-quotes
4758 for use within a MS Windows command-line, outputing to S."
4759 (labels ((issue (c) (princ c s))
4760 (issue-backslash (n) (loop :repeat n :do (issue #\\))))
4761 (loop
4762 :initially (issue #\") :finally (issue #\")
4763 :with l = (length x) :with i = 0
4764 :for i+1 = (1+ i) :while (< i l) :do
4765 (case (char x i)
4766 ((#\") (issue-backslash 1) (issue #\") (setf i i+1))
4767 ((#\\)
4768 (let* ((j (and (< i+1 l) (position-if-not
4769 #'(lambda (c) (eql c #\\)) x :start i+1)))
4770 (n (- (or j l) i)))
4771 (cond
4772 ((null j)
4773 (issue-backslash (* 2 n)) (setf i l))
4774 ((and (< j l) (eql (char x j) #\"))
4775 (issue-backslash (1+ (* 2 n))) (issue #\") (setf i (1+ j)))
4776 (t
4777 (issue-backslash n) (setf i j)))))
4778 (otherwise
4779 (issue (char x i)) (setf i i+1))))))
4780
4781 (defun easy-windows-character-p (x)
4782 "Is X an \"easy\" character that does not require quoting by the shell?"
4783 (or (alphanumericp x) (find x "+-_.,@:/=")))
4784
4785 (defun escape-windows-token (token &optional s)
4786 "Escape a string TOKEN within double-quotes if needed
4787 for use within a MS Windows command-line, outputing to S."
4788 (escape-token token :stream s :good-chars #'easy-windows-character-p :quote nil
4789 :escaper 'escape-windows-token-within-double-quotes))
4790
4791 (defun escape-sh-token-within-double-quotes (x s &key (quote t))
4792 "Escape a string TOKEN within double-quotes
4793 for use within a POSIX Bourne shell, outputing to S;
4794 omit the outer double-quotes if key argument :QUOTE is NIL"
4795 (when quote (princ #\" s))
4796 (loop :for c :across x :do
4797 (when (find c "$`\\\"") (princ #\\ s))
4798 (princ c s))
4799 (when quote (princ #\" s)))
4800
4801 (defun easy-sh-character-p (x)
4802 "Is X an \"easy\" character that does not require quoting by the shell?"
4803 (or (alphanumericp x) (find x "+-_.,%@:/=")))
4804
4805 (defun escape-sh-token (token &optional s)
4806 "Escape a string TOKEN within double-quotes if needed
4807 for use within a POSIX Bourne shell, outputing to S."
4808 (escape-token token :stream s :quote #\" :good-chars #'easy-sh-character-p
4809 :escaper 'escape-sh-token-within-double-quotes))
4810
4811 (defun escape-shell-token (token &optional s)
4812 "Escape a token for the current operating system shell"
4813 (os-cond
4814 ((os-unix-p) (escape-sh-token token s))
4815 ((os-windows-p) (escape-windows-token token s))))
4816
4817 (defun escape-command (command &optional s
4818 (escaper 'escape-shell-token))
4819 "Given a COMMAND as a list of tokens, return a string of the
4820 spaced, escaped tokens, using ESCAPER to escape."
4821 (etypecase command
4822 (string (output-string command s))
4823 (list (with-output (s)
4824 (loop :for first = t :then nil :for token :in command :do
4825 (unless first (princ #\space s))
4826 (funcall escaper token s))))))
4827
4828 (defun escape-windows-command (command &optional s)
4829 "Escape a list of command-line arguments into a string suitable for parsing
4830 by CommandLineToArgv in MS Windows"
4831 ;; http://msdn.microsoft.com/en-us/library/bb776391(v=vs.85).aspx
4832 ;; http://msdn.microsoft.com/en-us/library/17w5ykft(v=vs.85).aspx
4833 (escape-command command s 'escape-windows-token))
4834
4835 (defun escape-sh-command (command &optional s)
4836 "Escape a list of command-line arguments into a string suitable for parsing
4837 by /bin/sh in POSIX"
4838 (escape-command command s 'escape-sh-token))
4839
4840 (defun escape-shell-command (command &optional stream)
4841 "Escape a command for the current operating system's shell"
4842 (escape-command command stream 'escape-shell-token)))
4843
4844
4845 ;;;; Slurping a stream, typically the output of another program
4846 (with-upgradability ()
4847 (defun call-stream-processor (fun processor stream)
4848 "Given FUN (typically SLURP-INPUT-STREAM or VOMIT-OUTPUT-STREAM,
4849 a PROCESSOR specification which is either an atom or a list specifying
4850 a processor an keyword arguments, call the specified processor with
4851 the given STREAM as input"
4852 (if (consp processor)
4853 (apply fun (first processor) stream (rest processor))
4854 (funcall fun processor stream)))
4855
4856 (defgeneric slurp-input-stream (processor input-stream &key)
4857 (:documentation
4858 "SLURP-INPUT-STREAM is a generic function with two positional arguments
4859 PROCESSOR and INPUT-STREAM and additional keyword arguments, that consumes (slurps)
4860 the contents of the INPUT-STREAM and processes them according to a method
4861 specified by PROCESSOR.
4862
4863 Built-in methods include the following:
4864 * if PROCESSOR is a function, it is called with the INPUT-STREAM as its argument
4865 * if PROCESSOR is a list, its first element should be a function. It will be applied to a cons of the
4866 INPUT-STREAM and the rest of the list. That is (x . y) will be treated as
4867 \(APPLY x <stream> y\)
4868 * if PROCESSOR is an output-stream, the contents of INPUT-STREAM is copied to the output-stream,
4869 per copy-stream-to-stream, with appropriate keyword arguments.
4870 * if PROCESSOR is the symbol CL:STRING or the keyword :STRING, then the contents of INPUT-STREAM
4871 are returned as a string, as per SLURP-STREAM-STRING.
4872 * if PROCESSOR is the keyword :LINES then the INPUT-STREAM will be handled by SLURP-STREAM-LINES.
4873 * if PROCESSOR is the keyword :LINE then the INPUT-STREAM will be handled by SLURP-STREAM-LINE.
4874 * if PROCESSOR is the keyword :FORMS then the INPUT-STREAM will be handled by SLURP-STREAM-FORMS.
4875 * if PROCESSOR is the keyword :FORM then the INPUT-STREAM will be handled by SLURP-STREAM-FORM.
4876 * if PROCESSOR is T, it is treated the same as *standard-output*. If it is NIL, NIL is returned.
4877
4878 Programmers are encouraged to define their own methods for this generic function."))
4879
4880 #-genera
4881 (defmethod slurp-input-stream ((function function) input-stream &key)
4882 (funcall function input-stream))
4883
4884 (defmethod slurp-input-stream ((list cons) input-stream &key)
4885 (apply (first list) input-stream (rest list)))
4886
4887 #-genera
4888 (defmethod slurp-input-stream ((output-stream stream) input-stream
4889 &key linewise prefix (element-type 'character) buffer-size)
4890 (copy-stream-to-stream
4891 input-stream output-stream
4892 :linewise linewise :prefix prefix :element-type element-type :buffer-size buffer-size))
4893
4894 (defmethod slurp-input-stream ((x (eql 'string)) stream &key stripped)
4895 (slurp-stream-string stream :stripped stripped))
4896
4897 (defmethod slurp-input-stream ((x (eql :string)) stream &key stripped)
4898 (slurp-stream-string stream :stripped stripped))
4899
4900 (defmethod slurp-input-stream ((x (eql :lines)) stream &key count)
4901 (slurp-stream-lines stream :count count))
4902
4903 (defmethod slurp-input-stream ((x (eql :line)) stream &key (at 0))
4904 (slurp-stream-line stream :at at))
4905
4906 (defmethod slurp-input-stream ((x (eql :forms)) stream &key count)
4907 (slurp-stream-forms stream :count count))
4908
4909 (defmethod slurp-input-stream ((x (eql :form)) stream &key (at 0))
4910 (slurp-stream-form stream :at at))
4911
4912 (defmethod slurp-input-stream ((x (eql t)) stream &rest keys &key &allow-other-keys)
4913 (apply 'slurp-input-stream *standard-output* stream keys))
4914
4915 (defmethod slurp-input-stream ((x null) (stream t) &key)
4916 nil)
4917
4918 (defmethod slurp-input-stream ((pathname pathname) input
4919 &key
4920 (element-type *default-stream-element-type*)
4921 (external-format *utf-8-external-format*)
4922 (if-exists :rename-and-delete)
4923 (if-does-not-exist :create)
4924 buffer-size
4925 linewise)
4926 (with-output-file (output pathname
4927 :element-type element-type
4928 :external-format external-format
4929 :if-exists if-exists
4930 :if-does-not-exist if-does-not-exist)
4931 (copy-stream-to-stream
4932 input output
4933 :element-type element-type :buffer-size buffer-size :linewise linewise)))
4934
4935 (defmethod slurp-input-stream (x stream
4936 &key linewise prefix (element-type 'character) buffer-size)
4937 (declare (ignorable stream linewise prefix element-type buffer-size))
4938 (cond
4939 #+genera
4940 ((functionp x) (funcall x stream))
4941 #+genera
4942 ((output-stream-p x)
4943 (copy-stream-to-stream
4944 stream x
4945 :linewise linewise :prefix prefix :element-type element-type :buffer-size buffer-size))
4946 (t
4947 (error "Invalid ~S destination ~S" 'slurp-input-stream x)))))
4948
4949
4950 (with-upgradability ()
4951 (defgeneric vomit-output-stream (processor output-stream &key)
4952 (:documentation
4953 "VOMIT-OUTPUT-STREAM is a generic function with two positional arguments
4954 PROCESSOR and OUTPUT-STREAM and additional keyword arguments, that produces (vomits)
4955 some content onto the OUTPUT-STREAM, according to a method specified by PROCESSOR.
4956
4957 Built-in methods include the following:
4958 * if PROCESSOR is a function, it is called with the OUTPUT-STREAM as its argument
4959 * if PROCESSOR is a list, its first element should be a function.
4960 It will be applied to a cons of the OUTPUT-STREAM and the rest of the list.
4961 That is (x . y) will be treated as \(APPLY x <stream> y\)
4962 * if PROCESSOR is an input-stream, its contents will be copied the OUTPUT-STREAM,
4963 per copy-stream-to-stream, with appropriate keyword arguments.
4964 * if PROCESSOR is a string, its contents will be printed to the OUTPUT-STREAM.
4965 * if PROCESSOR is T, it is treated the same as *standard-input*. If it is NIL, nothing is done.
4966
4967 Programmers are encouraged to define their own methods for this generic function."))
4968
4969 #-genera
4970 (defmethod vomit-output-stream ((function function) output-stream &key)
4971 (funcall function output-stream))
4972
4973 (defmethod vomit-output-stream ((list cons) output-stream &key)
4974 (apply (first list) output-stream (rest list)))
4975
4976 #-genera
4977 (defmethod vomit-output-stream ((input-stream stream) output-stream
4978 &key linewise prefix (element-type 'character) buffer-size)
4979 (copy-stream-to-stream
4980 input-stream output-stream
4981 :linewise linewise :prefix prefix :element-type element-type :buffer-size buffer-size))
4982
4983 (defmethod vomit-output-stream ((x string) stream &key fresh-line terpri)
4984 (princ x stream)
4985 (when fresh-line (fresh-line stream))
4986 (when terpri (terpri stream))
4987 (values))
4988
4989 (defmethod vomit-output-stream ((x (eql t)) stream &rest keys &key &allow-other-keys)
4990 (apply 'vomit-output-stream *standard-input* stream keys))
4991
4992 (defmethod vomit-output-stream ((x null) (stream t) &key)
4993 (values))
4994
4995 (defmethod vomit-output-stream ((pathname pathname) input
4996 &key
4997 (element-type *default-stream-element-type*)
4998 (external-format *utf-8-external-format*)
4999 (if-exists :rename-and-delete)
5000 (if-does-not-exist :create)
5001 buffer-size
5002 linewise)
5003 (with-output-file (output pathname
5004 :element-type element-type
5005 :external-format external-format
5006 :if-exists if-exists
5007 :if-does-not-exist if-does-not-exist)
5008 (copy-stream-to-stream
5009 input output
5010 :element-type element-type :buffer-size buffer-size :linewise linewise)))
5011
5012 (defmethod vomit-output-stream (x stream
5013 &key linewise prefix (element-type 'character) buffer-size)
5014 (declare (ignorable stream linewise prefix element-type buffer-size))
5015 (cond
5016 #+genera
5017 ((functionp x) (funcall x stream))
5018 #+genera
5019 ((input-stream-p x)
5020 (copy-stream-to-stream
5021 x stream
5022 :linewise linewise :prefix prefix :element-type element-type :buffer-size buffer-size))
5023 (t
5024 (error "Invalid ~S source ~S" 'vomit-output-stream x)))))
5025
5026
5027 ;;;; ----- Running an external program -----
5028 ;;; Simple variant of run-program with no input, and capturing output
5029 ;;; On some implementations, may output to a temporary file...
5030 (with-upgradability ()
5031 (define-condition subprocess-error (error)
5032 ((code :initform nil :initarg :code :reader subprocess-error-code)
5033 (command :initform nil :initarg :command :reader subprocess-error-command)
5034 (process :initform nil :initarg :process :reader subprocess-error-process))
5035 (:report (lambda (condition stream)
5036 (format stream "Subprocess ~@[~S~% ~]~@[with command ~S~% ~]exited with error~@[ code ~D~]"
5037 (subprocess-error-process condition)
5038 (subprocess-error-command condition)
5039 (subprocess-error-code condition)))))
5040
5041 ;;; find CMD.exe on windows
5042 (defun %cmd-shell-pathname ()
5043 (os-cond
5044 ((os-windows-p)
5045 (strcat (native-namestring (getenv-absolute-directory "WINDIR"))
5046 "System32\\cmd.exe"))
5047 (t
5048 (error "CMD.EXE is not the command shell for this OS."))))
5049
5050 ;;; Internal helpers for run-program
5051 (defun %normalize-command (command)
5052 "Given a COMMAND as a list or string, transform it in a format suitable
5053 for the implementation's underlying run-program function"
5054 (etypecase command
5055 #+os-unix (string `("/bin/sh" "-c" ,command))
5056 #+os-unix (list command)
5057 #+os-windows
5058 (string
5059 ;; NB: We do NOT add cmd /c here. You might want to.
5060 #+(or allegro clisp) command
5061 ;; On ClozureCL for Windows, we assume you are using
5062 ;; r15398 or later in 1.9 or later,
5063 ;; so that bug 858 is fixed http://trac.clozure.com/ccl/ticket/858
5064 #+clozure (cons "cmd" (strcat "/c " command))
5065 #+mkcl (list "cmd" "/c" command)
5066 #+sbcl (list (%cmd-shell-pathname) "/c" command)
5067 ;; NB: On other Windows implementations, this is utterly bogus
5068 ;; except in the most trivial cases where no quoting is needed.
5069 ;; Use at your own risk.
5070 #-(or allegro clisp clozure mkcl sbcl) (list "cmd" "/c" command))
5071 #+os-windows
5072 (list
5073 #+allegro (escape-windows-command command)
5074 #-allegro command)))
5075
5076 (defun %active-io-specifier-p (specifier)
5077 "Determines whether a run-program I/O specifier requires Lisp-side processing
5078 via SLURP-INPUT-STREAM or VOMIT-OUTPUT-STREAM (return T),
5079 or whether it's already taken care of by the implementation's underlying run-program."
5080 (not (typep specifier '(or null string pathname (member :interactive :output)
5081 #+(or cmucl (and sbcl os-unix) scl) (or stream (eql t))
5082 #+lispworks file-stream))))
5083
5084 (defun %normalize-io-specifier (specifier &optional role)
5085 "Normalizes a portable I/O specifier for %RUN-PROGRAM into an implementation-dependent
5086 argument to pass to the internal RUN-PROGRAM"
5087 (declare (ignorable role))
5088 (etypecase specifier
5089 (null (or #+(or allegro lispworks) (null-device-pathname)))
5090 (string (parse-native-namestring specifier))
5091 (pathname specifier)
5092 (stream specifier)
5093 ((eql :stream) :stream)
5094 ((eql :interactive)
5095 #+allegro nil
5096 #+clisp :terminal
5097 #+(or clozure cmucl ecl mkcl sbcl scl) t)
5098 #+(or abcl allegro clozure cmucl ecl lispworks mkcl sbcl scl)
5099 ((eql :output)
5100 (if (eq role :error-output)
5101 :output
5102 (error "Wrong specifier ~S for role ~S" specifier role)))))
5103
5104 (defun %normalize-if-exists (action)
5105 (ecase action
5106 (:supersede #+clisp :overwrite #-clisp action)
5107 ((:append :error) action)))
5108
5109 (defun %interactivep (input output error-output)
5110 (member :interactive (list input output error-output)))
5111
5112 (defun %signal-to-exit-code (signum)
5113 (+ 128 signum))
5114
5115 #+mkcl
5116 (defun %mkcl-signal-to-number (signal)
5117 (require :mk-unix)
5118 (symbol-value (find-symbol signal :mk-unix)))
5119
5120 (defclass process-info ()
5121 ((process :initform nil)
5122 (input-stream :initform nil)
5123 (output-stream :initform nil)
5124 (bidir-stream :initform nil)
5125 (error-output-stream :initform nil)
5126 ;; For backward-compatibility, to maintain the property (zerop
5127 ;; exit-code) <-> success, an exit in response to a signal is
5128 ;; encoded as 128+signum.
5129 (exit-code :initform nil)
5130 ;; If the platform allows it, distinguish exiting with a code
5131 ;; >128 from exiting in response to a signal by setting this code
5132 (signal-code :initform nil)))
5133
5134 (defun %run-program (command
5135 &rest keys
5136 &key input (if-input-does-not-exist :error)
5137 output (if-output-exists :supersede)
5138 error-output (if-error-output-exists :supersede)
5139 directory wait
5140 #+allegro separate-streams
5141 &allow-other-keys)
5142 "A portable abstraction of a low-level call to the implementation's run-program or equivalent.
5143 It spawns a subprocess that runs the specified COMMAND (a list of program and arguments).
5144 INPUT, OUTPUT and ERROR-OUTPUT specify a portable IO specifer,
5145 to be normalized by %NORMALIZE-IO-SPECIFIER.
5146 It returns a process-info object."
5147 ;; NB: these implementations have Unix vs Windows set at compile-time.
5148 (declare (ignorable directory if-input-does-not-exist if-output-exists if-error-output-exists))
5149 #-(or abcl allegro clisp clozure cmucl ecl (and lispworks os-unix) mkcl sbcl scl)
5150 (progn command keys input output error-output directory wait ;; ignore
5151 (not-implemented-error '%run-program))
5152 #-(or abcl cmucl ecl mkcl sbcl)
5153 (when (and wait (member :stream (list input output error-output)))
5154 (parameter-error "~S: I/O parameters cannot be ~S when ~S is ~S on this lisp"
5155 '%run-program :stream :wait t))
5156 #+allegro
5157 (when (some #'(lambda (stream)
5158 (and (streamp stream)
5159 (not (file-stream-p stream))))
5160 (list input output error-output))
5161 (parameter-error "~S: Streams passed as I/O parameters need to be file streams on this lisp"
5162 '%run-program))
5163 #+(or abcl clisp lispworks)
5164 (when (some #'streamp (list input output error-output))
5165 (parameter-error "~S: I/O parameters cannot be foreign streams on this lisp"
5166 '%run-program))
5167 #+clisp
5168 (unless (eq error-output :interactive)
5169 (parameter-error "~S: The only admissible value for ~S is ~S on this lisp"
5170 '%run-program :error-output :interactive))
5171 #+clisp
5172 (when (or (stringp input) (pathnamep input))
5173 (unless (file-exists-p input)
5174 (parameter-error "~S: Files passed as arguments to ~S need to exist on this lisp"
5175 '%run-program :input)))
5176 #+ecl
5177 (when (some #'(lambda (stream)
5178 (and (streamp stream)
5179 (not (file-or-synonym-stream-p stream))))
5180 (list input output error-output))
5181 (parameter-error "~S: Streams passed as I/O parameters need to be (synonymous with) file streams on this lisp"
5182 '%run-program))
5183 #+(or abcl allegro clisp clozure cmucl ecl (and lispworks os-unix) mkcl sbcl scl)
5184 (let* ((%command (%normalize-command command))
5185 (%if-output-exists (%normalize-if-exists if-output-exists))
5186 (%input (%normalize-io-specifier input :input))
5187 (%output (%normalize-io-specifier output :output))
5188 (%error-output (%normalize-io-specifier error-output :error-output))
5189 #+(and allegro os-windows)
5190 (interactive (%interactivep input output error-output))
5191 (process*
5192 (nest
5193 #-(or allegro mkcl sbcl) (with-current-directory (directory))
5194 #+(or allegro clisp ecl lispworks mkcl) (multiple-value-list)
5195 (apply
5196 #+abcl #'sys:run-program
5197 #+allegro 'excl:run-shell-command
5198 #+(and allegro os-unix) (coerce (cons (first %command) %command) 'vector)
5199 #+(and allegro os-windows) %command
5200 #+clisp
5201 (etypecase %command
5202 #+os-windows
5203 (string (lambda (&rest keys) (apply 'ext:run-shell-command %command keys)))
5204 (list (lambda (&rest keys)
5205 (apply 'ext:run-program (car %command) :arguments (cdr %command) keys))))
5206 #+clozure 'ccl:run-program
5207 #+(or cmucl ecl scl) 'ext:run-program
5208 #+lispworks 'system:run-shell-command
5209 #+lispworks (cons "/usr/bin/env" %command) ; LW wants a full path
5210 #+mkcl 'mk-ext:run-program
5211 #+sbcl 'sb-ext:run-program
5212 (append
5213 #+(or abcl clozure cmucl ecl mkcl sbcl scl) `(,(car %command) ,(cdr %command))
5214 `(:input ,%input :output ,%output :wait ,wait :allow-other-keys t)
5215 #-clisp `(#+(or allegro lispworks) :error-output #-(or allegro lispworks) :error
5216 ,%error-output)
5217 #+(and allegro os-windows) `(:show-window ,(if interactive nil :hide))
5218 #+clisp `(:if-output-exists ,%if-output-exists)
5219 #+(or abcl allegro clozure cmucl ecl lispworks mkcl sbcl scl)
5220 `(:if-input-does-not-exist ,if-input-does-not-exist
5221 :if-output-exists ,%if-output-exists
5222 #-(or allegro lispworks) :if-error-exists
5223 #+(or allegro lispworks) :if-error-output-exists
5224 ,if-error-output-exists)
5225 #+lispworks `(:save-exit-status t)
5226 #+mkcl `(:directory ,(native-namestring directory))
5227 #+sbcl `(:search t)
5228 #-sbcl keys
5229 #+sbcl (if directory keys (remove-plist-key :directory keys))))))
5230 (process-info (make-instance 'process-info)))
5231 #+clisp (declare (ignore %error-output))
5232 (labels ((prop (key value) (setf (slot-value process-info key) value))
5233 #+(or allegro clisp ecl lispworks mkcl)
5234 (store-codes (exit-code &optional signal-code)
5235 (if signal-code
5236 (progn (prop 'exit-code (%signal-to-exit-code signal-code))
5237 (prop 'signal-code signal-code))
5238 (prop 'exit-code exit-code))))
5239 #+allegro
5240 (cond
5241 (wait (store-codes (first process*)))
5242 (separate-streams
5243 (destructuring-bind (in out err pid) process*
5244 (prop 'process pid)
5245 (when (eq input :stream) (prop 'input-stream in))
5246 (when (eq output :stream) (prop 'output-stream out))
5247 (when (eq error-output :stream) (prop 'error-stream err))))
5248 (t
5249 (prop 'process (third process*))
5250 (let ((x (first process*)))
5251 (ecase (+ (if (eq input :stream) 1 0) (if (eq output :stream) 2 0))
5252 (0)
5253 (1 (prop 'input-stream x))
5254 (2 (prop 'output-stream x))
5255 (3 (prop 'bidir-stream x))))
5256 (when (eq error-output :stream)
5257 (prop 'error-stream (second process*)))))
5258 #+clisp
5259 (if wait
5260 (let ((raw-exit-code (or (first process*) 0)))
5261 (if (minusp raw-exit-code)
5262 (store-codes 0 (- raw-exit-code))
5263 (store-codes raw-exit-code)))
5264 (ecase (+ (if (eq input :stream) 1 0) (if (eq output :stream) 2 0))
5265 (0)
5266 (1 (prop 'input-stream (first process*)))
5267 (2 (prop 'output-stream (first process*)))
5268 (3 (prop 'bidir-stream (pop process*))
5269 (prop 'input-stream (pop process*))
5270 (prop 'output-stream (pop process*)))))
5271 #+(or abcl clozure cmucl sbcl scl)
5272 (progn
5273 (prop 'process process*)
5274 (when (eq input :stream)
5275 (prop 'input-stream
5276 #+abcl (symbol-call :sys :process-input process*)
5277 #+clozure (ccl:external-process-input-stream process*)
5278 #+(or cmucl scl) (ext:process-input process*)
5279 #+sbcl (sb-ext:process-input process*)))
5280 (when (eq output :stream)
5281 (prop 'output-stream
5282 #+abcl (symbol-call :sys :process-output process*)
5283 #+clozure (ccl:external-process-output-stream process*)
5284 #+(or cmucl scl) (ext:process-output process*)
5285 #+sbcl (sb-ext:process-output process*)))
5286 (when (eq error-output :stream)
5287 (prop 'error-output-stream
5288 #+abcl (symbol-call :sys :process-error process*)
5289 #+clozure (ccl:external-process-error-stream process*)
5290 #+(or cmucl scl) (ext:process-error process*)
5291 #+sbcl (sb-ext:process-error process*))))
5292 #+(or ecl mkcl)
5293 (destructuring-bind #+ecl (stream code process) #+mkcl (stream process code) process*
5294 (let ((mode (+ (if (eq input :stream) 1 0) (if (eq output :stream) 2 0))))
5295 (cond
5296 ((zerop mode))
5297 ((null process*) (store-codes -1))
5298 (t (prop (case mode (1 'input-stream) (2 'output-stream) (3 'bidir-stream)) stream))))
5299 (when code
5300 (let ((signum #+mkcl (and (stringp code) (%mkcl-signal-to-number code))
5301 #-mkcl (and (eq (ext:external-process-wait process)
5302 :signaled)
5303 code)))
5304 (store-codes code signum)))
5305 (when process (prop 'process process)))
5306 #+lispworks
5307 (if wait
5308 (store-codes (first process*) (second process*))
5309 (let ((mode (+ (if (eq input :stream) 1 0) (if (eq output :stream) 2 0))))
5310 (if (or (plusp mode) (eq error-output :stream))
5311 (destructuring-bind (io err pid) process*
5312 #+lispworks7+ (declare (ignore pid))
5313 (prop 'process #+lispworks7+ io #-lispworks7+ pid)
5314 (when (plusp mode)
5315 (prop (ecase mode
5316 (1 'input-stream)
5317 (2 'output-stream)
5318 (3 'bidir-stream)) io))
5319 (when (eq error-output :stream)
5320 (prop 'error-stream err)))
5321 ;; lispworks6 returns (pid), lispworks7 returns (io,err,pid).
5322 (prop 'process (first process*)))))
5323 process-info)))
5324
5325 (defun process-info-error-output (process-info)
5326 (slot-value process-info 'error-output-stream))
5327 (defun process-info-input (process-info)
5328 (or (slot-value process-info 'bidir-stream)
5329 (slot-value process-info 'input-stream)))
5330 (defun process-info-output (process-info)
5331 (or (slot-value process-info 'bidir-stream)
5332 (slot-value process-info 'output-stream)))
5333
5334 (defun process-info-pid (process-info)
5335 (let ((process (slot-value process-info 'process)))
5336 (declare (ignorable process))
5337 #+abcl (symbol-call :sys :process-pid process)
5338 #+allegro process
5339 #+clozure (ccl:external-process-id process)
5340 #+ecl (ext:external-process-pid process)
5341 #+(or cmucl scl) (ext:process-pid process)
5342 #+lispworks7+ (sys:pipe-pid process)
5343 #+(and lispworks (not lispworks7+)) process
5344 #+mkcl (mkcl:process-id process)
5345 #+sbcl (sb-ext:process-pid process)
5346 #-(or abcl allegro clozure cmucl ecl mkcl lispworks sbcl scl)
5347 (not-implemented-error 'process-info-pid)))
5348
5349 (defun %process-status (process-info)
5350 (if-let (exit-code (slot-value process-info 'exit-code))
5351 (return-from %process-status
5352 (if-let (signal-code (slot-value process-info 'signal-code))
5353 (values :signaled signal-code)
5354 (values :exited exit-code))))
5355 #-(or allegro clozure cmucl ecl lispworks mkcl sbcl scl)
5356 (not-implemented-error '%process-status)
5357 (if-let (process (slot-value process-info 'process))
5358 (multiple-value-bind (status code)
5359 (progn
5360 #+allegro (multiple-value-bind (exit-code pid signal)
5361 (sys:reap-os-subprocess :pid process :wait nil)
5362 (assert pid)
5363 (cond ((null exit-code) :running)
5364 ((null signal) (values :exited exit-code))
5365 (t (values :signaled signal))))
5366 #+clozure (ccl:external-process-status process)
5367 #+(or cmucl scl) (let ((status (ext:process-status process)))
5368 (values status (if (member status '(:exited :signaled))
5369 (ext:process-exit-code process))))
5370 #+ecl (ext:external-process-status process)
5371 #+lispworks
5372 ;; a signal is only returned on LispWorks 7+
5373 (multiple-value-bind (exit-code signal)
5374 (funcall #+lispworks7+ #'sys:pipe-exit-status
5375 #-lispworks7+ #'sys:pid-exit-status
5376 process :wait nil)
5377 (cond ((null exit-code) :running)
5378 ((null signal) (values :exited exit-code))
5379 (t (values :signaled signal))))
5380 #+mkcl (let ((status (mk-ext:process-status process))
5381 (code (mk-ext:process-exit-code process)))
5382 (if (stringp code)
5383 (values :signaled (%mkcl-signal-to-number code))
5384 (values status code)))
5385 #+sbcl (let ((status (sb-ext:process-status process)))
5386 (values status (if (member status '(:exited :signaled))
5387 (sb-ext:process-exit-code process)))))
5388 (case status
5389 (:exited (setf (slot-value process-info 'exit-code) code))
5390 (:signaled (let ((%code (%signal-to-exit-code code)))
5391 (setf (slot-value process-info 'exit-code) %code
5392 (slot-value process-info 'signal-code) code))))
5393 (values status code))))
5394
5395 (defun process-alive-p (process-info)
5396 "Check if a process has yet to exit."
5397 (unless (slot-value process-info 'exit-code)
5398 #+abcl (sys:process-alive-p (slot-value process-info 'process))
5399 #+(or cmucl scl) (ext:process-alive-p (slot-value process-info 'process))
5400 #+sbcl (sb-ext:process-alive-p (slot-value process-info 'process))
5401 #-(or abcl cmucl sbcl scl) (member (%process-status process-info)
5402 '(:running :sleeping))))
5403
5404 (defun wait-process (process-info)
5405 "Wait for the process to terminate, if it is still running.
5406 Otherwise, return immediately. An exit code (a number) will be
5407 returned, with 0 indicating success, and anything else indicating
5408 failure. If the process exits after receiving a signal, the exit code
5409 will be the sum of 128 and the (positive) numeric signal code. A second
5410 value may be returned in this case: the numeric signal code itself.
5411 Any asynchronously spawned process requires this function to be run
5412 before it is garbage-collected in order to free up resources that
5413 might otherwise be irrevocably lost."
5414 (if-let (exit-code (slot-value process-info 'exit-code))
5415 (if-let (signal-code (slot-value process-info 'signal-code))
5416 (values exit-code signal-code)
5417 exit-code)
5418 (let ((process (slot-value process-info 'process)))
5419 #-(or abcl allegro clozure cmucl ecl lispworks mkcl sbcl scl)
5420 (not-implemented-error 'wait-process)
5421 (when process
5422 ;; 1- wait
5423 #+clozure (ccl::external-process-wait process)
5424 #+(or cmucl scl) (ext:process-wait process)
5425 #+sbcl (sb-ext:process-wait process)
5426 ;; 2- extract result
5427 (multiple-value-bind (exit-code signal-code)
5428 (progn
5429 #+abcl (sys:process-wait process)
5430 #+allegro (multiple-value-bind (exit-code pid signal)
5431 (sys:reap-os-subprocess :pid process :wait t)
5432 (assert pid)
5433 (values exit-code signal))
5434 #+clozure (multiple-value-bind (status code)
5435 (ccl:external-process-status process)
5436 (if (eq status :signaled)
5437 (values nil code)
5438 code))
5439 #+(or cmucl scl) (let ((status (ext:process-status process))
5440 (code (ext:process-exit-code process)))
5441 (if (eq status :signaled)
5442 (values nil code)
5443 code))
5444 #+ecl (multiple-value-bind (status code)
5445 (ext:external-process-wait process t)
5446 (if (eq status :signaled)
5447 (values nil code)
5448 code))
5449 #+lispworks (funcall #+lispworks7+ #'sys:pipe-exit-status
5450 #-lispworks7+ #'sys:pid-exit-status
5451 process :wait t)
5452 #+mkcl (let ((code (mkcl:join-process process)))
5453 (if (stringp code)
5454 (values nil (%mkcl-signal-to-number code))
5455 code))
5456 #+sbcl (let ((status (sb-ext:process-status process))
5457 (code (sb-ext:process-exit-code process)))
5458 (if (eq status :signaled)
5459 (values nil code)
5460 code)))
5461 (if signal-code
5462 (let ((%exit-code (%signal-to-exit-code signal-code)))
5463 (setf (slot-value process-info 'exit-code) %exit-code
5464 (slot-value process-info 'signal-code) signal-code)
5465 (values %exit-code signal-code))
5466 (progn (setf (slot-value process-info 'exit-code) exit-code)
5467 exit-code)))))))
5468
5469 (defun %check-result (exit-code &key command process ignore-error-status)
5470 (unless ignore-error-status
5471 (unless (eql exit-code 0)
5472 (cerror "IGNORE-ERROR-STATUS"
5473 'subprocess-error :command command :code exit-code :process process)))
5474 exit-code)
5475
5476 (defun close-streams (process-info)
5477 "Close any stream that the process might own. Needs to be run
5478 whenever streams were requested by passing :stream to :input, :output,
5479 or :error-output."
5480 (dolist (stream
5481 (cons (slot-value process-info 'error-output-stream)
5482 (if-let (bidir-stream (slot-value process-info 'bidir-stream))
5483 (list bidir-stream)
5484 (list (slot-value process-info 'input-stream)
5485 (slot-value process-info 'output-stream)))))
5486 (when stream (close stream))))
5487
5488 ;; WARNING: For signals other than SIGTERM and SIGKILL this may not
5489 ;; do what you expect it to. Sending SIGSTOP to a process spawned
5490 ;; via %run-program, e.g., will stop the shell /bin/sh that is used
5491 ;; to run the command (via `sh -c command`) but not the actual
5492 ;; command.
5493 #+os-unix
5494 (defun %posix-send-signal (process-info signal)
5495 #+allegro (excl.osi:kill (slot-value process-info 'process) signal)
5496 #+clozure (ccl:signal-external-process (slot-value process-info 'process)
5497 signal :error-if-exited nil)
5498 #+(or cmucl scl) (ext:process-kill (slot-value process-info 'process) signal)
5499 #+sbcl (sb-ext:process-kill (slot-value process-info 'process) signal)
5500 #-(or allegro clozure cmucl sbcl scl)
5501 (if-let (pid (process-info-pid process-info))
5502 (%run-program (format nil "kill -~a ~a" signal pid) :wait t)))
5503
5504 ;;; this function never gets called on Windows, but the compiler cannot tell
5505 ;;; that. [2016/09/25:rpg]
5506 #+os-windows
5507 (defun %posix-send-signal (process-info signal)
5508 (declare (ignore process-info signal))
5509 (values))
5510
5511 (defun terminate-process (process-info &key urgent)
5512 "Cause the process to exit. To that end, the process may or may
5513 not be sent a signal, which it will find harder (or even impossible)
5514 to ignore if URGENT is T. On some platforms, it may also be subject to
5515 race conditions."
5516 (declare (ignorable urgent))
5517 #+abcl (sys:process-kill (slot-value process-info 'process))
5518 #+ecl (symbol-call :ext :terminate-process
5519 (slot-value process-info 'process) urgent)
5520 #+lispworks7+ (sys:pipe-kill-process (slot-value process-info 'process))
5521 #+mkcl (mk-ext:terminate-process (slot-value process-info 'process)
5522 :force urgent)
5523 #-(or abcl ecl lispworks7+ mkcl)
5524 (os-cond
5525 ((os-unix-p) (%posix-send-signal process-info (if urgent 9 15)))
5526 ((os-windows-p) (if-let (pid (process-info-pid process-info))
5527 (%run-program (format nil "taskkill ~a /pid ~a"
5528 (if urgent "/f" "") pid))))
5529 (t (not-implemented-error 'terminate-process))))
5530
5531 (defun %call-with-program-io (gf tval stream-easy-p fun direction spec activep returner
5532 &key element-type external-format &allow-other-keys)
5533 ;; handle redirection for run-program and system
5534 ;; SPEC is the specification for the subprocess's input or output or error-output
5535 ;; TVAL is the value used if the spec is T
5536 ;; GF is the generic function to call to handle arbitrary values of SPEC
5537 ;; STREAM-EASY-P is T if we're going to use a RUN-PROGRAM that copies streams in the background
5538 ;; (it's only meaningful on CMUCL, SBCL, SCL that actually do it)
5539 ;; DIRECTION is :INPUT, :OUTPUT or :ERROR-OUTPUT for the direction of this io argument
5540 ;; FUN is a function of the new reduced spec and an activity function to call with a stream
5541 ;; when the subprocess is active and communicating through that stream.
5542 ;; ACTIVEP is a boolean true if we will get to run code while the process is running
5543 ;; ELEMENT-TYPE and EXTERNAL-FORMAT control what kind of temporary file we may open.
5544 ;; RETURNER is a function called with the value of the activity.
5545 ;; --- TODO ([email protected]): handle if-output-exists and such when doing it the hard way.
5546 (declare (ignorable stream-easy-p))
5547 (let* ((actual-spec (if (eq spec t) tval spec))
5548 (activity-spec (if (eq actual-spec :output)
5549 (ecase direction
5550 ((:input :output)
5551 (error "~S not allowed as a ~S ~S spec"
5552 :output 'run-program direction))
5553 ((:error-output)
5554 nil))
5555 actual-spec)))
5556 (labels ((activity (stream)
5557 (call-function returner (call-stream-processor gf activity-spec stream)))
5558 (easy-case ()
5559 (funcall fun actual-spec nil))
5560 (hard-case ()
5561 (if activep
5562 (funcall fun :stream #'activity)
5563 (with-temporary-file (:pathname tmp)
5564 (ecase direction
5565 (:input
5566 (with-output-file (s tmp :if-exists :overwrite
5567 :external-format external-format
5568 :element-type element-type)
5569 (activity s))
5570 (funcall fun tmp nil))
5571 ((:output :error-output)
5572 (multiple-value-prog1 (funcall fun tmp nil)
5573 (with-input-file (s tmp
5574 :external-format external-format
5575 :element-type element-type)
5576 (activity s)))))))))
5577 (typecase activity-spec
5578 ((or null string pathname (eql :interactive))
5579 (easy-case))
5580 #+(or cmucl (and sbcl os-unix) scl) ;; streams are only easy on implementations that try very hard
5581 (stream
5582 (if stream-easy-p (easy-case) (hard-case)))
5583 (t
5584 (hard-case))))))
5585
5586 (defmacro place-setter (place)
5587 (when place
5588 (let ((value (gensym)))
5589 `#'(lambda (,value) (setf ,place ,value)))))
5590
5591 (defmacro with-program-input (((reduced-input-var
5592 &optional (input-activity-var (gensym) iavp))
5593 input-form &key setf stream-easy-p active keys) &body body)
5594 `(apply '%call-with-program-io 'vomit-output-stream *standard-input* ,stream-easy-p
5595 #'(lambda (,reduced-input-var ,input-activity-var)
5596 ,@(unless iavp `((declare (ignore ,input-activity-var))))
5597 ,@body)
5598 :input ,input-form ,active (place-setter ,setf) ,keys))
5599
5600 (defmacro with-program-output (((reduced-output-var
5601 &optional (output-activity-var (gensym) oavp))
5602 output-form &key setf stream-easy-p active keys) &body body)
5603 `(apply '%call-with-program-io 'slurp-input-stream *standard-output* ,stream-easy-p
5604 #'(lambda (,reduced-output-var ,output-activity-var)
5605 ,@(unless oavp `((declare (ignore ,output-activity-var))))
5606 ,@body)
5607 :output ,output-form ,active (place-setter ,setf) ,keys))
5608
5609 (defmacro with-program-error-output (((reduced-error-output-var
5610 &optional (error-output-activity-var (gensym) eoavp))
5611 error-output-form &key setf stream-easy-p active keys)
5612 &body body)
5613 `(apply '%call-with-program-io 'slurp-input-stream *error-output* ,stream-easy-p
5614 #'(lambda (,reduced-error-output-var ,error-output-activity-var)
5615 ,@(unless eoavp `((declare (ignore ,error-output-activity-var))))
5616 ,@body)
5617 :error-output ,error-output-form ,active (place-setter ,setf) ,keys))
5618
5619 (defun %use-run-program (command &rest keys
5620 &key input output error-output ignore-error-status &allow-other-keys)
5621 ;; helper for RUN-PROGRAM when using %run-program
5622 #+(or cormanlisp gcl (and lispworks os-windows) mcl xcl)
5623 (progn
5624 command keys input output error-output ignore-error-status ;; ignore
5625 (not-implemented-error '%use-run-program))
5626 (assert (not (member :stream (list input output error-output))))
5627 (let* ((active-input-p (%active-io-specifier-p input))
5628 (active-output-p (%active-io-specifier-p output))
5629 (active-error-output-p (%active-io-specifier-p error-output))
5630 (activity
5631 (cond
5632 (active-output-p :output)
5633 (active-input-p :input)
5634 (active-error-output-p :error-output)
5635 (t nil)))
5636 (wait (not activity))
5637 output-result error-output-result exit-code process-info)
5638 (with-program-output ((reduced-output output-activity)
5639 output :keys keys :setf output-result
5640 :stream-easy-p t :active (eq activity :output))
5641 (with-program-error-output ((reduced-error-output error-output-activity)
5642 error-output :keys keys :setf error-output-result
5643 :stream-easy-p t :active (eq activity :error-output))
5644 (with-program-input ((reduced-input input-activity)
5645 input :keys keys
5646 :stream-easy-p t :active (eq activity :input))
5647 (setf process-info
5648 (apply '%run-program command
5649 :wait wait :input reduced-input :output reduced-output
5650 :error-output (if (eq error-output :output) :output reduced-error-output)
5651 keys))
5652 (labels ((get-stream (stream-name &optional fallbackp)
5653 (or (slot-value process-info stream-name)
5654 (when fallbackp
5655 (slot-value process-info 'bidir-stream))))
5656 (run-activity (activity stream-name &optional fallbackp)
5657 (if-let (stream (get-stream stream-name fallbackp))
5658 (funcall activity stream)
5659 (error 'subprocess-error
5660 :code `(:missing ,stream-name)
5661 :command command :process process-info))))
5662 (unwind-protect
5663 (ecase activity
5664 ((nil))
5665 (:input (run-activity input-activity 'input-stream t))
5666 (:output (run-activity output-activity 'output-stream t))
5667 (:error-output (run-activity error-output-activity 'error-output-stream)))
5668 (close-streams process-info)
5669 (setf exit-code (wait-process process-info)))))))
5670 (%check-result exit-code
5671 :command command :process process-info
5672 :ignore-error-status ignore-error-status)
5673 (values output-result error-output-result exit-code)))
5674
5675 (defun %normalize-system-command (command) ;; helper for %USE-SYSTEM
5676 (etypecase command
5677 (string
5678 (os-cond
5679 ((os-windows-p)
5680 #+(or allegro clisp)
5681 (strcat (%cmd-shell-pathname) " /c " command)
5682 #-(or allegro clisp) command)
5683 (t command)))
5684 (list (escape-shell-command
5685 (os-cond
5686 ((os-unix-p) (cons "exec" command))
5687 ((os-windows-p)
5688 #+(or allegro sbcl clisp)
5689 (cons (%cmd-shell-pathname) (cons "/c" command))
5690 #-(or allegro sbcl clisp) command)
5691 (t command))))))
5692
5693 (defun %redirected-system-command (command in out err directory) ;; helper for %USE-SYSTEM
5694 (flet ((redirect (spec operator)
5695 (let ((pathname
5696 (typecase spec
5697 (null (null-device-pathname))
5698 (string (parse-native-namestring spec))
5699 (pathname spec)
5700 ((eql :output)
5701 (assert (equal operator " 2>"))
5702 (return-from redirect '(" 2>&1"))))))
5703 (when pathname
5704 (list operator " "
5705 (escape-shell-token (native-namestring pathname)))))))
5706 (let* ((redirections (append (redirect in " <") (redirect out " >") (redirect err " 2>")))
5707 (normalized (%normalize-system-command command))
5708 (directory (or directory #+(or abcl xcl) (getcwd)))
5709 (chdir (when directory
5710 (let ((dir-arg (escape-shell-token (native-namestring directory))))
5711 (os-cond
5712 ((os-unix-p) `("cd " ,dir-arg " ; "))
5713 ((os-windows-p) `("cd /d " ,dir-arg " & ")))))))
5714 (reduce/strcat
5715 (os-cond
5716 ((os-unix-p) `(,@(when redirections `("exec " ,@redirections " ; ")) ,@chdir ,normalized))
5717 ((os-windows-p) `(,@chdir ,@redirections " " ,normalized)))))))
5718
5719 (defun %system (command &rest keys
5720 &key input output error-output directory &allow-other-keys)
5721 "A portable abstraction of a low-level call to libc's system()."
5722 (declare (ignorable input output error-output directory keys))
5723 #+(or allegro clozure cmucl (and lispworks os-unix) sbcl scl)
5724 (wait-process
5725 (apply '%run-program (%normalize-system-command command) :wait t keys))
5726 #+(or abcl clasp clisp cormanlisp ecl gcl genera (and lispworks os-windows) mkcl xcl)
5727 (let ((%command (%redirected-system-command command input output error-output directory)))
5728 #+(and lispworks os-windows)
5729 (system:call-system %command :current-directory directory :wait t)
5730 #+clisp
5731 (wait-process
5732 (apply '%run-program %command :wait t
5733 :input :interactive :output :interactive :error-output :interactive keys))
5734 #-(or clisp (and lispworks os-windows))
5735 (with-current-directory ((os-cond ((not (os-unix-p)) directory)))
5736 #+abcl (ext:run-shell-command %command) ;; FIXME: deprecated
5737 #+cormanlisp (win32:system %command)
5738 #+(or clasp ecl) (let ((*standard-input* *stdin*)
5739 (*standard-output* *stdout*)
5740 (*error-output* *stderr*))
5741 (ext:system %command))
5742 #+gcl (system:system %command)
5743 #+genera (not-implemented-error '%system)
5744 #+mcl (ccl::with-cstrs ((%%command %command)) (_system %%command))
5745 #+mkcl (mkcl:system %command)
5746 #+xcl (system:%run-shell-command %command))))
5747
5748 (defun %use-system (command &rest keys
5749 &key input output error-output ignore-error-status &allow-other-keys)
5750 ;; helper for RUN-PROGRAM when using %system
5751 (let (output-result error-output-result exit-code)
5752 (with-program-output ((reduced-output)
5753 output :keys keys :setf output-result)
5754 (with-program-error-output ((reduced-error-output)
5755 error-output :keys keys :setf error-output-result)
5756 (with-program-input ((reduced-input) input :keys keys)
5757 (setf exit-code (apply '%system command
5758 :input reduced-input :output reduced-output
5759 :error-output reduced-error-output keys)))))
5760 (%check-result exit-code
5761 :command command
5762 :ignore-error-status ignore-error-status)
5763 (values output-result error-output-result exit-code)))
5764
5765 (defun launch-program (command &rest keys &key
5766 input (if-input-does-not-exist :error)
5767 output (if-output-exists :supersede)
5768 error-output (if-error-output-exists :supersede)
5769 (element-type #-clozure *default-stream-element-type*
5770 #+clozure 'character)
5771 (external-format *utf-8-external-format*)
5772 &allow-other-keys)
5773 "Launch program specified by COMMAND,
5774 either a list of strings specifying a program and list of arguments,
5775 or a string specifying a shell command (/bin/sh on Unix, CMD.EXE on
5776 Windows) _asynchronously_.
5777
5778 If OUTPUT is a pathname, a string designating a pathname, or NIL
5779 designating the null device, the file at that path is used as output.
5780 If it's :INTERACTIVE, output is inherited from the current process;
5781 beware that this may be different from your *STANDARD-OUTPUT*, and
5782 under SLIME will be on your *inferior-lisp* buffer. If it's T, output
5783 goes to your current *STANDARD-OUTPUT* stream. If it's :STREAM, a new
5784 stream will be made available that can be accessed via
5785 PROCESS-INFO-OUTPUT and read from. Otherwise, OUTPUT should be a value
5786 that the underlying lisp implementation knows how to handle.
5787
5788 ERROR-OUTPUT is similar to OUTPUT. T designates the *ERROR-OUTPUT*,
5789 :OUTPUT means redirecting the error output to the output stream,
5790 and :STREAM causes a stream to be made available via
5791 PROCESS-INFO-ERROR-OUTPUT.
5792
5793 INPUT is similar to OUTPUT, except that T designates the
5794 *STANDARD-INPUT* and a stream requested through the :STREAM keyword
5795 would be available through PROCESS-INFO-INPUT.
5796
5797 ELEMENT-TYPE and EXTERNAL-FORMAT are passed on to your Lisp
5798 implementation, when applicable, for creation of the output stream.
5799
5800 LAUNCH-PROGRAM returns a process-info object."
5801 (apply '%run-program command
5802 :wait nil
5803 :input input :if-input-does-not-exist if-input-does-not-exist
5804 :output output :if-output-exists if-output-exists
5805 :error-output error-output :if-error-output-exists if-error-output-exists
5806 :element-type element-type :external-format external-format
5807 keys))
5808
5809 (defun run-program (command &rest keys
5810 &key ignore-error-status (force-shell nil force-shell-suppliedp)
5811 (input nil inputp) (if-input-does-not-exist :error)
5812 output (if-output-exists :supersede)
5813 (error-output nil error-output-p) (if-error-output-exists :supersede)
5814 (element-type #-clozure *default-stream-element-type* #+clozure 'character)
5815 (external-format *utf-8-external-format*)
5816 &allow-other-keys)
5817 "Run program specified by COMMAND,
5818 either a list of strings specifying a program and list of arguments,
5819 or a string specifying a shell command (/bin/sh on Unix, CMD.EXE on Windows);
5820 _synchronously_ process its output as specified and return the processing results
5821 when the program and its output processing are complete.
5822
5823 Always call a shell (rather than directly execute the command when possible)
5824 if FORCE-SHELL is specified. Similarly, never call a shell if FORCE-SHELL is
5825 specified to be NIL.
5826
5827 Signal a continuable SUBPROCESS-ERROR if the process wasn't successful (exit-code 0),
5828 unless IGNORE-ERROR-STATUS is specified.
5829
5830 If OUTPUT is a pathname, a string designating a pathname, or NIL designating the null device,
5831 the file at that path is used as output.
5832 If it's :INTERACTIVE, output is inherited from the current process;
5833 beware that this may be different from your *STANDARD-OUTPUT*,
5834 and under SLIME will be on your *inferior-lisp* buffer.
5835 If it's T, output goes to your current *STANDARD-OUTPUT* stream.
5836 Otherwise, OUTPUT should be a value that is a suitable first argument to
5837 SLURP-INPUT-STREAM (qv.), or a list of such a value and keyword arguments.
5838 In this case, RUN-PROGRAM will create a temporary stream for the program output;
5839 the program output, in that stream, will be processed by a call to SLURP-INPUT-STREAM,
5840 using OUTPUT as the first argument (or the first element of OUTPUT, and the rest as keywords).
5841 The primary value resulting from that call (or NIL if no call was needed)
5842 will be the first value returned by RUN-PROGRAM.
5843 E.g., using :OUTPUT :STRING will have it return the entire output stream as a string.
5844 And using :OUTPUT '(:STRING :STRIPPED T) will have it return the same string
5845 stripped of any ending newline.
5846
5847 ERROR-OUTPUT is similar to OUTPUT, except that the resulting value is returned
5848 as the second value of RUN-PROGRAM. T designates the *ERROR-OUTPUT*.
5849 Also :OUTPUT means redirecting the error output to the output stream,
5850 in which case NIL is returned.
5851
5852 INPUT is similar to OUTPUT, except that VOMIT-OUTPUT-STREAM is used,
5853 no value is returned, and T designates the *STANDARD-INPUT*.
5854
5855 ELEMENT-TYPE and EXTERNAL-FORMAT are passed on
5856 to your Lisp implementation, when applicable, for creation of the output stream.
5857
5858 One and only one of the stream slurping or vomiting may or may not happen
5859 in parallel in parallel with the subprocess,
5860 depending on options and implementation,
5861 and with priority being given to output processing.
5862 Other streams are completely produced or consumed
5863 before or after the subprocess is spawned, using temporary files.
5864
5865 RUN-PROGRAM returns 3 values:
5866 0- the result of the OUTPUT slurping if any, or NIL
5867 1- the result of the ERROR-OUTPUT slurping if any, or NIL
5868 2- either 0 if the subprocess exited with success status,
5869 or an indication of failure via the EXIT-CODE of the process"
5870 (declare (ignorable ignore-error-status))
5871 #-(or abcl allegro clasp clisp clozure cmucl cormanlisp ecl gcl lispworks mcl mkcl sbcl scl xcl)
5872 (not-implemented-error 'run-program)
5873 ;; per doc string, set FORCE-SHELL to T if we get command as a string. But
5874 ;; don't override user's specified preference. [2015/06/29:rpg]
5875 (when (stringp command)
5876 (unless force-shell-suppliedp
5877 #-(and sbcl os-windows) ;; force-shell t isn't working properly on windows as of sbcl 1.2.16
5878 (setf force-shell t)))
5879 (flet ((default (x xp output) (cond (xp x) ((eq output :interactive) :interactive))))
5880 (apply (if (or force-shell
5881 #+(or clasp clisp) t
5882 ;; A race condition in ECL <= 16.0.0 prevents using ext:run-program
5883 #+ecl #.(if-let (ver (parse-version (lisp-implementation-version)))
5884 (lexicographic<= '< ver '(16 0 1)))
5885 #+(and lispworks os-unix) (%interactivep input output error-output)
5886 #+(or cormanlisp gcl (and lispworks os-windows) mcl xcl) t)
5887 '%use-system '%use-run-program)
5888 command
5889 :input (default input inputp output)
5890 :error-output (default error-output error-output-p output)
5891 :if-input-does-not-exist if-input-does-not-exist
5892 :if-output-exists if-output-exists
5893 :if-error-output-exists if-error-output-exists
5894 :element-type element-type :external-format external-format
5895 keys))))
5896 ;;;; -------------------------------------------------------------------------
5897 ;;;; Support to build (compile and load) Lisp files
5898
5899 (uiop/package:define-package :uiop/lisp-build
5900 (:nicknames :asdf/lisp-build)
5901 (:recycle :uiop/lisp-build :asdf/lisp-build :asdf)
5902 (:use :uiop/common-lisp :uiop/package :uiop/utility
5903 :uiop/os :uiop/pathname :uiop/filesystem :uiop/stream :uiop/image)
5904 (:export
5905 ;; Variables
5906 #:*compile-file-warnings-behaviour* #:*compile-file-failure-behaviour*
5907 #:*output-translation-function*
5908 #:*optimization-settings* #:*previous-optimization-settings*
5909 #:*base-build-directory*
5910 #:compile-condition #:compile-file-error #:compile-warned-error #:compile-failed-error
5911 #:compile-warned-warning #:compile-failed-warning
5912 #:check-lisp-compile-results #:check-lisp-compile-warnings
5913 #:*uninteresting-conditions* #:*usual-uninteresting-conditions*
5914 #:*uninteresting-compiler-conditions* #:*uninteresting-loader-conditions*
5915 ;; Types
5916 #+sbcl #:sb-grovel-unknown-constant-condition
5917 ;; Functions & Macros
5918 #:get-optimization-settings #:proclaim-optimization-settings #:with-optimization-settings
5919 #:call-with-muffled-compiler-conditions #:with-muffled-compiler-conditions
5920 #:call-with-muffled-loader-conditions #:with-muffled-loader-conditions
5921 #:reify-simple-sexp #:unreify-simple-sexp
5922 #:reify-deferred-warnings #:unreify-deferred-warnings
5923 #:reset-deferred-warnings #:save-deferred-warnings #:check-deferred-warnings
5924 #:with-saved-deferred-warnings #:warnings-file-p #:warnings-file-type #:*warnings-file-type*
5925 #:enable-deferred-warnings-check #:disable-deferred-warnings-check
5926 #:current-lisp-file-pathname #:load-pathname
5927 #:lispize-pathname #:compile-file-type #:call-around-hook
5928 #:compile-file* #:compile-file-pathname* #:*compile-check*
5929 #:load* #:load-from-string #:combine-fasls)
5930 (:intern #:defaults #:failure-p #:warnings-p #:s #:y #:body))
5931 (in-package :uiop/lisp-build)
5932
5933 (with-upgradability ()
5934 (defvar *compile-file-warnings-behaviour*
5935 (or #+clisp :ignore :warn)
5936 "How should ASDF react if it encounters a warning when compiling a file?
5937 Valid values are :error, :warn, and :ignore.")
5938
5939 (defvar *compile-file-failure-behaviour*
5940 (or #+(or mkcl sbcl) :error #+clisp :ignore :warn)
5941 "How should ASDF react if it encounters a failure (per the ANSI spec of COMPILE-FILE)
5942 when compiling a file, which includes any non-style-warning warning.
5943 Valid values are :error, :warn, and :ignore.
5944 Note that ASDF ALWAYS raises an error if it fails to create an output file when compiling.")
5945
5946 (defvar *base-build-directory* nil
5947 "When set to a non-null value, it should be an absolute directory pathname,
5948 which will serve as the *DEFAULT-PATHNAME-DEFAULTS* around a COMPILE-FILE,
5949 what more while the input-file is shortened if possible to ENOUGH-PATHNAME relative to it.
5950 This can help you produce more deterministic output for FASLs."))
5951
5952 ;;; Optimization settings
5953 (with-upgradability ()
5954 (defvar *optimization-settings* nil
5955 "Optimization settings to be used by PROCLAIM-OPTIMIZATION-SETTINGS")
5956 (defvar *previous-optimization-settings* nil
5957 "Optimization settings saved by PROCLAIM-OPTIMIZATION-SETTINGS")
5958 (defparameter +optimization-variables+
5959 ;; TODO: allegro genera corman mcl
5960 (or #+(or abcl xcl) '(system::*speed* system::*space* system::*safety* system::*debug*)
5961 #+clisp '() ;; system::*optimize* is a constant hash-table! (with non-constant contents)
5962 #+clozure '(ccl::*nx-speed* ccl::*nx-space* ccl::*nx-safety*
5963 ccl::*nx-debug* ccl::*nx-cspeed*)
5964 #+(or cmucl scl) '(c::*default-cookie*)
5965 #+(and ecl (not clasp)) (unless (use-ecl-byte-compiler-p) '(c::*speed* c::*space* c::*safety* c::*debug*))
5966 #+clasp '()
5967 #+gcl '(compiler::*speed* compiler::*space* compiler::*compiler-new-safety* compiler::*debug*)
5968 #+lispworks '(compiler::*optimization-level*)
5969 #+mkcl '(si::*speed* si::*space* si::*safety* si::*debug*)
5970 #+sbcl '(sb-c::*policy*)))
5971 (defun get-optimization-settings ()
5972 "Get current compiler optimization settings, ready to PROCLAIM again"
5973 #-(or abcl allegro clasp clisp clozure cmucl ecl lispworks mkcl sbcl scl xcl)
5974 (warn "~S does not support ~S. Please help me fix that."
5975 'get-optimization-settings (implementation-type))
5976 #+(or abcl allegro clasp clisp clozure cmucl ecl lispworks mkcl sbcl scl xcl)
5977 (let ((settings '(speed space safety debug compilation-speed #+(or cmucl scl) c::brevity)))
5978 #.`(loop #+(or allegro clozure)
5979 ,@'(:with info = #+allegro (sys:declaration-information 'optimize)
5980 #+clozure (ccl:declaration-information 'optimize nil))
5981 :for x :in settings
5982 ,@(or #+(or abcl clasp ecl gcl mkcl xcl) '(:for v :in +optimization-variables+))
5983 :for y = (or #+(or allegro clozure) (second (assoc x info)) ; normalize order
5984 #+clisp (gethash x system::*optimize* 1)
5985 #+(or abcl clasp ecl mkcl xcl) (symbol-value v)
5986 #+(or cmucl scl) (slot-value c::*default-cookie*
5987 (case x (compilation-speed 'c::cspeed)
5988 (otherwise x)))
5989 #+lispworks (slot-value compiler::*optimization-level* x)
5990 #+sbcl (sb-c::policy-quality sb-c::*policy* x))
5991 :when y :collect (list x y))))
5992 (defun proclaim-optimization-settings ()
5993 "Proclaim the optimization settings in *OPTIMIZATION-SETTINGS*"
5994 (proclaim `(optimize ,@*optimization-settings*))
5995 (let ((settings (get-optimization-settings)))
5996 (unless (equal *previous-optimization-settings* settings)
5997 (setf *previous-optimization-settings* settings))))
5998 (defmacro with-optimization-settings ((&optional (settings *optimization-settings*)) &body body)
5999 #+(or allegro clisp)
6000 (let ((previous-settings (gensym "PREVIOUS-SETTINGS")))
6001 `(let ((,previous-settings (get-optimization-settings)))
6002 ,@(when settings `((proclaim `(optimize ,@,settings))))
6003 (unwind-protect (progn ,@body)
6004 (proclaim `(optimize ,@,previous-settings)))))
6005 #-(or allegro clisp)
6006 `(let ,(loop :for v :in +optimization-variables+ :collect `(,v ,v))
6007 ,@(when settings `((proclaim `(optimize ,@,settings))))
6008 ,@body)))
6009
6010
6011 ;;; Condition control
6012 (with-upgradability ()
6013 #+sbcl
6014 (progn
6015 (defun sb-grovel-unknown-constant-condition-p (c)
6016 "Detect SB-GROVEL unknown-constant conditions on older versions of SBCL"
6017 (and (typep c 'sb-int:simple-style-warning)
6018 (string-enclosed-p
6019 "Couldn't grovel for "
6020 (simple-condition-format-control c)
6021 " (unknown to the C compiler).")))
6022 (deftype sb-grovel-unknown-constant-condition ()
6023 '(and style-warning (satisfies sb-grovel-unknown-constant-condition-p))))
6024
6025 (defvar *usual-uninteresting-conditions*
6026 (append
6027 ;;#+clozure '(ccl:compiler-warning)
6028 #+cmucl '("Deleting unreachable code.")
6029 #+lispworks '("~S being redefined in ~A (previously in ~A)."
6030 "~S defined more than once in ~A.") ;; lispworks gets confused by eval-when.
6031 #+sbcl
6032 '(sb-c::simple-compiler-note
6033 "&OPTIONAL and &KEY found in the same lambda list: ~S"
6034 #+sb-eval sb-kernel:lexical-environment-too-complex
6035 sb-kernel:undefined-alien-style-warning
6036 sb-grovel-unknown-constant-condition ; defined above.
6037 sb-ext:implicit-generic-function-warning ;; Controversial.
6038 sb-int:package-at-variance
6039 sb-kernel:uninteresting-redefinition
6040 ;; BEWARE: the below four are controversial to include here.
6041 sb-kernel:redefinition-with-defun
6042 sb-kernel:redefinition-with-defgeneric
6043 sb-kernel:redefinition-with-defmethod
6044 sb-kernel::redefinition-with-defmacro) ; not exported by old SBCLs
6045 '("No generic function ~S present when encountering macroexpansion of defmethod. Assuming it will be an instance of standard-generic-function.")) ;; from closer2mop
6046 "A suggested value to which to set or bind *uninteresting-conditions*.")
6047
6048 (defvar *uninteresting-conditions* '()
6049 "Conditions that may be skipped while compiling or loading Lisp code.")
6050 (defvar *uninteresting-compiler-conditions* '()
6051 "Additional conditions that may be skipped while compiling Lisp code.")
6052 (defvar *uninteresting-loader-conditions*
6053 (append
6054 '("Overwriting already existing readtable ~S." ;; from named-readtables
6055 #(#:finalizers-off-warning :asdf-finalizers)) ;; from asdf-finalizers
6056 #+clisp '(clos::simple-gf-replacing-method-warning))
6057 "Additional conditions that may be skipped while loading Lisp code."))
6058
6059 ;;;; ----- Filtering conditions while building -----
6060 (with-upgradability ()
6061 (defun call-with-muffled-compiler-conditions (thunk)
6062 "Call given THUNK in a context where uninteresting conditions and compiler conditions are muffled"
6063 (call-with-muffled-conditions
6064 thunk (append *uninteresting-conditions* *uninteresting-compiler-conditions*)))
6065 (defmacro with-muffled-compiler-conditions ((&optional) &body body)
6066 "Trivial syntax for CALL-WITH-MUFFLED-COMPILER-CONDITIONS"
6067 `(call-with-muffled-compiler-conditions #'(lambda () ,@body)))
6068 (defun call-with-muffled-loader-conditions (thunk)
6069 "Call given THUNK in a context where uninteresting conditions and loader conditions are muffled"
6070 (call-with-muffled-conditions
6071 thunk (append *uninteresting-conditions* *uninteresting-loader-conditions*)))
6072 (defmacro with-muffled-loader-conditions ((&optional) &body body)
6073 "Trivial syntax for CALL-WITH-MUFFLED-LOADER-CONDITIONS"
6074 `(call-with-muffled-loader-conditions #'(lambda () ,@body))))
6075
6076
6077 ;;;; Handle warnings and failures
6078 (with-upgradability ()
6079 (define-condition compile-condition (condition)
6080 ((context-format
6081 :initform nil :reader compile-condition-context-format :initarg :context-format)
6082 (context-arguments
6083 :initform nil :reader compile-condition-context-arguments :initarg :context-arguments)
6084 (description
6085 :initform nil :reader compile-condition-description :initarg :description))
6086 (:report (lambda (c s)
6087 (format s (compatfmt "~@<~A~@[ while ~?~]~@:>")
6088 (or (compile-condition-description c) (type-of c))
6089 (compile-condition-context-format c)
6090 (compile-condition-context-arguments c)))))
6091 (define-condition compile-file-error (compile-condition error) ())
6092 (define-condition compile-warned-warning (compile-condition warning) ())
6093 (define-condition compile-warned-error (compile-condition error) ())
6094 (define-condition compile-failed-warning (compile-condition warning) ())
6095 (define-condition compile-failed-error (compile-condition error) ())
6096
6097 (defun check-lisp-compile-warnings (warnings-p failure-p
6098 &optional context-format context-arguments)
6099 "Given the warnings or failures as resulted from COMPILE-FILE or checking deferred warnings,
6100 raise an error or warning as appropriate"
6101 (when failure-p
6102 (case *compile-file-failure-behaviour*
6103 (:warn (warn 'compile-failed-warning
6104 :description "Lisp compilation failed"
6105 :context-format context-format
6106 :context-arguments context-arguments))
6107 (:error (error 'compile-failed-error
6108 :description "Lisp compilation failed"
6109 :context-format context-format
6110 :context-arguments context-arguments))
6111 (:ignore nil)))
6112 (when warnings-p
6113 (case *compile-file-warnings-behaviour*
6114 (:warn (warn 'compile-warned-warning
6115 :description "Lisp compilation had style-warnings"
6116 :context-format context-format
6117 :context-arguments context-arguments))
6118 (:error (error 'compile-warned-error
6119 :description "Lisp compilation had style-warnings"
6120 :context-format context-format
6121 :context-arguments context-arguments))
6122 (:ignore nil))))
6123
6124 (defun check-lisp-compile-results (output warnings-p failure-p
6125 &optional context-format context-arguments)
6126 "Given the results of COMPILE-FILE, raise an error or warning as appropriate"
6127 (unless output
6128 (error 'compile-file-error :context-format context-format :context-arguments context-arguments))
6129 (check-lisp-compile-warnings warnings-p failure-p context-format context-arguments)))
6130
6131
6132 ;;;; Deferred-warnings treatment, originally implemented by Douglas Katzman.
6133 ;;;
6134 ;;; To support an implementation, three functions must be implemented:
6135 ;;; reify-deferred-warnings unreify-deferred-warnings reset-deferred-warnings
6136 ;;; See their respective docstrings.
6137 (with-upgradability ()
6138 (defun reify-simple-sexp (sexp)
6139 "Given a simple SEXP, return a representation of it as a portable SEXP.
6140 Simple means made of symbols, numbers, characters, simple-strings, pathnames, cons cells."
6141 (etypecase sexp
6142 (symbol (reify-symbol sexp))
6143 ((or number character simple-string pathname) sexp)
6144 (cons (cons (reify-simple-sexp (car sexp)) (reify-simple-sexp (cdr sexp))))
6145 (simple-vector (vector (mapcar 'reify-simple-sexp (coerce sexp 'list))))))
6146
6147 (defun unreify-simple-sexp (sexp)
6148 "Given the portable output of REIFY-SIMPLE-SEXP, return the simple SEXP it represents"
6149 (etypecase sexp
6150 ((or symbol number character simple-string pathname) sexp)
6151 (cons (cons (unreify-simple-sexp (car sexp)) (unreify-simple-sexp (cdr sexp))))
6152 ((simple-vector 2) (unreify-symbol sexp))
6153 ((simple-vector 1) (coerce (mapcar 'unreify-simple-sexp (aref sexp 0)) 'vector))))
6154
6155 #+clozure
6156 (progn
6157 (defun reify-source-note (source-note)
6158 (when source-note
6159 (with-accessors ((source ccl::source-note-source) (filename ccl:source-note-filename)
6160 (start-pos ccl:source-note-start-pos) (end-pos ccl:source-note-end-pos)) source-note
6161 (declare (ignorable source))
6162 (list :filename filename :start-pos start-pos :end-pos end-pos
6163 #|:source (reify-source-note source)|#))))
6164 (defun unreify-source-note (source-note)
6165 (when source-note
6166 (destructuring-bind (&key filename start-pos end-pos source) source-note
6167 (ccl::make-source-note :filename filename :start-pos start-pos :end-pos end-pos
6168 :source (unreify-source-note source)))))
6169 (defun unsymbolify-function-name (name)
6170 (if-let (setfed (gethash name ccl::%setf-function-name-inverses%))
6171 `(setf ,setfed)
6172 name))
6173 (defun symbolify-function-name (name)
6174 (if (and (consp name) (eq (first name) 'setf))
6175 (let ((setfed (second name)))
6176 (gethash setfed ccl::%setf-function-names%))
6177 name))
6178 (defun reify-function-name (function-name)
6179 (let ((name (or (first function-name) ;; defun: extract the name
6180 (let ((sec (second function-name)))
6181 (or (and (atom sec) sec) ; scoped method: drop scope
6182 (first sec)))))) ; method: keep gf name, drop method specializers
6183 (list name)))
6184 (defun unreify-function-name (function-name)
6185 function-name)
6186 (defun nullify-non-literals (sexp)
6187 (typecase sexp
6188 ((or number character simple-string symbol pathname) sexp)
6189 (cons (cons (nullify-non-literals (car sexp))
6190 (nullify-non-literals (cdr sexp))))
6191 (t nil)))
6192 (defun reify-deferred-warning (deferred-warning)
6193 (with-accessors ((warning-type ccl::compiler-warning-warning-type)
6194 (args ccl::compiler-warning-args)
6195 (source-note ccl:compiler-warning-source-note)
6196 (function-name ccl:compiler-warning-function-name)) deferred-warning
6197 (list :warning-type warning-type :function-name (reify-function-name function-name)
6198 :source-note (reify-source-note source-note)
6199 :args (destructuring-bind (fun &rest more)
6200 args
6201 (cons (unsymbolify-function-name fun)
6202 (nullify-non-literals more))))))
6203 (defun unreify-deferred-warning (reified-deferred-warning)
6204 (destructuring-bind (&key warning-type function-name source-note args)
6205 reified-deferred-warning
6206 (make-condition (or (cdr (ccl::assq warning-type ccl::*compiler-whining-conditions*))
6207 'ccl::compiler-warning)
6208 :function-name (unreify-function-name function-name)
6209 :source-note (unreify-source-note source-note)
6210 :warning-type warning-type
6211 :args (destructuring-bind (fun . more) args
6212 (cons (symbolify-function-name fun) more))))))
6213 #+(or cmucl scl)
6214 (defun reify-undefined-warning (warning)
6215 ;; Extracting undefined-warnings from the compilation-unit
6216 ;; To be passed through the above reify/unreify link, it must be a "simple-sexp"
6217 (list*
6218 (c::undefined-warning-kind warning)
6219 (c::undefined-warning-name warning)
6220 (c::undefined-warning-count warning)
6221 (mapcar
6222 #'(lambda (frob)
6223 ;; the lexenv slot can be ignored for reporting purposes
6224 `(:enclosing-source ,(c::compiler-error-context-enclosing-source frob)
6225 :source ,(c::compiler-error-context-source frob)
6226 :original-source ,(c::compiler-error-context-original-source frob)
6227 :context ,(c::compiler-error-context-context frob)
6228 :file-name ,(c::compiler-error-context-file-name frob) ; a pathname
6229 :file-position ,(c::compiler-error-context-file-position frob) ; an integer
6230 :original-source-path ,(c::compiler-error-context-original-source-path frob)))
6231 (c::undefined-warning-warnings warning))))
6232
6233 #+sbcl
6234 (defun reify-undefined-warning (warning)
6235 ;; Extracting undefined-warnings from the compilation-unit
6236 ;; To be passed through the above reify/unreify link, it must be a "simple-sexp"
6237 (list*
6238 (sb-c::undefined-warning-kind warning)
6239 (sb-c::undefined-warning-name warning)
6240 (sb-c::undefined-warning-count warning)
6241 (mapcar
6242 #'(lambda (frob)
6243 ;; the lexenv slot can be ignored for reporting purposes
6244 `(:enclosing-source ,(sb-c::compiler-error-context-enclosing-source frob)
6245 :source ,(sb-c::compiler-error-context-source frob)
6246 :original-source ,(sb-c::compiler-error-context-original-source frob)
6247 :context ,(sb-c::compiler-error-context-context frob)
6248 :file-name ,(sb-c::compiler-error-context-file-name frob) ; a pathname
6249 :file-position ,(sb-c::compiler-error-context-file-position frob) ; an integer
6250 :original-source-path ,(sb-c::compiler-error-context-original-source-path frob)))
6251 (sb-c::undefined-warning-warnings warning))))
6252
6253 (defun reify-deferred-warnings ()
6254 "return a portable S-expression, portably readable and writeable in any Common Lisp implementation
6255 using READ within a WITH-SAFE-IO-SYNTAX, that represents the warnings currently deferred by
6256 WITH-COMPILATION-UNIT. One of three functions required for deferred-warnings support in ASDF."
6257 #+allegro
6258 (list :functions-defined excl::.functions-defined.
6259 :functions-called excl::.functions-called.)
6260 #+clozure
6261 (mapcar 'reify-deferred-warning
6262 (if-let (dw ccl::*outstanding-deferred-warnings*)
6263 (let ((mdw (ccl::ensure-merged-deferred-warnings dw)))
6264 (ccl::deferred-warnings.warnings mdw))))
6265 #+(or cmucl scl)
6266 (when lisp::*in-compilation-unit*
6267 ;; Try to send nothing through the pipe if nothing needs to be accumulated
6268 `(,@(when c::*undefined-warnings*
6269 `((c::*undefined-warnings*
6270 ,@(mapcar #'reify-undefined-warning c::*undefined-warnings*))))
6271 ,@(loop :for what :in '(c::*compiler-error-count*
6272 c::*compiler-warning-count*
6273 c::*compiler-note-count*)
6274 :for value = (symbol-value what)
6275 :when (plusp value)
6276 :collect `(,what . ,value))))
6277 #+sbcl
6278 (when sb-c::*in-compilation-unit*
6279 ;; Try to send nothing through the pipe if nothing needs to be accumulated
6280 `(,@(when sb-c::*undefined-warnings*
6281 `((sb-c::*undefined-warnings*
6282 ,@(mapcar #'reify-undefined-warning sb-c::*undefined-warnings*))))
6283 ,@(loop :for what :in '(sb-c::*aborted-compilation-unit-count*
6284 sb-c::*compiler-error-count*
6285 sb-c::*compiler-warning-count*
6286 sb-c::*compiler-style-warning-count*
6287 sb-c::*compiler-note-count*)
6288 :for value = (symbol-value what)
6289 :when (plusp value)
6290 :collect `(,what . ,value)))))
6291
6292 (defun unreify-deferred-warnings (reified-deferred-warnings)
6293 "given a S-expression created by REIFY-DEFERRED-WARNINGS, reinstantiate the corresponding
6294 deferred warnings as to be handled at the end of the current WITH-COMPILATION-UNIT.
6295 Handle any warning that has been resolved already,
6296 such as an undefined function that has been defined since.
6297 One of three functions required for deferred-warnings support in ASDF."
6298 (declare (ignorable reified-deferred-warnings))
6299 #+allegro
6300 (destructuring-bind (&key functions-defined functions-called)
6301 reified-deferred-warnings
6302 (setf excl::.functions-defined.
6303 (append functions-defined excl::.functions-defined.)
6304 excl::.functions-called.
6305 (append functions-called excl::.functions-called.)))
6306 #+clozure
6307 (let ((dw (or ccl::*outstanding-deferred-warnings*
6308 (setf ccl::*outstanding-deferred-warnings* (ccl::%defer-warnings t)))))
6309 (appendf (ccl::deferred-warnings.warnings dw)
6310 (mapcar 'unreify-deferred-warning reified-deferred-warnings)))
6311 #+(or cmucl scl)
6312 (dolist (item reified-deferred-warnings)
6313 ;; Each item is (symbol . adjustment) where the adjustment depends on the symbol.
6314 ;; For *undefined-warnings*, the adjustment is a list of initargs.
6315 ;; For everything else, it's an integer.
6316 (destructuring-bind (symbol . adjustment) item
6317 (case symbol
6318 ((c::*undefined-warnings*)
6319 (setf c::*undefined-warnings*
6320 (nconc (mapcan
6321 #'(lambda (stuff)
6322 (destructuring-bind (kind name count . rest) stuff
6323 (unless (case kind (:function (fboundp name)))
6324 (list
6325 (c::make-undefined-warning
6326 :name name
6327 :kind kind
6328 :count count
6329 :warnings
6330 (mapcar #'(lambda (x)
6331 (apply #'c::make-compiler-error-context x))
6332 rest))))))
6333 adjustment)
6334 c::*undefined-warnings*)))
6335 (otherwise
6336 (set symbol (+ (symbol-value symbol) adjustment))))))
6337 #+sbcl
6338 (dolist (item reified-deferred-warnings)
6339 ;; Each item is (symbol . adjustment) where the adjustment depends on the symbol.
6340 ;; For *undefined-warnings*, the adjustment is a list of initargs.
6341 ;; For everything else, it's an integer.
6342 (destructuring-bind (symbol . adjustment) item
6343 (case symbol
6344 ((sb-c::*undefined-warnings*)
6345 (setf sb-c::*undefined-warnings*
6346 (nconc (mapcan
6347 #'(lambda (stuff)
6348 (destructuring-bind (kind name count . rest) stuff
6349 (unless (case kind (:function (fboundp name)))
6350 (list
6351 (sb-c::make-undefined-warning
6352 :name name
6353 :kind kind
6354 :count count
6355 :warnings
6356 (mapcar #'(lambda (x)
6357 (apply #'sb-c::make-compiler-error-context x))
6358 rest))))))
6359 adjustment)
6360 sb-c::*undefined-warnings*)))
6361 (otherwise
6362 (set symbol (+ (symbol-value symbol) adjustment)))))))
6363
6364 (defun reset-deferred-warnings ()
6365 "Reset the set of deferred warnings to be handled at the end of the current WITH-COMPILATION-UNIT.
6366 One of three functions required for deferred-warnings support in ASDF."
6367 #+allegro
6368 (setf excl::.functions-defined. nil
6369 excl::.functions-called. nil)
6370 #+clozure
6371 (if-let (dw ccl::*outstanding-deferred-warnings*)
6372 (let ((mdw (ccl::ensure-merged-deferred-warnings dw)))
6373 (setf (ccl::deferred-warnings.warnings mdw) nil)))
6374 #+(or cmucl scl)
6375 (when lisp::*in-compilation-unit*
6376 (setf c::*undefined-warnings* nil
6377 c::*compiler-error-count* 0
6378 c::*compiler-warning-count* 0
6379 c::*compiler-note-count* 0))
6380 #+sbcl
6381 (when sb-c::*in-compilation-unit*
6382 (setf sb-c::*undefined-warnings* nil
6383 sb-c::*aborted-compilation-unit-count* 0
6384 sb-c::*compiler-error-count* 0
6385 sb-c::*compiler-warning-count* 0
6386 sb-c::*compiler-style-warning-count* 0
6387 sb-c::*compiler-note-count* 0)))
6388
6389 (defun save-deferred-warnings (warnings-file)
6390 "Save forward reference conditions so they may be issued at a latter time,
6391 possibly in a different process."
6392 (with-open-file (s warnings-file :direction :output :if-exists :supersede
6393 :element-type *default-stream-element-type*
6394 :external-format *utf-8-external-format*)
6395 (with-safe-io-syntax ()
6396 (write (reify-deferred-warnings) :stream s :pretty t :readably t)
6397 (terpri s))))
6398
6399 (defun warnings-file-type (&optional implementation-type)
6400 "The pathname type for warnings files on given IMPLEMENTATION-TYPE,
6401 where NIL designates the current one"
6402 (case (or implementation-type *implementation-type*)
6403 ((:acl :allegro) "allegro-warnings")
6404 ;;((:clisp) "clisp-warnings")
6405 ((:cmu :cmucl) "cmucl-warnings")
6406 ((:sbcl) "sbcl-warnings")
6407 ((:clozure :ccl) "ccl-warnings")
6408 ((:scl) "scl-warnings")))
6409
6410 (defvar *warnings-file-type* nil
6411 "Pathname type for warnings files, or NIL if disabled")
6412
6413 (defun enable-deferred-warnings-check ()
6414 "Enable the saving of deferred warnings"
6415 (setf *warnings-file-type* (warnings-file-type)))
6416
6417 (defun disable-deferred-warnings-check ()
6418 "Disable the saving of deferred warnings"
6419 (setf *warnings-file-type* nil))
6420
6421 (defun warnings-file-p (file &optional implementation-type)
6422 "Is FILE a saved warnings file for the given IMPLEMENTATION-TYPE?
6423 If that given type is NIL, use the currently configured *WARNINGS-FILE-TYPE* instead."
6424 (if-let (type (if implementation-type
6425 (warnings-file-type implementation-type)
6426 *warnings-file-type*))
6427 (equal (pathname-type file) type)))
6428
6429 (defun check-deferred-warnings (files &optional context-format context-arguments)
6430 "Given a list of FILES containing deferred warnings saved by CALL-WITH-SAVED-DEFERRED-WARNINGS,
6431 re-intern and raise any warnings that are still meaningful."
6432 (let ((file-errors nil)
6433 (failure-p nil)
6434 (warnings-p nil))
6435 (handler-bind
6436 ((warning #'(lambda (c)
6437 (setf warnings-p t)
6438 (unless (typep c 'style-warning)
6439 (setf failure-p t)))))
6440 (with-compilation-unit (:override t)
6441 (reset-deferred-warnings)
6442 (dolist (file files)
6443 (unreify-deferred-warnings
6444 (handler-case (safe-read-file-form file)
6445 (error (c)
6446 ;;(delete-file-if-exists file) ;; deleting forces rebuild but prevents debugging
6447 (push c file-errors)
6448 nil))))))
6449 (dolist (error file-errors) (error error))
6450 (check-lisp-compile-warnings
6451 (or failure-p warnings-p) failure-p context-format context-arguments)))
6452
6453 #|
6454 Mini-guide to adding support for deferred warnings on an implementation.
6455
6456 First, look at what such a warning looks like:
6457
6458 (describe
6459 (handler-case
6460 (and (eval '(lambda () (some-undefined-function))) nil)
6461 (t (c) c)))
6462
6463 Then you can grep for the condition type in your compiler sources
6464 and see how to catch those that have been deferred,
6465 and/or read, clear and restore the deferred list.
6466
6467 Also look at
6468 (macroexpand-1 '(with-compilation-unit () foo))
6469 |#
6470
6471 (defun call-with-saved-deferred-warnings (thunk warnings-file &key source-namestring)
6472 "If WARNINGS-FILE is not nil, record the deferred-warnings around a call to THUNK
6473 and save those warnings to the given file for latter use,
6474 possibly in a different process. Otherwise just call THUNK."
6475 (declare (ignorable source-namestring))
6476 (if warnings-file
6477 (with-compilation-unit (:override t #+sbcl :source-namestring #+sbcl source-namestring)
6478 (unwind-protect
6479 (let (#+sbcl (sb-c::*undefined-warnings* nil))
6480 (multiple-value-prog1
6481 (funcall thunk)
6482 (save-deferred-warnings warnings-file)))
6483 (reset-deferred-warnings)))
6484 (funcall thunk)))
6485
6486 (defmacro with-saved-deferred-warnings ((warnings-file &key source-namestring) &body body)
6487 "Trivial syntax for CALL-WITH-SAVED-DEFERRED-WARNINGS"
6488 `(call-with-saved-deferred-warnings
6489 #'(lambda () ,@body) ,warnings-file :source-namestring ,source-namestring)))
6490
6491
6492 ;;; from ASDF
6493 (with-upgradability ()
6494 (defun current-lisp-file-pathname ()
6495 "Portably return the PATHNAME of the current Lisp source file being compiled or loaded"
6496 (or *compile-file-pathname* *load-pathname*))
6497
6498 (defun load-pathname ()
6499 "Portably return the LOAD-PATHNAME of the current source file or fasl"
6500 *load-pathname*) ;; magic no longer needed for GCL.
6501
6502 (defun lispize-pathname (input-file)
6503 "From a INPUT-FILE pathname, return a corresponding .lisp source pathname"
6504 (make-pathname :type "lisp" :defaults input-file))
6505
6506 (defun compile-file-type (&rest keys)
6507 "pathname TYPE for lisp FASt Loading files"
6508 (declare (ignorable keys))
6509 #-(or clasp ecl mkcl) (load-time-value (pathname-type (compile-file-pathname "foo.lisp")))
6510 #+(or clasp ecl mkcl) (pathname-type (apply 'compile-file-pathname "foo" keys)))
6511
6512 (defun call-around-hook (hook function)
6513 "Call a HOOK around the execution of FUNCTION"
6514 (call-function (or hook 'funcall) function))
6515
6516 (defun compile-file-pathname* (input-file &rest keys &key output-file &allow-other-keys)
6517 "Variant of COMPILE-FILE-PATHNAME that works well with COMPILE-FILE*"
6518 (let* ((keys
6519 (remove-plist-keys `(#+(or (and allegro (not (version>= 8 2)))) :external-format
6520 ,@(unless output-file '(:output-file))) keys)))
6521 (if (absolute-pathname-p output-file)
6522 ;; what cfp should be doing, w/ mp* instead of mp
6523 (let* ((type (pathname-type (apply 'compile-file-type keys)))
6524 (defaults (make-pathname
6525 :type type :defaults (merge-pathnames* input-file))))
6526 (merge-pathnames* output-file defaults))
6527 (funcall *output-translation-function*
6528 (apply 'compile-file-pathname input-file keys)))))
6529
6530 (defvar *compile-check* nil
6531 "A hook for user-defined compile-time invariants")
6532
6533 (defun* (compile-file*) (input-file &rest keys
6534 &key (compile-check *compile-check*) output-file warnings-file
6535 #+clisp lib-file #+(or clasp ecl mkcl) object-file #+sbcl emit-cfasl
6536 &allow-other-keys)
6537 "This function provides a portable wrapper around COMPILE-FILE.
6538 It ensures that the OUTPUT-FILE value is only returned and
6539 the file only actually created if the compilation was successful,
6540 even though your implementation may not do that. It also checks an optional
6541 user-provided consistency function COMPILE-CHECK to determine success;
6542 it will call this function if not NIL at the end of the compilation
6543 with the arguments sent to COMPILE-FILE*, except with :OUTPUT-FILE TMP-FILE
6544 where TMP-FILE is the name of a temporary output-file.
6545 It also checks two flags (with legacy british spelling from ASDF1),
6546 *COMPILE-FILE-FAILURE-BEHAVIOUR* and *COMPILE-FILE-WARNINGS-BEHAVIOUR*
6547 with appropriate implementation-dependent defaults,
6548 and if a failure (respectively warnings) are reported by COMPILE-FILE,
6549 it will consider that an error unless the respective behaviour flag
6550 is one of :SUCCESS :WARN :IGNORE.
6551 If WARNINGS-FILE is defined, deferred warnings are saved to that file.
6552 On ECL or MKCL, it creates both the linkable object and loadable fasl files.
6553 On implementations that erroneously do not recognize standard keyword arguments,
6554 it will filter them appropriately."
6555 #+(or clasp ecl)
6556 (when (and object-file (equal (compile-file-type) (pathname object-file)))
6557 (format t "Whoa, some funky ASDF upgrade switched ~S calling convention for ~S and ~S~%"
6558 'compile-file* output-file object-file)
6559 (rotatef output-file object-file))
6560 (let* ((keywords (remove-plist-keys
6561 `(:output-file :compile-check :warnings-file
6562 #+clisp :lib-file #+(or clasp ecl mkcl) :object-file) keys))
6563 (output-file
6564 (or output-file
6565 (apply 'compile-file-pathname* input-file :output-file output-file keywords)))
6566 (physical-output-file (physicalize-pathname output-file))
6567 #+(or clasp ecl)
6568 (object-file
6569 (unless (use-ecl-byte-compiler-p)
6570 (or object-file
6571 #+ecl (compile-file-pathname output-file :type :object)
6572 #+clasp (compile-file-pathname output-file :output-type :object))))
6573 #+mkcl
6574 (object-file
6575 (or object-file
6576 (compile-file-pathname output-file :fasl-p nil)))
6577 (tmp-file (tmpize-pathname physical-output-file))
6578 #+sbcl
6579 (cfasl-file (etypecase emit-cfasl
6580 (null nil)
6581 ((eql t) (make-pathname :type "cfasl" :defaults physical-output-file))
6582 (string (parse-namestring emit-cfasl))
6583 (pathname emit-cfasl)))
6584 #+sbcl
6585 (tmp-cfasl (when cfasl-file (make-pathname :type "cfasl" :defaults tmp-file)))
6586 #+clisp
6587 (tmp-lib (make-pathname :type "lib" :defaults tmp-file)))
6588 (multiple-value-bind (output-truename warnings-p failure-p)
6589 (with-enough-pathname (input-file :defaults *base-build-directory*)
6590 (with-saved-deferred-warnings (warnings-file :source-namestring (namestring input-file))
6591 (with-muffled-compiler-conditions ()
6592 (or #-(or clasp ecl mkcl)
6593 (apply 'compile-file input-file :output-file tmp-file
6594 #+sbcl (if emit-cfasl (list* :emit-cfasl tmp-cfasl keywords) keywords)
6595 #-sbcl keywords)
6596 #+ecl (apply 'compile-file input-file :output-file
6597 (if object-file
6598 (list* object-file :system-p t keywords)
6599 (list* tmp-file keywords)))
6600 #+clasp (apply 'compile-file input-file :output-file
6601 (if object-file
6602 (list* object-file :output-type :object #|:system-p t|# keywords)
6603 (list* tmp-file keywords)))
6604 #+mkcl (apply 'compile-file input-file
6605 :output-file object-file :fasl-p nil keywords)))))
6606 (cond
6607 ((and output-truename
6608 (flet ((check-flag (flag behaviour)
6609 (or (not flag) (member behaviour '(:success :warn :ignore)))))
6610 (and (check-flag failure-p *compile-file-failure-behaviour*)
6611 (check-flag warnings-p *compile-file-warnings-behaviour*)))
6612 (progn
6613 #+(or clasp ecl mkcl)
6614 (when (and #+(or clasp ecl) object-file)
6615 (setf output-truename
6616 (compiler::build-fasl tmp-file
6617 #+(or clasp ecl) :lisp-files #+mkcl :lisp-object-files (list object-file))))
6618 (or (not compile-check)
6619 (apply compile-check input-file
6620 :output-file output-truename
6621 keywords))))
6622 (delete-file-if-exists physical-output-file)
6623 (when output-truename
6624 #+clasp (when output-truename (rename-file-overwriting-target tmp-file output-truename))
6625 ;; see CLISP bug 677
6626 #+clisp
6627 (progn
6628 (setf tmp-lib (make-pathname :type "lib" :defaults output-truename))
6629 (unless lib-file (setf lib-file (make-pathname :type "lib" :defaults physical-output-file)))
6630 (rename-file-overwriting-target tmp-lib lib-file))
6631 #+sbcl (when cfasl-file (rename-file-overwriting-target tmp-cfasl cfasl-file))
6632 (rename-file-overwriting-target output-truename physical-output-file)
6633 (setf output-truename (truename physical-output-file)))
6634 #+clasp (delete-file-if-exists tmp-file)
6635 #+clisp (progn (delete-file-if-exists tmp-file) ;; this one works around clisp BUG 677
6636 (delete-file-if-exists tmp-lib))) ;; this one is "normal" defensive cleanup
6637 (t ;; error or failed check
6638 (delete-file-if-exists output-truename)
6639 #+clisp (delete-file-if-exists tmp-lib)
6640 #+sbcl (delete-file-if-exists tmp-cfasl)
6641 (setf output-truename nil)))
6642 (values output-truename warnings-p failure-p))))
6643
6644 (defun load* (x &rest keys &key &allow-other-keys)
6645 "Portable wrapper around LOAD that properly handles loading from a stream."
6646 (with-muffled-loader-conditions ()
6647 (etypecase x
6648 ((or pathname string #-(or allegro clozure genera) stream #+clozure file-stream)
6649 (apply 'load x keys))
6650 ;; Genera can't load from a string-input-stream
6651 ;; ClozureCL 1.6 can only load from file input stream
6652 ;; Allegro 5, I don't remember but it must have been broken when I tested.
6653 #+(or allegro clozure genera)
6654 (stream ;; make do this way
6655 (let ((*package* *package*)
6656 (*readtable* *readtable*)
6657 (*load-pathname* nil)
6658 (*load-truename* nil))
6659 (eval-input x))))))
6660
6661 (defun load-from-string (string)
6662 "Portably read and evaluate forms from a STRING."
6663 (with-input-from-string (s string) (load* s))))
6664
6665 ;;; Links FASLs together
6666 (with-upgradability ()
6667 (defun combine-fasls (inputs output)
6668 "Combine a list of FASLs INPUTS into a single FASL OUTPUT"
6669 #-(or abcl allegro clisp clozure cmucl lispworks sbcl scl xcl)
6670 (error "~A does not support ~S~%inputs ~S~%output ~S"
6671 (implementation-type) 'combine-fasls inputs output)
6672 #+abcl (funcall 'sys::concatenate-fasls inputs output) ; requires ABCL 1.2.0
6673 #+(or allegro clisp cmucl sbcl scl xcl) (concatenate-files inputs output)
6674 #+clozure (ccl:fasl-concatenate output inputs :if-exists :supersede)
6675 #+lispworks
6676 (let (fasls)
6677 (unwind-protect
6678 (progn
6679 (loop :for i :in inputs
6680 :for n :from 1
6681 :for f = (add-pathname-suffix
6682 output (format nil "-FASL~D" n))
6683 :do (copy-file i f)
6684 (push f fasls))
6685 (ignore-errors (lispworks:delete-system :fasls-to-concatenate))
6686 (eval `(scm:defsystem :fasls-to-concatenate
6687 (:default-pathname ,(pathname-directory-pathname output))
6688 :members
6689 ,(loop :for f :in (reverse fasls)
6690 :collect `(,(namestring f) :load-only t))))
6691 (scm:concatenate-system output :fasls-to-concatenate :force t))
6692 (loop :for f :in fasls :do (ignore-errors (delete-file f)))
6693 (ignore-errors (lispworks:delete-system :fasls-to-concatenate))))))
6694 ;;;; ---------------------------------------------------------------------------
6695 ;;;; Generic support for configuration files
6696
6697 (uiop/package:define-package :uiop/configuration
6698 (:nicknames :asdf/configuration)
6699 (:recycle :uiop/configuration :asdf/configuration :asdf)
6700 (:use :uiop/common-lisp :uiop/utility
6701 :uiop/os :uiop/pathname :uiop/filesystem :uiop/stream :uiop/image :uiop/lisp-build)
6702 (:export
6703 #:user-configuration-directories #:system-configuration-directories ;; implemented in backward-driver
6704 #:in-first-directory #:in-user-configuration-directory #:in-system-configuration-directory ;; idem
6705 #:get-folder-path
6706 #:xdg-data-home #:xdg-config-home #:xdg-data-dirs #:xdg-config-dirs
6707 #:xdg-cache-home #:xdg-runtime-dir #:system-config-pathnames
6708 #:filter-pathname-set #:xdg-data-pathnames #:xdg-config-pathnames
6709 #:find-preferred-file #:xdg-data-pathname #:xdg-config-pathname
6710 #:validate-configuration-form #:validate-configuration-file #:validate-configuration-directory
6711 #:configuration-inheritance-directive-p
6712 #:report-invalid-form #:invalid-configuration #:*ignored-configuration-form* #:*user-cache*
6713 #:*clear-configuration-hook* #:clear-configuration #:register-clear-configuration-hook
6714 #:resolve-location #:location-designator-p #:location-function-p #:*here-directory*
6715 #:resolve-relative-location #:resolve-absolute-location #:upgrade-configuration))
6716 (in-package :uiop/configuration)
6717
6718 (with-upgradability ()
6719 (define-condition invalid-configuration ()
6720 ((form :reader condition-form :initarg :form)
6721 (location :reader condition-location :initarg :location)
6722 (format :reader condition-format :initarg :format)
6723 (arguments :reader condition-arguments :initarg :arguments :initform nil))
6724 (:report (lambda (c s)
6725 (format s (compatfmt "~@<~? (will be skipped)~@:>")
6726 (condition-format c)
6727 (list* (condition-form c) (condition-location c)
6728 (condition-arguments c))))))
6729
6730 (defun configuration-inheritance-directive-p (x)
6731 "Is X a configuration inheritance directive?"
6732 (let ((kw '(:inherit-configuration :ignore-inherited-configuration)))
6733 (or (member x kw)
6734 (and (length=n-p x 1) (member (car x) kw)))))
6735
6736 (defun report-invalid-form (reporter &rest args)
6737 "Report an invalid form according to REPORTER and various ARGS"
6738 (etypecase reporter
6739 (null
6740 (apply 'error 'invalid-configuration args))
6741 (function
6742 (apply reporter args))
6743 ((or symbol string)
6744 (apply 'error reporter args))
6745 (cons
6746 (apply 'apply (append reporter args)))))
6747
6748 (defvar *ignored-configuration-form* nil
6749 "Have configuration forms been ignored while parsing the configuration?")
6750
6751 (defun validate-configuration-form (form tag directive-validator
6752 &key location invalid-form-reporter)
6753 "Validate a configuration FORM. By default it will raise an error if the
6754 FORM is not valid. Otherwise it will return the validated form.
6755 Arguments control the behavior:
6756 The configuration FORM should be of the form (TAG . <rest>)
6757 Each element of <rest> will be checked by first seeing if it's a configuration inheritance
6758 directive (see CONFIGURATION-INHERITANCE-DIRECTIVE-P) then invoking DIRECTIVE-VALIDATOR
6759 on it.
6760 In the event of an invalid form, INVALID-FORM-REPORTER will be used to control
6761 reporting (see REPORT-INVALID-FORM) with LOCATION providing information about where
6762 the configuration form appeared."
6763 (unless (and (consp form) (eq (car form) tag))
6764 (setf *ignored-configuration-form* t)
6765 (report-invalid-form invalid-form-reporter :form form :location location)
6766 (return-from validate-configuration-form nil))
6767 (loop :with inherit = 0 :with ignore-invalid-p = nil :with x = (list tag)
6768 :for directive :in (cdr form)
6769 :when (cond
6770 ((configuration-inheritance-directive-p directive)
6771 (incf inherit) t)
6772 ((eq directive :ignore-invalid-entries)
6773 (setf ignore-invalid-p t) t)
6774 ((funcall directive-validator directive)
6775 t)
6776 (ignore-invalid-p
6777 nil)
6778 (t
6779 (setf *ignored-configuration-form* t)
6780 (report-invalid-form invalid-form-reporter :form directive :location location)
6781 nil))
6782 :do (push directive x)
6783 :finally
6784 (unless (= inherit 1)
6785 (report-invalid-form invalid-form-reporter
6786 :form form :location location
6787 ;; we throw away the form and location arguments, hence the ~2*
6788 ;; this is necessary because of the report in INVALID-CONFIGURATION
6789 :format (compatfmt "~@<Invalid source registry ~S~@[ in ~S~]. ~
6790 One and only one of ~S or ~S is required.~@:>")
6791 :arguments '(:inherit-configuration :ignore-inherited-configuration)))
6792 (return (nreverse x))))
6793
6794 (defun validate-configuration-file (file validator &key description)
6795 "Validate a configuration FILE. The configuration file should have only one s-expression
6796 in it, which will be checked with the VALIDATOR FORM. DESCRIPTION argument used for error
6797 reporting."
6798 (let ((forms (read-file-forms file)))
6799 (unless (length=n-p forms 1)
6800 (error (compatfmt "~@<One and only one form allowed for ~A. Got: ~3i~_~S~@:>~%")
6801 description forms))
6802 (funcall validator (car forms) :location file)))
6803
6804 (defun validate-configuration-directory (directory tag validator &key invalid-form-reporter)
6805 "Map the VALIDATOR across the .conf files in DIRECTORY, the TAG will
6806 be applied to the results to yield a configuration form. Current
6807 values of TAG include :source-registry and :output-translations."
6808 (let ((files (sort (ignore-errors ;; SORT w/o COPY-LIST is OK: DIRECTORY returns a fresh list
6809 (remove-if
6810 'hidden-pathname-p
6811 (directory* (make-pathname :name *wild* :type "conf" :defaults directory))))
6812 #'string< :key #'namestring)))
6813 `(,tag
6814 ,@(loop :for file :in files :append
6815 (loop :with ignore-invalid-p = nil
6816 :for form :in (read-file-forms file)
6817 :when (eq form :ignore-invalid-entries)
6818 :do (setf ignore-invalid-p t)
6819 :else
6820 :when (funcall validator form)
6821 :collect form
6822 :else
6823 :when ignore-invalid-p
6824 :do (setf *ignored-configuration-form* t)
6825 :else
6826 :do (report-invalid-form invalid-form-reporter :form form :location file)))
6827 :inherit-configuration)))
6828
6829 (defun resolve-relative-location (x &key ensure-directory wilden)
6830 "Given a designator X for an relative location, resolve it to a pathname."
6831 (ensure-pathname
6832 (etypecase x
6833 (null nil)
6834 (pathname x)
6835 (string (parse-unix-namestring
6836 x :ensure-directory ensure-directory))
6837 (cons
6838 (if (null (cdr x))
6839 (resolve-relative-location
6840 (car x) :ensure-directory ensure-directory :wilden wilden)
6841 (let* ((car (resolve-relative-location
6842 (car x) :ensure-directory t :wilden nil)))
6843 (merge-pathnames*
6844 (resolve-relative-location
6845 (cdr x) :ensure-directory ensure-directory :wilden wilden)
6846 car))))
6847 ((eql :*/) *wild-directory*)
6848 ((eql :**/) *wild-inferiors*)
6849 ((eql :*.*.*) *wild-file*)
6850 ((eql :implementation)
6851 (parse-unix-namestring
6852 (implementation-identifier) :ensure-directory t))
6853 ((eql :implementation-type)
6854 (parse-unix-namestring
6855 (string-downcase (implementation-type)) :ensure-directory t))
6856 ((eql :hostname)
6857 (parse-unix-namestring (hostname) :ensure-directory t)))
6858 :wilden (and wilden (not (pathnamep x)) (not (member x '(:*/ :**/ :*.*.*))))
6859 :want-relative t))
6860
6861 (defvar *here-directory* nil
6862 "This special variable is bound to the currect directory during calls to
6863 PROCESS-SOURCE-REGISTRY in order that we be able to interpret the :here
6864 directive.")
6865
6866 (defvar *user-cache* nil
6867 "A specification as per RESOLVE-LOCATION of where the user keeps his FASL cache")
6868
6869 (defun resolve-absolute-location (x &key ensure-directory wilden)
6870 "Given a designator X for an absolute location, resolve it to a pathname"
6871 (ensure-pathname
6872 (etypecase x
6873 (null nil)
6874 (pathname x)
6875 (string
6876 (let ((p #-mcl (parse-namestring x)
6877 #+mcl (probe-posix x)))
6878 #+mcl (unless p (error "POSIX pathname ~S does not exist" x))
6879 (if ensure-directory (ensure-directory-pathname p) p)))
6880 (cons
6881 (return-from resolve-absolute-location
6882 (if (null (cdr x))
6883 (resolve-absolute-location
6884 (car x) :ensure-directory ensure-directory :wilden wilden)
6885 (merge-pathnames*
6886 (resolve-relative-location
6887 (cdr x) :ensure-directory ensure-directory :wilden wilden)
6888 (resolve-absolute-location
6889 (car x) :ensure-directory t :wilden nil)))))
6890 ((eql :root)
6891 ;; special magic! we return a relative pathname,
6892 ;; but what it means to the output-translations is
6893 ;; "relative to the root of the source pathname's host and device".
6894 (return-from resolve-absolute-location
6895 (let ((p (make-pathname :directory '(:relative))))
6896 (if wilden (wilden p) p))))
6897 ((eql :home) (user-homedir-pathname))
6898 ((eql :here) (resolve-absolute-location
6899 (or *here-directory* (pathname-directory-pathname (load-pathname)))
6900 :ensure-directory t :wilden nil))
6901 ((eql :user-cache) (resolve-absolute-location
6902 *user-cache* :ensure-directory t :wilden nil)))
6903 :wilden (and wilden (not (pathnamep x)))
6904 :resolve-symlinks *resolve-symlinks*
6905 :want-absolute t))
6906
6907 ;; Try to override declaration in previous versions of ASDF.
6908 (declaim (ftype (function (t &key (:directory boolean) (:wilden boolean)
6909 (:ensure-directory boolean)) t) resolve-location))
6910
6911 (defun* (resolve-location) (x &key ensure-directory wilden directory)
6912 "Resolve location designator X into a PATHNAME"
6913 ;; :directory backward compatibility, until 2014-01-16: accept directory as well as ensure-directory
6914 (loop* :with dirp = (or directory ensure-directory)
6915 :with (first . rest) = (if (atom x) (list x) x)
6916 :with path = (or (resolve-absolute-location
6917 first :ensure-directory (and (or dirp rest) t)
6918 :wilden (and wilden (null rest)))
6919 (return nil))
6920 :for (element . morep) :on rest
6921 :for dir = (and (or morep dirp) t)
6922 :for wild = (and wilden (not morep))
6923 :for sub = (merge-pathnames*
6924 (resolve-relative-location
6925 element :ensure-directory dir :wilden wild)
6926 path)
6927 :do (setf path (if (absolute-pathname-p sub) (resolve-symlinks* sub) sub))
6928 :finally (return path)))
6929
6930 (defun location-designator-p (x)
6931 "Is X a designator for a location?"
6932 ;; NIL means "skip this entry", or as an output translation, same as translation input.
6933 ;; T means "any input" for a translation, or as output, same as translation input.
6934 (flet ((absolute-component-p (c)
6935 (typep c '(or string pathname
6936 (member :root :home :here :user-cache))))
6937 (relative-component-p (c)
6938 (typep c '(or string pathname
6939 (member :*/ :**/ :*.*.* :implementation :implementation-type)))))
6940 (or (typep x 'boolean)
6941 (absolute-component-p x)
6942 (and (consp x) (absolute-component-p (first x)) (every #'relative-component-p (rest x))))))
6943
6944 (defun location-function-p (x)
6945 "Is X the specification of a location function?"
6946 ;; Location functions are allowed in output translations, and notably used by ABCL for JAR file support.
6947 (and (length=n-p x 2) (eq (car x) :function)))
6948
6949 (defvar *clear-configuration-hook* '())
6950
6951 (defun register-clear-configuration-hook (hook-function &optional call-now-p)
6952 "Register a function to be called when clearing configuration"
6953 (register-hook-function '*clear-configuration-hook* hook-function call-now-p))
6954
6955 (defun clear-configuration ()
6956 "Call the functions in *CLEAR-CONFIGURATION-HOOK*"
6957 (call-functions *clear-configuration-hook*))
6958
6959 (register-image-dump-hook 'clear-configuration)
6960
6961 (defun upgrade-configuration ()
6962 "If a previous version of ASDF failed to read some configuration, try again now."
6963 (when *ignored-configuration-form*
6964 (clear-configuration)
6965 (setf *ignored-configuration-form* nil)))
6966
6967
6968 (defun get-folder-path (folder)
6969 "Semi-portable implementation of a subset of LispWorks' sys:get-folder-path,
6970 this function tries to locate the Windows FOLDER for one of
6971 :LOCAL-APPDATA, :APPDATA or :COMMON-APPDATA.
6972 Returns NIL when the folder is not defined (e.g., not on Windows)."
6973 (or #+(and lispworks mswindows) (sys:get-folder-path folder)
6974 ;; read-windows-registry HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders\AppData
6975 (ecase folder
6976 (:local-appdata (or (getenv-absolute-directory "LOCALAPPDATA")
6977 (subpathname* (get-folder-path :appdata) "Local")))
6978 (:appdata (getenv-absolute-directory "APPDATA"))
6979 (:common-appdata (or (getenv-absolute-directory "ALLUSERSAPPDATA")
6980 (subpathname* (getenv-absolute-directory "ALLUSERSPROFILE") "Application Data/"))))))
6981
6982
6983 ;; Support for the XDG Base Directory Specification
6984 (defun xdg-data-home (&rest more)
6985 "Returns an absolute pathname for the directory containing user-specific data files.
6986 MORE may contain specifications for a subpath relative to this directory: a
6987 subpathname specification and keyword arguments as per RESOLVE-LOCATION \(see
6988 also \"Configuration DSL\"\) in the ASDF manual."
6989 (resolve-absolute-location
6990 `(,(or (getenv-absolute-directory "XDG_DATA_HOME")
6991 (os-cond
6992 ((os-windows-p) (get-folder-path :local-appdata))
6993 (t (subpathname (user-homedir-pathname) ".local/share/"))))
6994 ,more)))
6995
6996 (defun xdg-config-home (&rest more)
6997 "Returns a pathname for the directory containing user-specific configuration files.
6998 MORE may contain specifications for a subpath relative to this directory: a
6999 subpathname specification and keyword arguments as per RESOLVE-LOCATION \(see
7000 also \"Configuration DSL\"\) in the ASDF manual."
7001 (resolve-absolute-location
7002 `(,(or (getenv-absolute-directory "XDG_CONFIG_HOME")
7003 (os-cond
7004 ((os-windows-p) (xdg-data-home "config/"))
7005 (t (subpathname (user-homedir-pathname) ".config/"))))
7006 ,more)))
7007
7008 (defun xdg-data-dirs (&rest more)
7009 "The preference-ordered set of additional paths to search for data files.
7010 Returns a list of absolute directory pathnames.
7011 MORE may contain specifications for a subpath relative to these directories: a
7012 subpathname specification and keyword arguments as per RESOLVE-LOCATION \(see
7013 also \"Configuration DSL\"\) in the ASDF manual."
7014 (mapcar #'(lambda (d) (resolve-location `(,d ,more)))
7015 (or (getenv-absolute-directories "XDG_DATA_DIRS")
7016 (os-cond
7017 ((os-windows-p) (mapcar 'get-folder-path '(:appdata :common-appdata)))
7018 (t (mapcar 'parse-unix-namestring '("/usr/local/share/" "/usr/share/")))))))
7019
7020 (defun xdg-config-dirs (&rest more)
7021 "The preference-ordered set of additional base paths to search for configuration files.
7022 Returns a list of absolute directory pathnames.
7023 MORE may contain specifications for a subpath relative to these directories:
7024 subpathname specification and keyword arguments as per RESOLVE-LOCATION \(see
7025 also \"Configuration DSL\"\) in the ASDF manual."
7026 (mapcar #'(lambda (d) (resolve-location `(,d ,more)))
7027 (or (getenv-absolute-directories "XDG_CONFIG_DIRS")
7028 (os-cond
7029 ((os-windows-p) (xdg-data-dirs "config/"))
7030 (t (mapcar 'parse-unix-namestring '("/etc/xdg/")))))))
7031
7032 (defun xdg-cache-home (&rest more)
7033 "The base directory relative to which user specific non-essential data files should be stored.
7034 Returns an absolute directory pathname.
7035 MORE may contain specifications for a subpath relative to this directory: a
7036 subpathname specification and keyword arguments as per RESOLVE-LOCATION \(see
7037 also \"Configuration DSL\"\) in the ASDF manual."
7038 (resolve-absolute-location
7039 `(,(or (getenv-absolute-directory "XDG_CACHE_HOME")
7040 (os-cond
7041 ((os-windows-p) (xdg-data-home "cache/"))
7042 (t (subpathname* (user-homedir-pathname) ".cache/"))))
7043 ,more)))
7044
7045 (defun xdg-runtime-dir (&rest more)
7046 "Pathname for user-specific non-essential runtime files and other file objects,
7047 such as sockets, named pipes, etc.
7048 Returns an absolute directory pathname.
7049 MORE may contain specifications for a subpath relative to this directory: a
7050 subpathname specification and keyword arguments as per RESOLVE-LOCATION \(see
7051 also \"Configuration DSL\"\) in the ASDF manual."
7052 ;; The XDG spec says that if not provided by the login system, the application should
7053 ;; issue a warning and provide a replacement. UIOP is not equipped to do that and returns NIL.
7054 (resolve-absolute-location `(,(getenv-absolute-directory "XDG_RUNTIME_DIR") ,more)))
7055
7056 ;;; NOTE: modified the docstring because "system user configuration
7057 ;;; directories" seems self-contradictory. I'm not sure my wording is right.
7058 (defun system-config-pathnames (&rest more)
7059 "Return a list of directories where are stored the system's default user configuration information.
7060 MORE may contain specifications for a subpath relative to these directories: a
7061 subpathname specification and keyword arguments as per RESOLVE-LOCATION \(see
7062 also \"Configuration DSL\"\) in the ASDF manual."
7063 (declare (ignorable more))
7064 (os-cond
7065 ((os-unix-p) (list (resolve-absolute-location `(,(parse-unix-namestring "/etc/") ,more))))))
7066
7067 (defun filter-pathname-set (dirs)
7068 "Parse strings as unix namestrings and remove duplicates and non absolute-pathnames in a list."
7069 (remove-duplicates (remove-if-not #'absolute-pathname-p dirs) :from-end t :test 'equal))
7070
7071 (defun xdg-data-pathnames (&rest more)
7072 "Return a list of absolute pathnames for application data directories. With APP,
7073 returns directory for data for that application, without APP, returns the set of directories
7074 for storing all application configurations.
7075 MORE may contain specifications for a subpath relative to these directories: a
7076 subpathname specification and keyword arguments as per RESOLVE-LOCATION \(see
7077 also \"Configuration DSL\"\) in the ASDF manual."
7078 (filter-pathname-set
7079 `(,(xdg-data-home more)
7080 ,@(xdg-data-dirs more))))
7081
7082 (defun xdg-config-pathnames (&rest more)
7083 "Return a list of pathnames for application configuration.
7084 MORE may contain specifications for a subpath relative to these directories: a
7085 subpathname specification and keyword arguments as per RESOLVE-LOCATION \(see
7086 also \"Configuration DSL\"\) in the ASDF manual."
7087 (filter-pathname-set
7088 `(,(xdg-config-home more)
7089 ,@(xdg-config-dirs more))))
7090
7091 (defun find-preferred-file (files &key (direction :input))
7092 "Find first file in the list of FILES that exists (for direction :input or :probe)
7093 or just the first one (for direction :output or :io).
7094 Note that when we say \"file\" here, the files in question may be directories."
7095 (find-if (ecase direction ((:probe :input) 'probe-file*) ((:output :io) 'identity)) files))
7096
7097 (defun xdg-data-pathname (&optional more (direction :input))
7098 (find-preferred-file (xdg-data-pathnames more) :direction direction))
7099
7100 (defun xdg-config-pathname (&optional more (direction :input))
7101 (find-preferred-file (xdg-config-pathnames more) :direction direction))
7102
7103 (defun compute-user-cache ()
7104 "Compute (and return) the location of the default user-cache for translate-output
7105 objects. Side-effects for cached file location computation."
7106 (setf *user-cache* (xdg-cache-home "common-lisp" :implementation)))
7107 (register-image-restore-hook 'compute-user-cache))
7108 ;;;; -------------------------------------------------------------------------
7109 ;;; Hacks for backward-compatibility of the driver
7110
7111 (uiop/package:define-package :uiop/backward-driver
7112 (:nicknames :asdf/backward-driver)
7113 (:recycle :uiop/backward-driver :asdf/backward-driver :asdf)
7114 (:use :uiop/common-lisp :uiop/package :uiop/utility
7115 :uiop/pathname :uiop/stream :uiop/os :uiop/image
7116 :uiop/run-program :uiop/lisp-build :uiop/configuration)
7117 (:export
7118 #:coerce-pathname
7119 #:user-configuration-directories #:system-configuration-directories
7120 #:in-first-directory #:in-user-configuration-directory #:in-system-configuration-directory
7121 ))
7122 (in-package :uiop/backward-driver)
7123
7124 ;;;; Backward compatibility with various pathname functions.
7125
7126 (with-upgradability ()
7127 (defun coerce-pathname (name &key type defaults)
7128 ;; For backward-compatibility only, for people using internals
7129 ;; Reported users in quicklisp 2015-11: hu.dwim.asdf (removed in next release)
7130 ;; Will be removed after 2015-12.
7131 ;;(warn "Please don't use ASDF::COERCE-PATHNAME. Use ASDF/PATHNAME:PARSE-UNIX-NAMESTRING.")
7132 (parse-unix-namestring name :type type :defaults defaults))
7133
7134 ;; Backward compatibility for ASDF 2.27 to 3.1.4
7135 (defun user-configuration-directories ()
7136 "Return the current user's list of user configuration directories
7137 for configuring common-lisp.
7138 DEPRECATED. Use uiop:xdg-config-pathnames instead."
7139 (xdg-config-pathnames "common-lisp"))
7140 (defun system-configuration-directories ()
7141 "Return the list of system configuration directories for common-lisp.
7142 DEPRECATED. Use uiop:config-system-pathnames instead."
7143 (system-config-pathnames "common-lisp"))
7144 (defun in-first-directory (dirs x &key (direction :input))
7145 "Finds the first appropriate file named X in the list of DIRS for I/O
7146 in DIRECTION \(which may be :INPUT, :OUTPUT, :IO, or :PROBE).
7147 If direction is :INPUT or :PROBE, will return the first extant file named
7148 X in one of the DIRS.
7149 If direction is :OUTPUT or :IO, will simply return the file named X in the
7150 first element of DIRS that exists. DEPRECATED."
7151 (find-preferred-file
7152 (mapcar #'(lambda (dir) (subpathname (ensure-directory-pathname dir) x)) dirs)
7153 :direction direction))
7154 (defun in-user-configuration-directory (x &key (direction :input))
7155 "Return the file named X in the user configuration directory for common-lisp.
7156 DEPRECATED."
7157 (xdg-config-pathname `("common-lisp" ,x) direction))
7158 (defun in-system-configuration-directory (x &key (direction :input))
7159 "Return the pathname for the file named X under the system configuration directory
7160 for common-lisp. DEPRECATED."
7161 (find-preferred-file (system-config-pathnames "common-lisp" x) :direction direction)))
7162 ;;;; ---------------------------------------------------------------------------
7163 ;;;; Re-export all the functionality in UIOP
7164
7165 (uiop/package:define-package :uiop/driver
7166 (:nicknames :uiop :asdf/driver :asdf-driver :asdf-utils)
7167 (:use :uiop/common-lisp)
7168 ;; NB: not reexporting uiop/common-lisp
7169 ;; which include all of CL with compatibility modifications on select platforms,
7170 ;; that could cause potential conflicts for packages that would :use (cl uiop)
7171 ;; or :use (closer-common-lisp uiop), etc.
7172 (:use-reexport
7173 :uiop/package :uiop/utility
7174 :uiop/os :uiop/pathname :uiop/stream :uiop/filesystem :uiop/image
7175 :uiop/run-program :uiop/lisp-build
7176 :uiop/configuration :uiop/backward-driver))
7177
7178 ;; Provide both lowercase and uppercase, to satisfy more people.
7179 (provide "uiop") (provide "UIOP")
7180 ;;;; -------------------------------------------------------------------------
7181 ;;;; Handle upgrade as forward- and backward-compatibly as possible
7182 ;; See https://bugs.launchpad.net/asdf/+bug/485687
7183
7184 (uiop/package:define-package :asdf/upgrade
7185 (:recycle :asdf/upgrade :asdf)
7186 (:use :uiop/common-lisp :uiop)
7187 (:export
7188 #:asdf-version #:*previous-asdf-versions* #:*asdf-version*
7189 #:asdf-message #:*verbose-out*
7190 #:upgrading-p #:when-upgrading #:upgrade-asdf #:defparameter*
7191 #:*post-upgrade-cleanup-hook* #:*post-upgrade-restart-hook* #:cleanup-upgraded-asdf
7192 ;; There will be no symbol left behind!
7193 #:intern*)
7194 (:import-from :uiop/package #:intern* #:find-symbol*))
7195 (in-package :asdf/upgrade)
7196
7197 ;;; Special magic to detect if this is an upgrade
7198
7199 (with-upgradability ()
7200 (defun asdf-version ()
7201 "Exported interface to the version of ASDF currently installed. A string.
7202 You can compare this string with e.g.: (ASDF:VERSION-SATISFIES (ASDF:ASDF-VERSION) \"3.4.5.67\")."
7203 (when (find-package :asdf)
7204 (or (symbol-value (find-symbol (string :*asdf-version*) :asdf))
7205 (let* ((revsym (find-symbol (string :*asdf-revision*) :asdf))
7206 (rev (and revsym (boundp revsym) (symbol-value revsym))))
7207 (etypecase rev
7208 (string rev)
7209 (cons (format nil "~{~D~^.~}" rev))
7210 (null "1.0"))))))
7211 ;; This (private) variable contains a list of versions of previously loaded variants of ASDF,
7212 ;; from which ASDF was upgraded.
7213 ;; Important: define *p-a-v* /before/ *a-v* so that they initialize correctly.
7214 (defvar *previous-asdf-versions*
7215 (let ((previous (asdf-version)))
7216 (when previous
7217 ;; Punt on hard package upgrade: from ASDF1 or ASDF2
7218 (when (version< previous "2.27") ;; 2.27 is the first to have the :asdf3 feature.
7219 (let ((away (format nil "~A-~A" :asdf previous)))
7220 (rename-package :asdf away)
7221 (when *load-verbose*
7222 (format t "~&; Renamed old ~A package away to ~A~%" :asdf away)))))
7223 (list previous)))
7224 ;; This public variable will be bound shortly to the currently loaded version of ASDF.
7225 (defvar *asdf-version* nil)
7226 ;; We need to clear systems from versions older than the one in this (private) parameter:
7227 (defparameter *oldest-forward-compatible-asdf-version* "2.33") ;; 2.32.13 renames a slot in component.
7228 ;; Semi-private variable: a designator for a stream on which to output ASDF progress messages
7229 (defvar *verbose-out* nil)
7230 ;; Private function by which ASDF outputs progress messages and warning messages:
7231 (defun asdf-message (format-string &rest format-args)
7232 (when *verbose-out* (apply 'format *verbose-out* format-string format-args)))
7233 ;; Private hook for functions to run after ASDF has upgraded itself from an older variant:
7234 (defvar *post-upgrade-cleanup-hook* ())
7235 ;; Private hook for functions to run after ASDF is restarted, whether by starting a process
7236 ;; from a dumped image or after upgrading from an older variant:
7237 ;; TODO: understand what happened with that hook, why functions are registered on it but it is
7238 ;; never called anymore. This is a bug that should be fixed before next release (3.1.8)!
7239 (defvar *post-upgrade-restart-hook* ())
7240 ;; Private function to detect whether the current upgrade counts as an incompatible
7241 ;; data schema upgrade implying the need to drop data.
7242 (defun upgrading-p (&optional (oldest-compatible-version *oldest-forward-compatible-asdf-version*))
7243 (and *previous-asdf-versions*
7244 (version< (first *previous-asdf-versions*) oldest-compatible-version)))
7245 ;; Private variant of defparameter that works in presence of incompatible upgrades:
7246 ;; behaves like defvar in a compatible upgrade (e.g. reloading system after simple code change),
7247 ;; but behaves like defparameter if in presence of an incompatible upgrade.
7248 (defmacro defparameter* (var value &optional docstring (version *oldest-forward-compatible-asdf-version*))
7249 (let* ((name (string-trim "*" var))
7250 (valfun (intern (format nil "%~A-~A-~A" :compute name :value))))
7251 `(progn
7252 (defun ,valfun () ,value)
7253 (defvar ,var (,valfun) ,@(ensure-list docstring))
7254 (when (upgrading-p ,version)
7255 (setf ,var (,valfun))))))
7256 ;; Private macro to declare sections of code that are only compiled and run when upgrading.
7257 ;; The use of eval portably ensures that the code will not have adverse compile-time side-effects,
7258 ;; whereas the use of handler-bind portably ensures that it will not issue warnings when it runs.
7259 (defmacro when-upgrading ((&key (version *oldest-forward-compatible-asdf-version*)
7260 (upgrading-p `(upgrading-p ,version)) when) &body body)
7261 "A wrapper macro for code that should only be run when upgrading a
7262 previously-loaded version of ASDF."
7263 `(with-upgradability ()
7264 (when (and ,upgrading-p ,@(when when `(,when)))
7265 (handler-bind ((style-warning #'muffle-warning))
7266 (eval '(progn ,@body))))))
7267 ;; Only now can we safely update the version.
7268 (let* (;; For bug reporting sanity, please always bump this version when you modify this file.
7269 ;; Please also modify asdf.asd to reflect this change. make bump-version v=3.4.5.67.8
7270 ;; can help you do these changes in synch (look at the source for documentation).
7271 ;; Relying on its automation, the version is now redundantly present on top of asdf.lisp.
7272 ;; "3.4" would be the general branch for major version 3, minor version 4.
7273 ;; "3.4.5" would be an official release in the 3.4 branch.
7274 ;; "3.4.5.67" would be a development version in the official branch, on top of 3.4.5.
7275 ;; "3.4.5.0.8" would be your eighth local modification of official release 3.4.5
7276 ;; "3.4.5.67.8" would be your eighth local modification of development version 3.4.5.67
7277 (asdf-version "3.1.8.10")
7278 (existing-version (asdf-version)))
7279 (setf *asdf-version* asdf-version)
7280 (when (and existing-version (not (equal asdf-version existing-version)))
7281 (push existing-version *previous-asdf-versions*)
7282 (when (or *verbose-out* *load-verbose*)
7283 (format (or *verbose-out* *trace-output*)
7284 (compatfmt "~&~@<; ~@;Upgrading ASDF ~@[from version ~A ~]to version ~A~@:>~%")
7285 existing-version asdf-version)))))
7286
7287 ;;; Upon upgrade, specially frob some functions and classes that are being incompatibly redefined
7288 (when-upgrading ()
7289 (let ((redefined-functions ;; gf signature and/or semantics changed incompatibly. Oops.
7290 ;; NB: it's too late to do anything about functions in UIOP!
7291 ;; If you introduce some critically incompatibility there, you must change name.
7292 '()) ;; empty now that we don't unintern, but wholly punt on ASDF 2.26 or earlier.
7293 (redefined-classes
7294 ;; redefining the classes causes interim circularities
7295 ;; with the old ASDF during upgrade, and many implementations bork
7296 '((#:compile-concatenated-source-op (#:operation) ()))))
7297 (loop :for name :in redefined-functions
7298 :for sym = (find-symbol* name :asdf nil) :do
7299 (when sym
7300 ;; CLISP seemingly can't fmakunbound and define a function in the same fasl. Sigh.
7301 #-clisp (fmakunbound sym)))
7302 (labels ((asym (x) (multiple-value-bind (s p) (if (consp x) (values (car x) (cadr x)) (values x :asdf))
7303 (find-symbol* s p nil)))
7304 (asyms (l) (mapcar #'asym l)))
7305 (loop* :for (name superclasses slots) :in redefined-classes
7306 :for sym = (find-symbol* name :asdf nil)
7307 :when (and sym (find-class sym))
7308 :do (eval `(defclass ,sym ,(asyms superclasses) ,(asyms slots)))))))
7309
7310
7311 ;;; Self-upgrade functions
7312 (with-upgradability ()
7313 ;; This private function is called at the end of asdf/footer and ensures that,
7314 ;; *if* this loading of ASDF was an upgrade, then all registered cleanup functions will be called.
7315 (defun cleanup-upgraded-asdf (&optional (old-version (first *previous-asdf-versions*)))
7316 (let ((new-version (asdf-version)))
7317 (unless (equal old-version new-version)
7318 (push new-version *previous-asdf-versions*)
7319 (when old-version
7320 (if (version<= new-version old-version)
7321 (error (compatfmt "~&~@<; ~@;Downgraded ASDF from version ~A to version ~A~@:>~%")
7322 old-version new-version)
7323 (asdf-message (compatfmt "~&~@<; ~@;Upgraded ASDF from version ~A to version ~A~@:>~%")
7324 old-version new-version))
7325 ;; In case the previous version was too old to be forward-compatible, clear systems.
7326 ;; TODO: if needed, we may have to define a separate hook to run
7327 ;; in case of forward-compatible upgrade.
7328 ;; Or to move the tests forward-compatibility test inside each hook function?
7329 (unless (version<= *oldest-forward-compatible-asdf-version* old-version)
7330 (call-functions (reverse *post-upgrade-cleanup-hook*)))
7331 t))))
7332
7333 (defun upgrade-asdf ()
7334 "Try to upgrade of ASDF. If a different version was used, return T.
7335 We need do that before we operate on anything that may possibly depend on ASDF."
7336 (let ((*load-print* nil)
7337 (*compile-print* nil))
7338 (handler-bind (((or style-warning) #'muffle-warning))
7339 (symbol-call :asdf :load-system :asdf :verbose nil))))
7340
7341 ;; Register the upgrade-configuration function from UIOP,
7342 ;; to ensure configuration is upgraded as needed.
7343 (register-hook-function '*post-upgrade-cleanup-hook* 'upgrade-configuration))
7344
7345 ;;;; -------------------------------------------------------------------------
7346 ;;;; Components
7347
7348 (uiop/package:define-package :asdf/component
7349 (:recycle :asdf/component :asdf/defsystem :asdf/find-system :asdf)
7350 (:use :uiop/common-lisp :uiop :asdf/upgrade)
7351 (:export
7352 #:component #:component-find-path
7353 #:component-name #:component-pathname #:component-relative-pathname
7354 #:component-parent #:component-system #:component-parent-pathname
7355 #:child-component #:parent-component #:module
7356 #:file-component
7357 #:source-file #:c-source-file #:java-source-file
7358 #:static-file #:doc-file #:html-file
7359 #:file-type
7360 #:source-file-type #:source-file-explicit-type ;; backward-compatibility
7361 #:component-in-order-to #:component-sideway-dependencies
7362 #:component-if-feature #:around-compile-hook
7363 #:component-description #:component-long-description
7364 #:component-version #:version-satisfies
7365 #:component-inline-methods ;; backward-compatibility only. DO NOT USE!
7366 #:component-operation-times ;; For internal use only.
7367 ;; portable ASDF encoding and implementation-specific external-format
7368 #:component-external-format #:component-encoding
7369 #:component-children-by-name #:component-children #:compute-children-by-name
7370 #:component-build-operation
7371 #:module-default-component-class
7372 #:module-components ;; backward-compatibility. DO NOT USE.
7373 #:sub-components
7374
7375 ;; conditions
7376 #:system-definition-error ;; top level, moved here because this is the earliest place for it.
7377 #:duplicate-names
7378
7379 ;; Internals we'd like to share with the ASDF package, especially for upgrade purposes
7380 #:name #:version #:description #:long-description #:author #:maintainer #:licence
7381 #:components-by-name #:components #:children #:children-by-name
7382 #:default-component-class #:source-file
7383 #:defsystem-depends-on ; This symbol retained for backward compatibility.
7384 #:sideway-dependencies #:if-feature #:in-order-to #:inline-methods
7385 #:relative-pathname #:absolute-pathname #:operation-times #:around-compile
7386 #:%encoding #:properties #:component-properties #:parent))
7387 (in-package :asdf/component)
7388
7389 (with-upgradability ()
7390 (defgeneric component-name (component)
7391 (:documentation "Name of the COMPONENT, unique relative to its parent"))
7392 (defgeneric component-system (component)
7393 (:documentation "Top-level system containing the COMPONENT"))
7394 (defgeneric component-pathname (component)
7395 (:documentation "Pathname of the COMPONENT if any, or NIL."))
7396 (defgeneric (component-relative-pathname) (component)
7397 ;; in ASDF4, rename that to component-specified-pathname ?
7398 (:documentation "Specified pathname of the COMPONENT,
7399 intended to be merged with the pathname of that component's parent if any, using merged-pathnames*.
7400 Despite the function's name, the return value can be an absolute pathname, in which case the merge
7401 will leave it unmodified."))
7402 (defgeneric component-external-format (component)
7403 (:documentation "The external-format of the COMPONENT.
7404 By default, deduced from the COMPONENT-ENCODING."))
7405 (defgeneric component-encoding (component)
7406 (:documentation "The encoding of the COMPONENT. By default, only :utf-8 is supported.
7407 Use asdf-encodings to support more encodings."))
7408 (defgeneric version-satisfies (component version)
7409 (:documentation "Check whether a COMPONENT satisfies the constraint of being at least as recent
7410 as the specified VERSION, which must be a string of dot-separated natural numbers, or NIL."))
7411 (defgeneric component-version (component)
7412 (:documentation "Return the version of a COMPONENT, which must be a string of dot-separated
7413 natural numbers, or NIL."))
7414 (defgeneric (setf component-version) (new-version component)
7415 (:documentation "Updates the version of a COMPONENT, which must be a string of dot-separated
7416 natural numbers, or NIL."))
7417 (defgeneric component-parent (component)
7418 (:documentation "The parent of a child COMPONENT,
7419 or NIL for top-level components (a.k.a. systems)"))
7420 ;; NIL is a designator for the absence of a component, in which case the parent is also absent.
7421 (defmethod component-parent ((component null)) nil)
7422
7423 ;; Deprecated: Backward compatible way of computing the FILE-TYPE of a component.
7424 ;; TODO: find users, have them stop using that, remove it for ASDF4.
7425 (defgeneric (source-file-type) (component system)
7426 (:documentation "DEPRECATED. Use the FILE-TYPE of a COMPONENT instead."))
7427
7428 (define-condition system-definition-error (error) ()
7429 ;; [this use of :report should be redundant, but unfortunately it's not.
7430 ;; cmucl's lisp::output-instance prefers the kernel:slot-class-print-function
7431 ;; over print-object; this is always conditions::%print-condition for
7432 ;; condition objects, which in turn does inheritance of :report options at
7433 ;; run-time. fortunately, inheritance means we only need this kludge here in
7434 ;; order to fix all conditions that build on it. -- rgr, 28-Jul-02.]
7435 #+cmucl (:report print-object))
7436
7437 (define-condition duplicate-names (system-definition-error)
7438 ((name :initarg :name :reader duplicate-names-name))
7439 (:report (lambda (c s)
7440 (format s (compatfmt "~@<Error while defining system: multiple components are given same name ~S~@:>")
7441 (duplicate-names-name c))))))
7442
7443
7444 (with-upgradability ()
7445 (defclass component ()
7446 ((name :accessor component-name :initarg :name :type string :documentation
7447 "Component name: designator for a string composed of portable pathname characters")
7448 ;; We might want to constrain version with
7449 ;; :type (and string (satisfies parse-version))
7450 ;; but we cannot until we fix all systems that don't use it correctly!
7451 (version :accessor component-version :initarg :version :initform nil)
7452 (description :accessor component-description :initarg :description :initform nil)
7453 (long-description :accessor component-long-description :initarg :long-description :initform nil)
7454 (sideway-dependencies :accessor component-sideway-dependencies :initform nil)
7455 (if-feature :accessor component-if-feature :initform nil :initarg :if-feature)
7456 ;; In the ASDF object model, dependencies exist between *actions*,
7457 ;; where an action is a pair of an operation and a component.
7458 ;; Dependencies are represented as alists of operations
7459 ;; to a list where each entry is a pair of an operation and a list of component specifiers.
7460 ;; Up until ASDF 2.26.9, there used to be two kinds of dependencies:
7461 ;; in-order-to and do-first, each stored in its own slot. Now there is only in-order-to.
7462 ;; in-order-to used to represent things that modify the filesystem (such as compiling a fasl)
7463 ;; and do-first things that modify the current image (such as loading a fasl).
7464 ;; These are now unified because we now correctly propagate timestamps between dependencies.
7465 ;; Happily, no one seems to have used do-first too much (especially since until ASDF 2.017,
7466 ;; anything you specified was overridden by ASDF itself anyway), but the name in-order-to remains.
7467 ;; The names are bad, but they have been the official API since Dan Barlow's ASDF 1.52!
7468 ;; LispWorks's defsystem has caused-by and requires for in-order-to and do-first respectively.
7469 ;; Maybe rename the slots in ASDF? But that's not very backward-compatible.
7470 ;; See our ASDF 2 paper for more complete explanations.
7471 (in-order-to :initform nil :initarg :in-order-to
7472 :accessor component-in-order-to)
7473 ;; Methods defined using the "inline" style inside a defsystem form:
7474 ;; we store them here so we can delete them when the system is re-evaluated.
7475 (inline-methods :accessor component-inline-methods :initform nil)
7476 ;; ASDF4: rename it from relative-pathname to specified-pathname. It need not be relative.
7477 ;; There is no initform and no direct accessor for this specified pathname,
7478 ;; so we only access the information through appropriate methods, after it has been processed.
7479 ;; Unhappily, some braindead systems directly access the slot. Make them stop before ASDF4.
7480 (relative-pathname :initarg :pathname)
7481 ;; The absolute-pathname is computed based on relative-pathname and parent pathname.
7482 ;; The slot is but a cache used by component-pathname.
7483 (absolute-pathname)
7484 (operation-times :initform (make-hash-table)
7485 :accessor component-operation-times)
7486 (around-compile :initarg :around-compile)
7487 ;; Properties are for backward-compatibility with ASDF2 only. DO NOT USE!
7488 (properties :accessor component-properties :initarg :properties
7489 :initform nil)
7490 (%encoding :accessor %component-encoding :initform nil :initarg :encoding)
7491 ;; For backward-compatibility, this slot is part of component rather than of child-component. ASDF4: stop it.
7492 (parent :initarg :parent :initform nil :reader component-parent)
7493 (build-operation
7494 :initarg :build-operation :initform nil :reader component-build-operation))
7495 (:documentation "Base class for all components of a build"))
7496
7497 (defun component-find-path (component)
7498 "Return a path from a root system to the COMPONENT.
7499 The return value is a list of component NAMES; a list of strings."
7500 (check-type component (or null component))
7501 (reverse
7502 (loop :for c = component :then (component-parent c)
7503 :while c :collect (component-name c))))
7504
7505 (defmethod print-object ((c component) stream)
7506 (print-unreadable-object (c stream :type t :identity nil)
7507 (format stream "~{~S~^ ~}" (component-find-path c))))
7508
7509 (defmethod component-system ((component component))
7510 (if-let (system (component-parent component))
7511 (component-system system)
7512 component)))
7513
7514
7515 ;;;; Component hierarchy within a system
7516 ;; The tree typically but not necessarily follows the filesystem hierarchy.
7517 (with-upgradability ()
7518 (defclass child-component (component) ()
7519 (:documentation "A CHILD-COMPONENT is a COMPONENT that may be part of
7520 a PARENT-COMPONENT."))
7521
7522 (defclass file-component (child-component)
7523 ((type :accessor file-type :initarg :type)) ; no default
7524 (:documentation "a COMPONENT that represents a file"))
7525 (defclass source-file (file-component)
7526 ((type :accessor source-file-explicit-type ;; backward-compatibility
7527 :initform nil))) ;; NB: many systems have come to rely on this default.
7528 (defclass c-source-file (source-file)
7529 ((type :initform "c")))
7530 (defclass java-source-file (source-file)
7531 ((type :initform "java")))
7532 (defclass static-file (source-file)
7533 ((type :initform nil))
7534 (:documentation "Component for a file to be included as is in the build output"))
7535 (defclass doc-file (static-file) ())
7536 (defclass html-file (doc-file)
7537 ((type :initform "html")))
7538
7539 (defclass parent-component (component)
7540 ((children
7541 :initform nil
7542 :initarg :components
7543 :reader module-components ; backward-compatibility
7544 :accessor component-children)
7545 (children-by-name
7546 :reader module-components-by-name ; backward-compatibility
7547 :accessor component-children-by-name)
7548 (default-component-class
7549 :initform nil
7550 :initarg :default-component-class
7551 :accessor module-default-component-class))
7552 (:documentation "A PARENT-COMPONENT is a component that may have children.")))
7553
7554 (with-upgradability ()
7555 ;; (Private) Function that given a PARENT component,
7556 ;; the list of children of which has been initialized,
7557 ;; compute the hash-table in slot children-by-name that allows to retrieve its children by name.
7558 ;; If ONLY-IF-NEEDED-P is defined, skip any (re)computation if the slot is already populated.
7559 (defun compute-children-by-name (parent &key only-if-needed-p)
7560 (unless (and only-if-needed-p (slot-boundp parent 'children-by-name))
7561 (let ((hash (make-hash-table :test 'equal)))
7562 (setf (component-children-by-name parent) hash)
7563 (loop :for c :in (component-children parent)
7564 :for name = (component-name c)
7565 :for previous = (gethash name hash)
7566 :do (when previous (error 'duplicate-names :name name))
7567 (setf (gethash name hash) c))
7568 hash))))
7569
7570 (with-upgradability ()
7571 (defclass module (child-component parent-component)
7572 (#+clisp (components)) ;; backward compatibility during upgrade only
7573 (:documentation "A module is a intermediate component with both a parent and children,
7574 typically but not necessarily representing the files in a subdirectory of the build source.")))
7575
7576
7577 ;;;; component pathnames
7578 (with-upgradability ()
7579 (defgeneric* (component-parent-pathname) (component)
7580 (:documentation "The pathname of the COMPONENT's parent, if any, or NIL"))
7581 (defmethod component-parent-pathname (component)
7582 (component-pathname (component-parent component)))
7583
7584 ;; The default method for component-pathname tries to extract a cached precomputed
7585 ;; absolute-pathname from the relevant slot, and if not, computes it by merging the
7586 ;; component-relative-pathname (which should be component-specified-pathname, it can be absolute)
7587 ;; with the directory of the component-parent-pathname.
7588 (defmethod component-pathname ((component component))
7589 (if (slot-boundp component 'absolute-pathname)
7590 (slot-value component 'absolute-pathname)
7591 (let ((pathname
7592 (merge-pathnames*
7593 (component-relative-pathname component)
7594 (pathname-directory-pathname (component-parent-pathname component)))))
7595 (unless (or (null pathname) (absolute-pathname-p pathname))
7596 (error (compatfmt "~@<Invalid relative pathname ~S for component ~S~@:>")
7597 pathname (component-find-path component)))
7598 (setf (slot-value component 'absolute-pathname) pathname)
7599 pathname)))
7600
7601 ;; Default method for component-relative-pathname:
7602 ;; combine the contents of slot relative-pathname (from specified initarg :pathname)
7603 ;; with the appropriate source-file-type, which defaults to the file-type of the component.
7604 (defmethod component-relative-pathname ((component component))
7605 ;; SOURCE-FILE-TYPE below is strictly for backward-compatibility with ASDF1.
7606 ;; We ought to be able to extract this from the component alone with FILE-TYPE.
7607 ;; TODO: track who uses it in Quicklisp, and have them not use it anymore;
7608 ;; maybe issue a WARNING (then eventually CERROR) if the two methods diverge?
7609 (parse-unix-namestring
7610 (or (and (slot-boundp component 'relative-pathname)
7611 (slot-value component 'relative-pathname))
7612 (component-name component))
7613 :want-relative t
7614 :type (source-file-type component (component-system component))
7615 :defaults (component-parent-pathname component)))
7616
7617 (defmethod source-file-type ((component parent-component) (system parent-component))
7618 :directory)
7619
7620 (defmethod source-file-type ((component file-component) (system parent-component))
7621 (file-type component)))
7622
7623
7624 ;;;; Encodings
7625 (with-upgradability ()
7626 (defmethod component-encoding ((c component))
7627 (or (loop :for x = c :then (component-parent x)
7628 :while x :thereis (%component-encoding x))
7629 (detect-encoding (component-pathname c))))
7630
7631 (defmethod component-external-format ((c component))
7632 (encoding-external-format (component-encoding c))))
7633
7634
7635 ;;;; around-compile-hook
7636 (with-upgradability ()
7637 (defgeneric around-compile-hook (component)
7638 (:documentation "An optional hook function that will be called with one argument, a thunk.
7639 The hook function must call the thunk, that will compile code from the component, and may or may not
7640 also evaluate the compiled results. The hook function may establish dynamic variable bindings around
7641 this compilation, or check its results, etc."))
7642 (defmethod around-compile-hook ((c component))
7643 (cond
7644 ((slot-boundp c 'around-compile)
7645 (slot-value c 'around-compile))
7646 ((component-parent c)
7647 (around-compile-hook (component-parent c))))))
7648
7649
7650 ;;;; version-satisfies
7651 (with-upgradability ()
7652 ;; short-circuit testing of null version specifications.
7653 ;; this is an all-pass, without warning
7654 (defmethod version-satisfies :around ((c t) (version null))
7655 t)
7656 (defmethod version-satisfies ((c component) version)
7657 (unless (and version (slot-boundp c 'version) (component-version c))
7658 (when version
7659 (warn "Requested version ~S but ~S has no version" version c))
7660 (return-from version-satisfies nil))
7661 (version-satisfies (component-version c) version))
7662
7663 (defmethod version-satisfies ((cver string) version)
7664 (version<= version cver)))
7665
7666
7667 ;;; all sub-components (of a given type)
7668 (with-upgradability ()
7669 (defun sub-components (component &key (type t))
7670 "Compute the transitive sub-components of given COMPONENT that are of given TYPE"
7671 (while-collecting (c)
7672 (labels ((recurse (x)
7673 (when (if-let (it (component-if-feature x)) (featurep it) t)
7674 (when (typep x type)
7675 (c x))
7676 (when (typep x 'parent-component)
7677 (map () #'recurse (component-children x))))))
7678 (recurse component)))))
7679
7680 ;;;; -------------------------------------------------------------------------
7681 ;;;; Systems
7682
7683 (uiop/package:define-package :asdf/system
7684 (:recycle :asdf :asdf/system)
7685 (:use :uiop/common-lisp :uiop :asdf/upgrade :asdf/component)
7686 (:export
7687 #:system #:proto-system
7688 #:system-source-file #:system-source-directory #:system-relative-pathname
7689 #:reset-system
7690 #:system-description #:system-long-description
7691 #:system-author #:system-maintainer #:system-licence #:system-license
7692 #:system-defsystem-depends-on #:system-depends-on #:system-weakly-depends-on
7693 #:component-build-pathname #:build-pathname
7694 #:component-entry-point #:entry-point
7695 #:homepage #:system-homepage
7696 #:bug-tracker #:system-bug-tracker
7697 #:mailto #:system-mailto
7698 #:long-name #:system-long-name
7699 #:source-control #:system-source-control
7700 #:find-system #:builtin-system-p)) ;; forward-reference, defined in find-system
7701 (in-package :asdf/system)
7702
7703 (with-upgradability ()
7704 ;; The method is actually defined in asdf/find-system,
7705 ;; but we declare the function here to avoid a forward reference.
7706 (defgeneric* (find-system) (system &optional error-p)
7707 (:documentation "Given a system designator, find the actual corresponding system object.
7708 If no system is found, then signal an error if ERROR-P is true (the default), or else return NIL.
7709 A system designator is usually a string (conventionally all lowercase) or a symbol, designating
7710 the same system as its downcased name; it can also be a system object (designating itself)."))
7711 (defgeneric* (system-source-file :supersede #-clisp t #+clisp nil) (system)
7712 (:documentation "Return the source file in which system is defined."))
7713 ;; This is bad design, but was the easiest kluge I found to let the user specify that
7714 ;; some special actions create outputs at locations controled by the user that are not affected
7715 ;; by the usual output-translations.
7716 ;; TODO: Fix operate to stop passing flags to operation (which in the current design shouldn't
7717 ;; have any flags, since the stamp cache, etc., can't distinguish them), and instead insert
7718 ;; *there* the ability of specifying special output paths, not in the system definition.
7719 (defgeneric component-build-pathname (component)
7720 (:documentation "The COMPONENT-BUILD-PATHNAME, when defined and not null, specifies the
7721 output pathname for the action using the COMPONENT-BUILD-OPERATION.
7722
7723 NB: This interface is subject to change. Please contact ASDF maintainers if you use it."))
7724
7725 ;; TODO: Should this have been made a SYSTEM-ENTRY-POINT instead?
7726 (defgeneric component-entry-point (component)
7727 (:documentation "The COMPONENT-ENTRY-POINT, when defined, specifies what function to call
7728 (with no argument) when running an image dumped from the COMPONENT.
7729
7730 NB: This interface is subject to change. Please contact ASDF maintainers if you use it."))
7731 (defmethod component-entry-point ((c component))
7732 nil))
7733
7734
7735 ;;;; The system class
7736
7737 (with-upgradability ()
7738 (defclass proto-system () ; slots to keep when resetting a system
7739 ;; To preserve identity for all objects, we'd need keep the components slots
7740 ;; but also to modify parse-component-form to reset the recycled objects.
7741 ((name) (source-file) #|(children) (children-by-names)|#)
7742 (:documentation "PROTO-SYSTEM defines the elements of identity that are preserved when
7743 a SYSTEM is redefined and its class is modified."))
7744
7745 (defclass system (module proto-system)
7746 ;; Backward-compatibility: inherit from module. ASDF4: only inherit from parent-component.
7747 (;; {,long-}description is now inherited from component, but we add the legacy accessors
7748 (description :accessor system-description)
7749 (long-description :accessor system-long-description)
7750 (author :accessor system-author :initarg :author :initform nil)
7751 (maintainer :accessor system-maintainer :initarg :maintainer :initform nil)
7752 (licence :accessor system-licence :initarg :licence
7753 :accessor system-license :initarg :license :initform nil)
7754 (homepage :accessor system-homepage :initarg :homepage :initform nil)
7755 (bug-tracker :accessor system-bug-tracker :initarg :bug-tracker :initform nil)
7756 (mailto :accessor system-mailto :initarg :mailto :initform nil)
7757 (long-name :accessor system-long-name :initarg :long-name :initform nil)
7758 ;; Conventions for this slot aren't clear yet as of ASDF 2.27, but whenever they are, they will be enforced.
7759 ;; I'm introducing the slot before the conventions are set for maximum compatibility.
7760 (source-control :accessor system-source-control :initarg :source-control :initform nil)
7761 (builtin-system-p :accessor builtin-system-p :initform nil :initarg :builtin-system-p)
7762 (build-pathname
7763 :initform nil :initarg :build-pathname :accessor component-build-pathname)
7764 (entry-point
7765 :initform nil :initarg :entry-point :accessor component-entry-point)
7766 (source-file :initform nil :initarg :source-file :accessor system-source-file)
7767 (defsystem-depends-on :reader system-defsystem-depends-on :initarg :defsystem-depends-on
7768 :initform nil)
7769 ;; these two are specially set in parse-component-form, so have no :INITARGs.
7770 (depends-on :reader system-depends-on :initform nil)
7771 (weakly-depends-on :reader system-weakly-depends-on :initform nil))
7772 (:documentation "SYSTEM is the base class for top-level components that users may request
7773 ASDF to build."))
7774
7775
7776 (defun reset-system (system &rest keys &key &allow-other-keys)
7777 "Erase any data from a SYSTEM except its basic identity, then reinitialize it
7778 based on supplied KEYS."
7779 (change-class (change-class system 'proto-system) 'system)
7780 (apply 'reinitialize-instance system keys)))
7781
7782
7783 ;;;; Pathnames
7784
7785 (with-upgradability ()
7786 ;; Resolve a system designator to a system before extracting its system-source-file
7787 (defmethod system-source-file ((system-name string))
7788 (system-source-file (find-system system-name)))
7789 (defmethod system-source-file ((system-name symbol))
7790 (system-source-file (find-system system-name)))
7791
7792 (defun system-source-directory (system-designator)
7793 "Return a pathname object corresponding to the directory
7794 in which the system specification (.asd file) is located."
7795 (pathname-directory-pathname (system-source-file system-designator)))
7796
7797 (defun (system-relative-pathname) (system name &key type)
7798 "Given a SYSTEM, and a (Unix-style relative path) NAME of a file (or directory) of given TYPE,
7799 return the absolute pathname of a corresponding file under that system's source code pathname."
7800 (subpathname (system-source-directory system) name :type type))
7801
7802 (defmethod component-pathname ((system system))
7803 "Given a SYSTEM, and a (Unix-style relative path) NAME of a file (or directory) of given TYPE,
7804 return the absolute pathname of a corresponding file under that system's source code pathname."
7805 (let ((pathname (or (call-next-method) (system-source-directory system))))
7806 (unless (and (slot-boundp system 'relative-pathname) ;; backward-compatibility with ASDF1-age
7807 (slot-value system 'relative-pathname)) ;; systems that directly access this slot.
7808 (setf (slot-value system 'relative-pathname) pathname))
7809 pathname))
7810
7811 ;; The default method of component-relative-pathname for a system:
7812 ;; if a pathname was specified in the .asd file, it must be relative to the .asd file
7813 ;; (actually, to its truename* if *resolve-symlinks* it true, the default).
7814 ;; The method will return an *absolute* pathname, once again showing that the historical name
7815 ;; component-relative-pathname is misleading and should have been component-specified-pathname.
7816 (defmethod component-relative-pathname ((system system))
7817 (parse-unix-namestring
7818 (and (slot-boundp system 'relative-pathname)
7819 (slot-value system 'relative-pathname))
7820 :want-relative t
7821 :type :directory
7822 :ensure-absolute t
7823 :defaults (system-source-directory system)))
7824
7825 ;; A system has no parent; if some method wants to make a path "relative to its parent",
7826 ;; it will instead be relative to the system itself.
7827 (defmethod component-parent-pathname ((system system))
7828 (system-source-directory system))
7829
7830 ;; Most components don't have a specified component-build-pathname, and therefore
7831 ;; no magic redirection of their output that disregards the output-translations.
7832 (defmethod component-build-pathname ((c component))
7833 nil))
7834
7835 ;;;; -------------------------------------------------------------------------
7836 ;;;; Session cache
7837
7838 (uiop/package:define-package :asdf/cache
7839 (:use :uiop/common-lisp :uiop :asdf/upgrade)
7840 (:export #:get-file-stamp #:compute-file-stamp #:register-file-stamp
7841 #:set-asdf-cache-entry #:unset-asdf-cache-entry #:consult-asdf-cache
7842 #:do-asdf-cache #:normalize-namestring
7843 #:call-with-asdf-cache #:with-asdf-cache #:*asdf-cache*
7844 #:clear-configuration-and-retry #:retry))
7845 (in-package :asdf/cache)
7846
7847 ;;; The ASDF session cache is used to memoize some computations. It is instrumental in achieving:
7848 ;; * Consistency in the view of the world relied on by ASDF within a given session.
7849 ;; Inconsistencies in file stamps, system definitions, etc., could cause infinite loops
7850 ;; (a.k.a. stack overflows) and other erratic behavior.
7851 ;; * Speed and reliability of ASDF, with fewer side-effects from access to the filesystem, and
7852 ;; no expensive recomputations of transitive dependencies for some input-files or output-files.
7853 ;; * Testability of ASDF with the ability to fake timestamps without actually touching files.
7854
7855 (with-upgradability ()
7856 ;; The session cache variable.
7857 ;; NIL when outside a session, an equal hash-table when inside a session.
7858 (defvar *asdf-cache* nil)
7859
7860 ;; Set a session cache entry for KEY to a list of values VALUE-LIST, when inside a session.
7861 ;; Return those values.
7862 (defun set-asdf-cache-entry (key value-list)
7863 (values-list (if *asdf-cache*
7864 (setf (gethash key *asdf-cache*) value-list)
7865 value-list)))
7866
7867 ;; Unset the session cache entry for KEY, when inside a session.
7868 (defun unset-asdf-cache-entry (key)
7869 (when *asdf-cache*
7870 (remhash key *asdf-cache*)))
7871
7872 ;; Consult the session cache entry for KEY if present and in a session;
7873 ;; if not present, compute it by calling the THUNK,
7874 ;; and set the session cache entry accordingly, if in a session.
7875 ;; Return the values from the cache and/or the thunk computation.
7876 (defun consult-asdf-cache (key &optional thunk)
7877 (if *asdf-cache*
7878 (multiple-value-bind (results foundp) (gethash key *asdf-cache*)
7879 (if foundp
7880 (values-list results)
7881 (set-asdf-cache-entry key (multiple-value-list (call-function thunk)))))
7882 (call-function thunk)))
7883
7884 ;; Syntactic sugar for consult-asdf-cache
7885 (defmacro do-asdf-cache (key &body body)
7886 `(consult-asdf-cache ,key #'(lambda () ,@body)))
7887
7888 ;; Compute inside a ASDF session with a cache.
7889 ;; First, make sure an ASDF session is underway, by binding the session cache variable
7890 ;; to a new hash-table if it's currently null (or even if it isn't, if OVERRIDE is true).
7891 ;; Second, if a new session was started, establish restarts for retrying the overall computation.
7892 ;; Finally, consult the cache if a KEY was specified with the THUNK as a fallback when the cache
7893 ;; entry isn't found, or just call the THUNK if no KEY was specified.
7894 (defun call-with-asdf-cache (thunk &key override key)
7895 (let ((fun (if key #'(lambda () (consult-asdf-cache key thunk)) thunk)))
7896 (if (and *asdf-cache* (not override))
7897 (funcall fun)
7898 (loop
7899 (restart-case
7900 (let ((*asdf-cache* (make-hash-table :test 'equal)))
7901 (return (funcall fun)))
7902 (retry ()
7903 :report (lambda (s)
7904 (format s (compatfmt "~@<Retry ASDF operation.~@:>"))))
7905 (clear-configuration-and-retry ()
7906 :report (lambda (s)
7907 (format s (compatfmt "~@<Retry ASDF operation after resetting the configuration.~@:>")))
7908 (clear-configuration)))))))
7909
7910 ;; Syntactic sugar for call-with-asdf-cache
7911 (defmacro with-asdf-cache ((&key key override) &body body)
7912 `(call-with-asdf-cache #'(lambda () ,@body) :override ,override :key ,key))
7913
7914
7915 ;;; Define specific accessor for file (date) stamp.
7916
7917 ;; Normalize a namestring for use as a key in the session cache.
7918 (defun normalize-namestring (pathname)
7919 (let ((resolved (resolve-symlinks*
7920 (ensure-absolute-pathname
7921 (physicalize-pathname pathname)
7922 'get-pathname-defaults))))
7923 (with-pathname-defaults () (namestring resolved))))
7924
7925 ;; Compute the file stamp for a normalized namestring
7926 (defun compute-file-stamp (normalized-namestring)
7927 (with-pathname-defaults ()
7928 (safe-file-write-date normalized-namestring)))
7929
7930 ;; Override the time STAMP associated to a given FILE in the session cache.
7931 ;; If no STAMP is specified, recompute a new one from the filesystem.
7932 (defun register-file-stamp (file &optional (stamp nil stampp))
7933 (let* ((namestring (normalize-namestring file))
7934 (stamp (if stampp stamp (compute-file-stamp namestring))))
7935 (set-asdf-cache-entry `(get-file-stamp ,namestring) (list stamp))))
7936
7937 ;; Get or compute a memoized stamp for given FILE from the session cache.
7938 (defun get-file-stamp (file)
7939 (when file
7940 (let ((namestring (normalize-namestring file)))
7941 (do-asdf-cache `(get-file-stamp ,namestring) (compute-file-stamp namestring))))))
7942
7943 ;;;; -------------------------------------------------------------------------
7944 ;;;; Finding systems
7945
7946 (uiop/package:define-package :asdf/find-system
7947 (:recycle :asdf/find-system :asdf)
7948 (:use :uiop/common-lisp :uiop :asdf/upgrade
7949 :asdf/cache :asdf/component :asdf/system)
7950 (:export
7951 #:remove-entry-from-registry #:coerce-entry-to-directory
7952 #:coerce-name #:primary-system-name #:coerce-filename
7953 #:find-system #:locate-system #:load-asd
7954 #:system-registered-p #:registered-system #:register-system
7955 #:registered-systems* #:registered-systems
7956 #:clear-system #:map-systems
7957 #:missing-component #:missing-requires #:missing-parent
7958 #:formatted-system-definition-error #:format-control #:format-arguments #:sysdef-error
7959 #:load-system-definition-error #:error-name #:error-pathname #:error-condition
7960 #:*system-definition-search-functions* #:search-for-system-definition
7961 #:*central-registry* #:probe-asd #:sysdef-central-registry-search
7962 #:find-system-if-being-defined
7963 #:contrib-sysdef-search #:sysdef-find-asdf ;; backward compatibility symbols, functions removed
7964 #:sysdef-preloaded-system-search #:register-preloaded-system #:*preloaded-systems*
7965 #:mark-component-preloaded ;; forward reference to asdf/operate
7966 #:sysdef-immutable-system-search #:register-immutable-system #:*immutable-systems*
7967 #:*defined-systems* #:clear-defined-systems
7968 ;; defined in source-registry, but specially mentioned here:
7969 #:initialize-source-registry #:sysdef-source-registry-search))
7970 (in-package :asdf/find-system)
7971
7972 (with-upgradability ()
7973 (declaim (ftype (function (&optional t) t) initialize-source-registry)) ; forward reference
7974
7975 (define-condition missing-component (system-definition-error)
7976 ((requires :initform "(unnamed)" :reader missing-requires :initarg :requires)
7977 (parent :initform nil :reader missing-parent :initarg :parent)))
7978
7979 (define-condition formatted-system-definition-error (system-definition-error)
7980 ((format-control :initarg :format-control :reader format-control)
7981 (format-arguments :initarg :format-arguments :reader format-arguments))
7982 (:report (lambda (c s)
7983 (apply 'format s (format-control c) (format-arguments c)))))
7984
7985 (define-condition load-system-definition-error (system-definition-error)
7986 ((name :initarg :name :reader error-name)
7987 (pathname :initarg :pathname :reader error-pathname)
7988 (condition :initarg :condition :reader error-condition))
7989 (:report (lambda (c s)
7990 (format s (compatfmt "~@<Error while trying to load definition for system ~A from pathname ~A: ~3i~_~A~@:>")
7991 (error-name c) (error-pathname c) (error-condition c)))))
7992
7993 (defun sysdef-error (format &rest arguments)
7994 (error 'formatted-system-definition-error :format-control
7995 format :format-arguments arguments))
7996
7997
7998 ;;; Canonicalizing system names
7999
8000 (defun coerce-name (name)
8001 "Given a designator for a component NAME, return the name as a string.
8002 The designator can be a COMPONENT (designing its name; note that a SYSTEM is a component),
8003 a SYMBOL (designing its name, downcased), or a STRING (designing itself)."
8004 (typecase name
8005 (component (component-name name))
8006 (symbol (string-downcase name))
8007 (string name)
8008 (t (sysdef-error (compatfmt "~@<Invalid component designator: ~3i~_~A~@:>") name))))
8009
8010 (defun primary-system-name (name)
8011 "Given a system designator NAME, return the name of the corresponding primary system,
8012 after which the .asd file is named. That's the first component when dividing the name
8013 as a string by / slashes."
8014 (first (split-string (coerce-name name) :separator "/")))
8015
8016 (defun coerce-filename (name)
8017 "Coerce a system designator NAME into a string suitable as a filename component.
8018 The (current) transformation is to replace characters /:\\ each by --,
8019 the former being forbidden in a filename component.
8020 NB: The onus is unhappily on the user to avoid clashes."
8021 (frob-substrings (coerce-name name) '("/" ":" "\\") "--"))
8022
8023
8024 ;;; Registry of Defined Systems
8025
8026 (defvar *defined-systems* (make-hash-table :test 'equal)
8027 "This is a hash table whose keys are strings -- the
8028 names of systems -- and whose values are pairs, the first
8029 element of which is a universal-time indicating when the
8030 system definition was last updated, and the second element
8031 of which is a system object.
8032 A system is referred to as \"registered\" if it is present
8033 in this table.")
8034
8035 (defun system-registered-p (name)
8036 "Return a generalized boolean that is true if a system of given NAME was registered already.
8037 NAME is a system designator, to be normalized by COERCE-NAME.
8038 The value returned if true is a pair of a timestamp and a system object."
8039 (gethash (coerce-name name) *defined-systems*))
8040
8041 (defun registered-system (name)
8042 "Return a system of given NAME that was registered already,
8043 if such a system exists. NAME is a system designator, to be
8044 normalized by COERCE-NAME. The value returned is a system object,
8045 or NIL if not found."
8046 (cdr (system-registered-p name)))
8047
8048 (defun registered-systems* ()
8049 "Return a list containing every registered system (as a system object)."
8050 (loop :for registered :being :the :hash-values :of *defined-systems*
8051 :collect (cdr registered)))
8052
8053 (defun registered-systems ()
8054 "Return a list of the names of every registered system."
8055 (mapcar 'coerce-name (registered-systems*)))
8056
8057 (defun register-system (system)
8058 "Given a SYSTEM object, register it."
8059 (check-type system system)
8060 (let ((name (component-name system)))
8061 (check-type name string)
8062 (asdf-message (compatfmt "~&~@<; ~@;Registering ~3i~_~A~@:>~%") system)
8063 (unless (eq system (registered-system name))
8064 (setf (gethash name *defined-systems*)
8065 (cons (ignore-errors (get-file-stamp (system-source-file system)))
8066 system)))))
8067
8068
8069 ;;; Preloaded systems: in the image even if you can't find source files backing them.
8070
8071 (defvar *preloaded-systems* (make-hash-table :test 'equal)
8072 "Registration table for preloaded systems.")
8073
8074 (declaim (ftype (function (t) t) mark-component-preloaded)) ; defined in asdf/operate
8075
8076 (defun make-preloaded-system (name keys)
8077 "Make a preloaded system of given NAME with build information from KEYS"
8078 (let ((system (apply 'make-instance (getf keys :class 'system)
8079 :name name :source-file (getf keys :source-file)
8080 (remove-plist-keys '(:class :name :source-file) keys))))
8081 (mark-component-preloaded system)
8082 system))
8083
8084 (defun sysdef-preloaded-system-search (requested)
8085 "If REQUESTED names a system registered as preloaded, return a new system
8086 with its registration information."
8087 (let ((name (coerce-name requested)))
8088 (multiple-value-bind (keys foundp) (gethash name *preloaded-systems*)
8089 (when foundp
8090 (make-preloaded-system name keys)))))
8091
8092 (defun ensure-preloaded-system-registered (name)
8093 "If there isn't a registered _defined_ system of given NAME,
8094 and a there is a registered _preloaded_ system of given NAME,
8095 then define and register said preloaded system."
8096 (if-let (system (and (not (registered-system name)) (sysdef-preloaded-system-search name)))
8097 (register-system system)))
8098
8099 (defun ensure-all-preloaded-systems-registered ()
8100 "Make sure all registered preloaded systems are defined.
8101 This function is run whenever ASDF is upgraded."
8102 (loop :for name :being :the :hash-keys :of *preloaded-systems*
8103 :do (ensure-preloaded-system-registered name)))
8104 (register-hook-function '*post-upgrade-restart-hook* 'ensure-all-preloaded-systems-registered)
8105
8106 (defun register-preloaded-system (system-name &rest keys &key (version t) &allow-other-keys)
8107 "Register a system as being preloaded. If the system has not been loaded from the filesystem
8108 yet, or if its build information is later cleared with CLEAR-SYSTEM, a dummy system will be
8109 registered without backing filesystem information, based on KEYS (e.g. to provide a VERSION).
8110 If VERSION is the default T, and a system was already loaded, then its version will be preserved."
8111 (let ((name (coerce-name system-name)))
8112 (when (eql version t)
8113 (if-let (system (registered-system name))
8114 (setf (getf keys :version) (component-version system))))
8115 (setf (gethash name *preloaded-systems*) keys)
8116 (ensure-preloaded-system-registered system-name)))
8117
8118
8119 ;;; Immutable systems: in the image and can't be reloaded from source.
8120
8121 (defvar *immutable-systems* nil
8122 "A hash-set (equal hash-table mapping keys to T) of systems that are immutable,
8123 i.e. already loaded in memory and not to be refreshed from the filesystem.
8124 They will be treated specially by find-system, and passed as :force-not argument to make-plan.
8125
8126 For instance, to can deliver an image with many systems precompiled, that *will not* check the
8127 filesystem for them every time a user loads an extension, what more risk a problematic upgrade
8128 or catastrophic downgrade, before you dump an image, you may use:
8129 (map () 'asdf:register-immutable-system (asdf:already-loaded-systems))
8130
8131 Note that direct access to this variable from outside ASDF is not supported.
8132 Please call REGISTER-IMMUTABLE-SYSTEM to add new immutable systems, and
8133 contact maintainers if you need a stable API to do more than that.")
8134
8135 (defun sysdef-immutable-system-search (requested)
8136 (let ((name (coerce-name requested)))
8137 (when (and *immutable-systems* (gethash name *immutable-systems*))
8138 (or (registered-system requested)
8139 (error 'formatted-system-definition-error
8140 :format-control "Requested system ~A registered as an immutable-system, ~
8141 but not even registered as defined"
8142 :format-arguments (list name))))))
8143
8144 (defun register-immutable-system (system-name &rest keys)
8145 "Register SYSTEM-NAME as preloaded and immutable.
8146 It will automatically be considered as passed to FORCE-NOT in a plan."
8147 (let ((system-name (coerce-name system-name)))
8148 (apply 'register-preloaded-system system-name keys)
8149 (unless *immutable-systems*
8150 (setf *immutable-systems* (list-to-hash-set nil)))
8151 (setf (gethash system-name *immutable-systems*) t)))
8152
8153
8154 ;;; Making systems undefined.
8155
8156 (defun clear-system (system)
8157 "Clear the entry for a SYSTEM in the database of systems previously defined.
8158 However if the system was registered as PRELOADED (which it is if it is IMMUTABLE),
8159 then a new system with the same name will be defined and registered in its place
8160 from which build details will have been cleared.
8161 Note that this does NOT in any way cause any of the code of the system to be unloaded.
8162 Returns T if system was or is now undefined, NIL if a new preloaded system was redefined."
8163 ;; There is no "unload" operation in Common Lisp, and
8164 ;; a general such operation cannot be portably written,
8165 ;; considering how much CL relies on side-effects to global data structures.
8166 (let ((name (coerce-name system)))
8167 (remhash name *defined-systems*)
8168 (unset-asdf-cache-entry `(find-system ,name))
8169 (not (ensure-preloaded-system-registered name))))
8170
8171 (defun clear-defined-systems ()
8172 "Clear all currently registered defined systems.
8173 Preloaded systems (including immutable ones) will be reset, other systems will be de-registered."
8174 (loop :for name :being :the :hash-keys :of *defined-systems*
8175 :unless (equal name "asdf") :do (clear-system name)))
8176
8177 (register-hook-function '*post-upgrade-cleanup-hook* 'clear-defined-systems nil)
8178
8179 (defun map-systems (fn)
8180 "Apply FN to each defined system.
8181
8182 FN should be a function of one argument. It will be
8183 called with an object of type asdf:system."
8184 (loop :for registered :being :the :hash-values :of *defined-systems*
8185 :do (funcall fn (cdr registered))))
8186
8187
8188 ;;; Searching for system definitions
8189
8190 ;; For the sake of keeping things reasonably neat, we adopt a convention that
8191 ;; only symbols are to be pushed to this list (rather than e.g. function objects),
8192 ;; which makes upgrade easier. Also, the name of these symbols shall start with SYSDEF-
8193 (defvar *system-definition-search-functions* '()
8194 "A list that controls the ways that ASDF looks for system definitions.
8195 It contains symbols to be funcalled in order, with a requested system name as argument,
8196 until one returns a non-NIL result (if any), which must then be a fully initialized system object
8197 with that name.")
8198
8199 ;; Initialize and/or upgrade the *system-definition-search-functions*
8200 ;; so it doesn't contain obsolete symbols, and does contain the current ones.
8201 (defun cleanup-system-definition-search-functions ()
8202 (setf *system-definition-search-functions*
8203 (append
8204 ;; Remove known-incompatible sysdef functions from old versions of asdf.
8205 ;; Order matters, so we can't just use set-difference.
8206 (let ((obsolete
8207 '(contrib-sysdef-search sysdef-find-asdf sysdef-preloaded-system-search)))
8208 (remove-if #'(lambda (x) (member x obsolete)) *system-definition-search-functions*))
8209 ;; Tuck our defaults at the end of the list if they were absent.
8210 ;; This is imperfect, in case they were removed on purpose,
8211 ;; but then it will be the responsibility of whoever removes these symmbols
8212 ;; to upgrade asdf before he does such a thing rather than after.
8213 (remove-if #'(lambda (x) (member x *system-definition-search-functions*))
8214 '(sysdef-central-registry-search
8215 sysdef-source-registry-search)))))
8216 (cleanup-system-definition-search-functions)
8217
8218 ;; This (private) function does the search for a system definition using *s-d-s-f*;
8219 ;; it is to be called by locate-system.
8220 (defun search-for-system-definition (system)
8221 ;; Search for valid definitions of the system available in the current session.
8222 ;; Previous definitions as registered in *defined-systems* MUST NOT be considered;
8223 ;; they will be reconciled by locate-system then find-system.
8224 ;; There are two special treatments: first, specially search for objects being defined
8225 ;; in the current session, to avoid definition races between several files;
8226 ;; second, specially search for immutable systems, so they cannot be redefined.
8227 ;; Finally, use the search functions specified in *system-definition-search-functions*.
8228 (let ((name (coerce-name system)))
8229 (flet ((try (f) (if-let ((x (funcall f name))) (return-from search-for-system-definition x))))
8230 (try 'find-system-if-being-defined)
8231 (try 'sysdef-immutable-system-search)
8232 (map () #'try *system-definition-search-functions*))))
8233
8234
8235 ;;; The legacy way of finding a system: the *central-registry*
8236
8237 ;; This variable contains a list of directories to be lazily searched for the requested asd
8238 ;; by sysdef-central-registry-search.
8239 (defvar *central-registry* nil
8240 "A list of 'system directory designators' ASDF uses to find systems.
8241
8242 A 'system directory designator' is a pathname or an expression
8243 which evaluates to a pathname. For example:
8244
8245 (setf asdf:*central-registry*
8246 (list '*default-pathname-defaults*
8247 #p\"/home/me/cl/systems/\"
8248 #p\"/usr/share/common-lisp/systems/\"))
8249
8250 This variable is for backward compatibility.
8251 Going forward, we recommend new users should be using the source-registry.")
8252
8253 ;; Function to look for an asd file of given NAME under a directory provided by DEFAULTS.
8254 ;; Return the truename of that file if it is found and TRUENAME is true.
8255 ;; Return NIL if the file is not found.
8256 ;; On Windows, follow shortcuts to .asd files.
8257 (defun probe-asd (name defaults &key truename)
8258 (block nil
8259 (when (directory-pathname-p defaults)
8260 (if-let (file (probe-file*
8261 (ensure-absolute-pathname
8262 (parse-unix-namestring name :type "asd")
8263 #'(lambda () (ensure-absolute-pathname defaults 'get-pathname-defaults nil))
8264 nil)
8265 :truename truename))
8266 (return file))
8267 #-(or clisp genera) ; clisp doesn't need it, plain genera doesn't have read-sequence(!)
8268 (os-cond
8269 ((os-windows-p)
8270 (when (physical-pathname-p defaults)
8271 (let ((shortcut
8272 (make-pathname
8273 :defaults defaults :case :local
8274 :name (strcat name ".asd")
8275 :type "lnk")))
8276 (when (probe-file* shortcut)
8277 (ensure-pathname (parse-windows-shortcut shortcut) :namestring :native)))))))))
8278
8279 ;; Function to push onto *s-d-s-f* to use the *central-registry*
8280 (defun sysdef-central-registry-search (system)
8281 (let ((name (primary-system-name system))
8282 (to-remove nil)
8283 (to-replace nil))
8284 (block nil
8285 (unwind-protect
8286 (dolist (dir *central-registry*)
8287 (let ((defaults (eval dir))
8288 directorized)
8289 (when defaults
8290 (cond ((directory-pathname-p defaults)
8291 (let* ((file (probe-asd name defaults :truename *resolve-symlinks*)))
8292 (when file
8293 (return file))))
8294 (t
8295 (restart-case
8296 (let* ((*print-circle* nil)
8297 (message
8298 (format nil
8299 (compatfmt "~@<While searching for system ~S: ~3i~_~S evaluated to ~S which is not an absolute directory.~@:>")
8300 system dir defaults)))
8301 (error message))
8302 (remove-entry-from-registry ()
8303 :report "Remove entry from *central-registry* and continue"
8304 (push dir to-remove))
8305 (coerce-entry-to-directory ()
8306 :test (lambda (c) (declare (ignore c))
8307 (and (not (directory-pathname-p defaults))
8308 (directory-pathname-p
8309 (setf directorized
8310 (ensure-directory-pathname defaults)))))
8311 :report (lambda (s)
8312 (format s (compatfmt "~@<Coerce entry to ~a, replace ~a and continue.~@:>")
8313 directorized dir))
8314 (push (cons dir directorized) to-replace))))))))
8315 ;; cleanup
8316 (dolist (dir to-remove)
8317 (setf *central-registry* (remove dir *central-registry*)))
8318 (dolist (pair to-replace)
8319 (let* ((current (car pair))
8320 (new (cdr pair))
8321 (position (position current *central-registry*)))
8322 (setf *central-registry*
8323 (append (subseq *central-registry* 0 position)
8324 (list new)
8325 (subseq *central-registry* (1+ position))))))))))
8326
8327
8328 ;;; Methods for find-system
8329
8330 ;; Reject NIL as a system designator.
8331 (defmethod find-system ((name null) &optional (error-p t))
8332 (when error-p
8333 (sysdef-error (compatfmt "~@<NIL is not a valid system name~@:>"))))
8334
8335 ;; Default method for find-system: resolve the argument using COERCE-NAME.
8336 (defmethod find-system (name &optional (error-p t))
8337 (find-system (coerce-name name) error-p))
8338
8339 (defun find-system-if-being-defined (name)
8340 ;; This function finds systems being defined *in the current ASDF session*, as embodied by
8341 ;; its session cache, even before they are fully defined and registered in *defined-systems*.
8342 ;; The purpose of this function is to prevent races between two files that might otherwise
8343 ;; try overwrite each other's system objects, resulting in infinite loops and stack overflow.
8344 ;; This function explicitly MUST NOT find definitions merely registered in previous sessions.
8345 ;; NB: this function depends on a corresponding side-effect in parse-defsystem;
8346 ;; the precise protocol between the two functions may change in the future (or not).
8347 (first (gethash `(find-system ,(coerce-name name)) *asdf-cache*)))
8348
8349 (defun load-asd (pathname
8350 &key name (external-format (encoding-external-format (detect-encoding pathname)))
8351 &aux (readtable *readtable*) (print-pprint-dispatch *print-pprint-dispatch*))
8352 "Load system definitions from PATHNAME.
8353 NAME if supplied is the name of a system expected to be defined in that file.
8354
8355 Do NOT try to load a .asd file directly with CL:LOAD. Always use ASDF:LOAD-ASD."
8356 (with-asdf-cache ()
8357 (with-standard-io-syntax
8358 (let ((*package* (find-package :asdf-user))
8359 ;; Note that our backward-compatible *readtable* is
8360 ;; a global readtable that gets globally side-effected. Ouch.
8361 ;; Same for the *print-pprint-dispatch* table.
8362 ;; We should do something about that for ASDF3 if possible, or else ASDF4.
8363 (*readtable* readtable)
8364 (*print-pprint-dispatch* print-pprint-dispatch)
8365 (*print-readably* nil)
8366 (*default-pathname-defaults*
8367 ;; resolve logical-pathnames so they won't wreak havoc in parsing namestrings.
8368 (pathname-directory-pathname (physicalize-pathname pathname))))
8369 (handler-bind
8370 (((and error (not missing-component))
8371 #'(lambda (condition)
8372 (error 'load-system-definition-error
8373 :name name :pathname pathname :condition condition))))
8374 (asdf-message (compatfmt "~&~@<; ~@;Loading system definition~@[ for ~A~] from ~A~@:>~%")
8375 name pathname)
8376 (load* pathname :external-format external-format))))))
8377
8378 (defvar *old-asdf-systems* (make-hash-table :test 'equal))
8379
8380 ;; (Private) function to check that a system that was found isn't an asdf downgrade.
8381 ;; Returns T if everything went right, NIL if the system was an ASDF of the same or older version,
8382 ;; that shall not be loaded. Also issue a warning if it was a strictly older version of ASDF.
8383 (defun check-not-old-asdf-system (name pathname)
8384 (or (not (equal name "asdf"))
8385 (null pathname)
8386 (let* ((version-pathname (subpathname pathname "version.lisp-expr"))
8387 (version (and (probe-file* version-pathname :truename nil)
8388 (read-file-form version-pathname)))
8389 (old-version (asdf-version)))
8390 (cond
8391 ((version< old-version version) t) ;; newer version: good!
8392 ((equal old-version version) nil) ;; same version: don't load, but don't warn
8393 (t ;; old version: bad
8394 (ensure-gethash
8395 (list (namestring pathname) version) *old-asdf-systems*
8396 #'(lambda ()
8397 (let ((old-pathname
8398 (if-let (pair (system-registered-p "asdf"))
8399 (system-source-file (cdr pair)))))
8400 (warn "~@<~
8401 You are using ASDF version ~A ~:[(probably from (require \"asdf\") ~
8402 or loaded by quicklisp)~;from ~:*~S~] and have an older version of ASDF ~
8403 ~:[(and older than 2.27 at that)~;~:*~A~] registered at ~S. ~
8404 Having an ASDF installed and registered is the normal way of configuring ASDF to upgrade itself, ~
8405 and having an old version registered is a configuration error. ~
8406 ASDF will ignore this configured system rather than downgrade itself. ~
8407 In the future, you may want to either: ~
8408 (a) upgrade this configured ASDF to a newer version, ~
8409 (b) install a newer ASDF and register it in front of the former in your configuration, or ~
8410 (c) uninstall or unregister this and any other old version of ASDF from your configuration. ~
8411 Note that the older ASDF might be registered implicitly through configuration inherited ~
8412 from your system installation, in which case you might have to specify ~
8413 :ignore-inherited-configuration in your in your ~~/.config/common-lisp/source-registry.conf ~
8414 or other source-registry configuration file, environment variable or lisp parameter. ~
8415 Indeed, a likely offender is an obsolete version of the cl-asdf debian or ubuntu package, ~
8416 that you might want to upgrade (if a recent enough version is available) ~
8417 or else remove altogether (since most implementations ship with a recent asdf); ~
8418 if you lack the system administration rights to upgrade or remove this package, ~
8419 then you might indeed want to either install and register a more recent version, ~
8420 or use :ignore-inherited-configuration to avoid registering the old one. ~
8421 Please consult ASDF documentation and/or experts.~@:>~%"
8422 old-version old-pathname version pathname))))
8423 nil))))) ;; only issue the warning the first time, but always return nil
8424
8425 (defun locate-system (name)
8426 "Given a system NAME designator, try to locate where to load the system from.
8427 Returns five values: FOUNDP FOUND-SYSTEM PATHNAME PREVIOUS PREVIOUS-TIME
8428 FOUNDP is true when a system was found,
8429 either a new unregistered one or a previously registered one.
8430 FOUND-SYSTEM when not null is a SYSTEM object that may be REGISTER-SYSTEM'ed.
8431 PATHNAME when not null is a path from which to load the system,
8432 either associated with FOUND-SYSTEM, or with the PREVIOUS system.
8433 PREVIOUS when not null is a previously loaded SYSTEM object of same name.
8434 PREVIOUS-TIME when not null is the time at which the PREVIOUS system was loaded."
8435 (with-asdf-cache () ;; NB: We don't cache the results. We once used to, but it wasn't useful,
8436 ;; and keeping a negative cache was a bug (see lp#1335323), which required
8437 ;; explicit invalidation in clear-system and find-system (when unsucccessful).
8438 (let* ((name (coerce-name name))
8439 (in-memory (system-registered-p name)) ; load from disk if absent or newer on disk
8440 (previous (cdr in-memory))
8441 (previous (and (typep previous 'system) previous))
8442 (previous-time (car in-memory))
8443 (found (search-for-system-definition name))
8444 (found-system (and (typep found 'system) found))
8445 (pathname (ensure-pathname
8446 (or (and (typep found '(or pathname string)) (pathname found))
8447 (and found-system (system-source-file found-system))
8448 (and previous (system-source-file previous)))
8449 :want-absolute t :resolve-symlinks *resolve-symlinks*))
8450 (foundp (and (or found-system pathname previous) t)))
8451 (check-type found (or null pathname system))
8452 (unless (check-not-old-asdf-system name pathname)
8453 (check-type previous system) ;; asdf is preloaded, so there should be a previous one.
8454 (setf found-system nil pathname nil))
8455 (values foundp found-system pathname previous previous-time))))
8456
8457 ;; Main method for find-system: first, make sure the computation is memoized in a session cache.
8458 ;; unless the system is immutable, use locate-system to find the primary system;
8459 ;; reconcile the finding (if any) with any previous definition (in a previous session,
8460 ;; preloaded, with a previous configuration, or before filesystem changes), and
8461 ;; load a found .asd if appropriate. Finally, update registration table and return results.
8462 (defmethod find-system ((name string) &optional (error-p t))
8463 (with-asdf-cache (:key `(find-system ,name))
8464 (let ((primary-name (primary-system-name name)))
8465 (unless (equal name primary-name)
8466 (find-system primary-name nil)))
8467 (or (and *immutable-systems* (gethash name *immutable-systems*) (registered-system name))
8468 (multiple-value-bind (foundp found-system pathname previous previous-time)
8469 (locate-system name)
8470 (assert (eq foundp (and (or found-system pathname previous) t)))
8471 (let ((previous-pathname (and previous (system-source-file previous)))
8472 (system (or previous found-system)))
8473 (when (and found-system (not previous))
8474 (register-system found-system))
8475 (when (and system pathname)
8476 (setf (system-source-file system) pathname))
8477 (when (and pathname
8478 (let ((stamp (get-file-stamp pathname)))
8479 (and stamp
8480 (not (and previous
8481 (or (pathname-equal pathname previous-pathname)
8482 (and pathname previous-pathname
8483 (pathname-equal
8484 (physicalize-pathname pathname)
8485 (physicalize-pathname previous-pathname))))
8486 (stamp<= stamp previous-time))))))
8487 ;; Only load when it's a pathname that is different or has newer content.
8488 (load-asd pathname :name name)))
8489 ;; Try again after having loaded from disk if needed
8490 (let ((in-memory (system-registered-p name)))
8491 (cond
8492 (in-memory
8493 (when pathname
8494 (setf (car in-memory) (get-file-stamp pathname)))
8495 (cdr in-memory))
8496 (error-p
8497 (error 'missing-component :requires name))
8498 (t
8499 (return-from find-system nil)))))))))
8500 ;;;; -------------------------------------------------------------------------
8501 ;;;; Finding components
8502
8503 (uiop/package:define-package :asdf/find-component
8504 (:recycle :asdf/find-component :asdf)
8505 (:use :uiop/common-lisp :uiop :asdf/upgrade :asdf/cache
8506 :asdf/component :asdf/system :asdf/find-system)
8507 (:export
8508 #:find-component
8509 #:resolve-dependency-name #:resolve-dependency-spec
8510 #:resolve-dependency-combination
8511 ;; Conditions
8512 #:missing-component #:missing-component-of-version #:retry
8513 #:missing-dependency #:missing-dependency-of-version
8514 #:missing-requires #:missing-parent
8515 #:missing-required-by #:missing-version))
8516 (in-package :asdf/find-component)
8517
8518 ;;;; Missing component conditions
8519
8520 (with-upgradability ()
8521 (define-condition missing-component-of-version (missing-component)
8522 ((version :initform nil :reader missing-version :initarg :version)))
8523
8524 (define-condition missing-dependency (missing-component)
8525 ((required-by :initarg :required-by :reader missing-required-by)))
8526
8527 (defmethod print-object ((c missing-dependency) s)
8528 (format s (compatfmt "~@<~A, required by ~A~@:>")
8529 (call-next-method c nil) (missing-required-by c)))
8530
8531 (define-condition missing-dependency-of-version (missing-dependency
8532 missing-component-of-version)
8533 ())
8534
8535 (defmethod print-object ((c missing-component) s)
8536 (format s (compatfmt "~@<Component ~S not found~@[ in ~A~]~@:>")
8537 (missing-requires c)
8538 (when (missing-parent c)
8539 (coerce-name (missing-parent c)))))
8540
8541 (defmethod print-object ((c missing-component-of-version) s)
8542 (format s (compatfmt "~@<Component ~S does not match version ~A~@[ in ~A~]~@:>")
8543 (missing-requires c)
8544 (missing-version c)
8545 (when (missing-parent c)
8546 (coerce-name (missing-parent c))))))
8547
8548
8549 ;;;; Finding components
8550
8551 (with-upgradability ()
8552 (defgeneric* (find-component) (base path &key registered)
8553 (:documentation "Find a component by resolving the PATH starting from BASE parent.
8554 If REGISTERED is true, only search currently registered systems."))
8555 (defgeneric resolve-dependency-combination (component combinator arguments)
8556 (:documentation "Return a component satisfying the dependency specification (COMBINATOR . ARGUMENTS)
8557 in the context of COMPONENT"))
8558
8559 ;; Methods for find-component
8560
8561 ;; If the base component is a string, resolve it as a system, then if not nil follow the path.
8562 (defmethod find-component ((base string) path &key registered)
8563 (if-let ((s (if registered
8564 (registered-system base)
8565 (find-system base nil))))
8566 (find-component s path :registered registered)))
8567
8568 ;; If the base component is a symbol, coerce it to a name if not nil, and resolve that.
8569 ;; If nil, use the path as base if not nil, or else return nil.
8570 (defmethod find-component ((base symbol) path &key registered)
8571 (cond
8572 (base (find-component (coerce-name base) path :registered registered))
8573 (path (find-component path nil :registered registered))
8574 (t nil)))
8575
8576 ;; If the base component is a cons cell, resolve its car, and add its cdr to the path.
8577 (defmethod find-component ((base cons) path &key registered)
8578 (find-component (car base) (cons (cdr base) path) :registered registered))
8579
8580 ;; If the base component is a parent-component and the path a string, find the named child.
8581 (defmethod find-component ((parent parent-component) (name string) &key registered)
8582 (declare (ignorable registered))
8583 (compute-children-by-name parent :only-if-needed-p t)
8584 (values (gethash name (component-children-by-name parent))))
8585
8586 ;; If the path is a symbol, coerce it to a name if non-nil, or else just return the base.
8587 (defmethod find-component (base (name symbol) &key registered)
8588 (if name
8589 (find-component base (coerce-name name) :registered registered)
8590 base))
8591
8592 ;; If the path is a cons, first resolve its car as path, then its cdr.
8593 (defmethod find-component ((c component) (name cons) &key registered)
8594 (find-component (find-component c (car name) :registered registered)
8595 (cdr name) :registered registered))
8596
8597 ;; If the path is a component, return it, disregarding the base.
8598 (defmethod find-component ((base t) (actual component) &key registered)
8599 (declare (ignorable registered))
8600 actual)
8601
8602 ;; Resolve dependency NAME in the context of a COMPONENT, with given optional VERSION constraint.
8603 ;; This (private) function is used below by RESOLVE-DEPENDENCY-SPEC and by the :VERSION spec.
8604 (defun resolve-dependency-name (component name &optional version)
8605 (loop
8606 (restart-case
8607 (return
8608 (let ((comp (find-component (component-parent component) name)))
8609 (unless comp
8610 (error 'missing-dependency
8611 :required-by component
8612 :requires name))
8613 (when version
8614 (unless (version-satisfies comp version)
8615 (error 'missing-dependency-of-version
8616 :required-by component
8617 :version version
8618 :requires name)))
8619 comp))
8620 (retry ()
8621 :report (lambda (s)
8622 (format s (compatfmt "~@<Retry loading ~3i~_~A.~@:>") name))
8623 :test
8624 (lambda (c)
8625 (or (null c)
8626 (and (typep c 'missing-dependency)
8627 (eq (missing-required-by c) component)
8628 (equal (missing-requires c) name))))
8629 (unless (component-parent component)
8630 (let ((name (coerce-name name)))
8631 (unset-asdf-cache-entry `(find-system ,name))
8632 (unset-asdf-cache-entry `(locate-system ,name))))))))
8633
8634 ;; Resolve dependency specification DEP-SPEC in the context of COMPONENT.
8635 ;; This is notably used by MAP-DIRECT-DEPENDENCIES to process the results of COMPONENT-DEPENDS-ON
8636 ;; and by PARSE-DEFSYSTEM to process DEFSYSTEM-DEPENDS-ON.
8637 (defun resolve-dependency-spec (component dep-spec)
8638 (let ((component (find-component () component)))
8639 (if (atom dep-spec)
8640 (resolve-dependency-name component dep-spec)
8641 (resolve-dependency-combination component (car dep-spec) (cdr dep-spec)))))
8642
8643 ;; Methods for RESOLVE-DEPENDENCY-COMBINATION to parse lists as dependency specifications.
8644 (defmethod resolve-dependency-combination (component combinator arguments)
8645 (parameter-error (compatfmt "~@<In ~S, bad dependency ~S for ~S~@:>")
8646 'resolve-dependency-combination (cons combinator arguments) component))
8647
8648 (defmethod resolve-dependency-combination (component (combinator (eql :feature)) arguments)
8649 (when (featurep (first arguments))
8650 (resolve-dependency-spec component (second arguments))))
8651
8652 (defmethod resolve-dependency-combination (component (combinator (eql :version)) arguments)
8653 (resolve-dependency-name component (first arguments) (second arguments)))) ;; See lp#527788
8654
8655 ;;;; -------------------------------------------------------------------------
8656 ;;;; Operations
8657
8658 (uiop/package:define-package :asdf/operation
8659 (:recycle :asdf/operation :asdf/action :asdf) ;; asdf/action for FEATURE pre 2.31.5.
8660 (:use :uiop/common-lisp :uiop :asdf/upgrade :asdf/find-system)
8661 (:export
8662 #:operation
8663 #:operation-original-initargs #:original-initargs ;; backward-compatibility only. DO NOT USE.
8664 #:*operations* #:make-operation #:find-operation
8665 #:feature)) ;; TODO: stop exporting the deprecated FEATURE feature.
8666 (in-package :asdf/operation)
8667
8668 ;;; Operation Classes
8669
8670 (when-upgrading (:when (find-class 'operation nil))
8671 ;; override any obsolete shared-initialize method when upgrading from ASDF2.
8672 (defmethod shared-initialize :after ((o operation) (slot-names t) &key)
8673 (values)))
8674
8675 (with-upgradability ()
8676 (defclass operation ()
8677 ((original-initargs ;; for backward-compat -- used by GBBopen, and swank (via operation-forced)
8678 :initform nil :initarg :original-initargs :accessor operation-original-initargs))
8679 (:documentation "The base class for all ASDF operations.
8680
8681 ASDF does NOT, never did and never will distinguish between multiple operations of the same class.
8682 Therefore, all slots of all operations must have (:allocation class) and no initargs.
8683
8684 Any exceptions currently maintained for backward-compatibility are deprecated,
8685 and support for them may be discontinued at any moment.
8686 "))
8687
8688 ;; Cache a copy of the INITARGS in the ORIGINAL-INITARGS slot, if that slot is not already bound.
8689 ;; This is a deprecated feature temporarily maintained for backward compatibility.
8690 ;; It will be removed at some point in the future.
8691 (defmethod initialize-instance :after ((o operation) &rest initargs
8692 &key force force-not system verbose &allow-other-keys)
8693 (declare (ignore force force-not system verbose))
8694 (unless (slot-boundp o 'original-initargs)
8695 (setf (operation-original-initargs o) initargs)))
8696
8697 (defmethod print-object ((o operation) stream)
8698 (print-unreadable-object (o stream :type t :identity nil)
8699 (ignore-errors
8700 (format stream "~{~S~^ ~}" (operation-original-initargs o))))))
8701
8702 ;;; make-operation, find-operation
8703
8704 (with-upgradability ()
8705 ;; A table to memoize instances of a given operation. There shall be only one.
8706 (defparameter* *operations* (make-hash-table :test 'equal))
8707
8708 ;; A memoizing way of creating instances of operation.
8709 (defun make-operation (operation-class &rest initargs)
8710 "This function creates and memoizes an instance of OPERATION-CLASS.
8711 All operation instances MUST be created through this function.
8712
8713 Use of INITARGS is for backward compatibility and may be discontinued at any time."
8714 (let ((class (coerce-class operation-class
8715 :package :asdf/interface :super 'operation :error 'sysdef-error)))
8716 (ensure-gethash (cons class initargs) *operations*
8717 (list* 'make-instance class initargs))))
8718
8719 ;; We preserve the operation-original-initargs of the context,
8720 ;; but only as an unsupported feature.
8721 ;; This is all done purely for the temporary sake of backwards compatibility.
8722 (defgeneric find-operation (context spec)
8723 (:documentation "Find an operation by resolving the SPEC in the CONTEXT"))
8724 (defmethod find-operation ((context t) (spec operation))
8725 spec)
8726 (defmethod find-operation (context (spec symbol))
8727 (when spec ;; NIL designates itself, i.e. absence of operation
8728 (apply 'make-operation spec (operation-original-initargs context))))
8729 (defmethod find-operation (context (spec string))
8730 (apply 'make-operation spec (operation-original-initargs context)))
8731 (defmethod operation-original-initargs ((context symbol))
8732 (declare (ignorable context))
8733 nil))
8734
8735 ;;;; -------------------------------------------------------------------------
8736 ;;;; Actions
8737
8738 (uiop/package:define-package :asdf/action
8739 (:nicknames :asdf-action)
8740 (:recycle :asdf/action :asdf)
8741 (:use :uiop/common-lisp :uiop :asdf/upgrade
8742 :asdf/component :asdf/system #:asdf/cache :asdf/find-system :asdf/find-component :asdf/operation)
8743 (:export
8744 #:action #:define-convenience-action-methods
8745 #:explain #:action-description
8746 #:downward-operation #:upward-operation #:sideway-operation #:selfward-operation #:non-propagating-operation
8747 #:component-depends-on
8748 #:input-files #:output-files #:output-file #:operation-done-p
8749 #:action-status #:action-stamp #:action-done-p
8750 #:component-operation-time #:mark-operation-done #:compute-action-stamp
8751 #:perform #:perform-with-restarts #:retry #:accept
8752 #:traverse-actions #:traverse-sub-actions #:required-components ;; in plan
8753 #:action-path #:find-action #:stamp #:done-p
8754 #:operation-definition-warning #:operation-definition-error ;; condition
8755 ))
8756 (in-package :asdf/action)
8757
8758 (eval-when (#-lispworks :compile-toplevel :load-toplevel :execute) ;; LispWorks issues spurious warning
8759
8760 (deftype action ()
8761 "A pair of operation and component uniquely identifies a node in the dependency graph
8762 of steps to be performed while building a system."
8763 '(cons operation component))
8764
8765 (deftype operation-designator ()
8766 "An operation designates itself. NIL designates a context-dependent current operation,
8767 and a class-name or class designates the canonical instance of the designated class."
8768 '(or operation null symbol class)))
8769
8770
8771 ;;; TODO: These should be moved to asdf/plan and be made simple defuns.
8772 (with-upgradability ()
8773 (defgeneric traverse-actions (actions &key &allow-other-keys))
8774 (defgeneric traverse-sub-actions (operation component &key &allow-other-keys))
8775 (defgeneric required-components (component &key &allow-other-keys)))
8776
8777
8778 ;;;; Reified representation for storage or debugging. Note: it drops the operation-original-initargs
8779 (with-upgradability ()
8780 (defun action-path (action)
8781 "A readable data structure that identifies the action."
8782 (destructuring-bind (o . c) action (cons (type-of o) (component-find-path c))))
8783 (defun find-action (path)
8784 "Reconstitute an action from its action-path"
8785 (destructuring-bind (o . c) path (cons (make-operation o) (find-component () c)))))
8786
8787
8788 ;;;; Convenience methods
8789 (with-upgradability ()
8790 ;; A macro that defines convenience methods for a generic function (gf) that
8791 ;; dispatches on operation and component. The convenience methods allow users
8792 ;; to call the gf with operation and/or component designators, that the
8793 ;; methods will resolve into actual operation and component objects, so that
8794 ;; the users can interact using readable designators, but developers only have
8795 ;; to write methods that handle operation and component objects.
8796 ;; FUNCTION is the generic function name
8797 ;; FORMALS is its list of arguments, which must include OPERATION and COMPONENT.
8798 ;; IF-NO-OPERATION is a form (defaults to NIL) describing what to do if no operation is found.
8799 ;; IF-NO-COMPONENT is a form (defaults to NIL) describing what to do if no component is found.
8800 ;; If OPERATION-INITARGS is true, then for backward compatibility the function has
8801 ;; a &rest argument that is passed into the operation's initargs if and when it is created.
8802 (defmacro define-convenience-action-methods
8803 (function formals &key if-no-operation if-no-component operation-initargs)
8804 (let* ((rest (gensym "REST"))
8805 (found (gensym "FOUND"))
8806 (keyp (equal (last formals) '(&key)))
8807 (formals-no-key (if keyp (butlast formals) formals))
8808 (len (length formals-no-key))
8809 (operation 'operation)
8810 (component 'component)
8811 (opix (position operation formals))
8812 (coix (position component formals))
8813 (prefix (subseq formals 0 opix))
8814 (suffix (subseq formals (1+ coix) len))
8815 (more-args (when keyp `(&rest ,rest &key &allow-other-keys))))
8816 (assert (and (integerp opix) (integerp coix) (= coix (1+ opix))))
8817 (flet ((next-method (o c)
8818 (if keyp
8819 `(apply ',function ,@prefix ,o ,c ,@suffix ,rest)
8820 `(,function ,@prefix ,o ,c ,@suffix))))
8821 `(progn
8822 (defmethod ,function (,@prefix (,operation string) ,component ,@suffix ,@more-args)
8823 (let ((,component (find-component () ,component))) ;; do it first, for defsystem-depends-on
8824 ,(next-method `(safe-read-from-string ,operation :package :asdf/interface) component)))
8825 (defmethod ,function (,@prefix (,operation symbol) ,component ,@suffix ,@more-args)
8826 (if ,operation
8827 ,(next-method
8828 (if operation-initargs ;backward-compatibility with ASDF1's operate. Yuck.
8829 `(apply 'make-operation ,operation :original-initargs ,rest ,rest)
8830 `(make-operation ,operation))
8831 `(or (find-component () ,component) ,if-no-component))
8832 ,if-no-operation))
8833 (defmethod ,function (,@prefix (,operation operation) ,component ,@suffix ,@more-args)
8834 (if (typep ,component 'component)
8835 (error "No defined method for ~S on ~/asdf-action:format-action/"
8836 ',function (cons ,operation ,component))
8837 (if-let (,found (find-component () ,component))
8838 ,(next-method operation found)
8839 ,if-no-component))))))))
8840
8841
8842 ;;;; self-description
8843 (with-upgradability ()
8844 (defgeneric action-description (operation component)
8845 (:documentation "returns a phrase that describes performing this operation
8846 on this component, e.g. \"loading /a/b/c\".
8847 You can put together sentences using this phrase."))
8848 (defmethod action-description (operation component)
8849 (format nil (compatfmt "~@<~A on ~A~@:>")
8850 (type-of operation) component))
8851
8852 ;; This is for compatibility with ASDF 1, and is deprecated.
8853 ;; TODO: move it to backward-interface
8854 (defgeneric* (explain) (operation component)
8855 (:documentation "Display a message describing an action"))
8856 (defmethod explain ((o operation) (c component))
8857 (asdf-message (compatfmt "~&~@<; ~@;~A~:>~%") (action-description o c)))
8858 (define-convenience-action-methods explain (operation component))
8859
8860 (defun format-action (stream action &optional colon-p at-sign-p)
8861 "FORMAT helper to display an action's action-description.
8862 Use it in FORMAT control strings as ~/asdf-action:format-action/"
8863 (assert (null colon-p)) (assert (null at-sign-p))
8864 (destructuring-bind (operation . component) action
8865 (princ (action-description operation component) stream))))
8866
8867
8868 ;;;; Dependencies
8869 (with-upgradability ()
8870 (defgeneric* (component-depends-on) (operation component) ;; ASDF4: rename to component-dependencies
8871 (:documentation
8872 "Returns a list of dependencies needed by the component to perform
8873 the operation. A dependency has one of the following forms:
8874
8875 (<operation> <component>*), where <operation> is an operation designator
8876 with respect to FIND-OPERATION in the context of the OPERATION argument,
8877 and each <component> is a component designator with respect to
8878 FIND-COMPONENT in the context of the COMPONENT argument,
8879 and means that the component depends on
8880 <operation> having been performed on each <component>;
8881
8882 [Note: an <operation> is an operation designator -- it can be either an
8883 operation name or an operation object. Similarly, a <component> may be
8884 a component name or a component object. Also note that, the degenerate
8885 case of (<operation>) is a no-op.]
8886
8887 Methods specialized on subclasses of existing component types
8888 should usually append the results of CALL-NEXT-METHOD to the list."))
8889 (define-convenience-action-methods component-depends-on (operation component))
8890
8891 (defmethod component-depends-on :around ((o operation) (c component))
8892 (do-asdf-cache `(component-depends-on ,o ,c)
8893 (call-next-method))))
8894
8895
8896 ;;;; upward-operation, downward-operation, sideway-operation, selfward-operation
8897 ;; These together handle actions that propagate along the component hierarchy or operation universe.
8898 (with-upgradability ()
8899 (defclass downward-operation (operation)
8900 ((downward-operation
8901 :initform nil :reader downward-operation
8902 :type operation-designator :allocation :class))
8903 (:documentation "A DOWNWARD-OPERATION's dependencies propagate down the component hierarchy.
8904 I.e., if O is a DOWNWARD-OPERATION and its DOWNWARD-OPERATION slot designates operation D, then
8905 the action (O . M) of O on module M will depends on each of (D . C) for each child C of module M.
8906 The default value for slot DOWNWARD-OPERATION is NIL, which designates the operation O itself.
8907 E.g. in order for a MODULE to be loaded with LOAD-OP (resp. compiled with COMPILE-OP), all the
8908 children of the MODULE must have been loaded with LOAD-OP (resp. compiled with COMPILE-OP."))
8909 (defun downward-operation-depends-on (o c)
8910 `((,(or (downward-operation o) o) ,@(component-children c))))
8911 (defmethod component-depends-on ((o downward-operation) (c parent-component))
8912 `(,@(downward-operation-depends-on o c) ,@(call-next-method)))
8913
8914 (defclass upward-operation (operation)
8915 ((upward-operation
8916 :initform nil :reader upward-operation
8917 :type operation-designator :allocation :class))
8918 (:documentation "An UPWARD-OPERATION has dependencies that propagate up the component hierarchy.
8919 I.e., if O is an instance of UPWARD-OPERATION, and its UPWARD-OPERATION slot designates operation U,
8920 then the action (O . C) of O on a component C that has the parent P will depends on (U . P).
8921 The default value for slot UPWARD-OPERATION is NIL, which designates the operation O itself.
8922 E.g. in order for a COMPONENT to be prepared for loading or compiling with PREPARE-OP, its PARENT
8923 must first be prepared for loading or compiling with PREPARE-OP."))
8924 ;; For backward-compatibility reasons, a system inherits from module and is a child-component
8925 ;; so we must guard against this case. ASDF4: remove that.
8926 (defun upward-operation-depends-on (o c)
8927 (if-let (p (component-parent c)) `((,(or (upward-operation o) o) ,p))))
8928 (defmethod component-depends-on ((o upward-operation) (c child-component))
8929 `(,@(upward-operation-depends-on o c) ,@(call-next-method)))
8930
8931 (defclass sideway-operation (operation)
8932 ((sideway-operation
8933 :initform nil :reader sideway-operation
8934 :type operation-designator :allocation :class))
8935 (:documentation "A SIDEWAY-OPERATION has dependencies that propagate \"sideway\" to siblings
8936 that a component depends on. I.e. if O is a SIDEWAY-OPERATION, and its SIDEWAY-OPERATION slot
8937 designates operation S (where NIL designates O itself), then the action (O . C) of O on component C
8938 depends on each of (S . D) where D is a declared dependency of C.
8939 E.g. in order for a COMPONENT to be prepared for loading or compiling with PREPARE-OP,
8940 each of its declared dependencies must first be loaded as by LOAD-OP."))
8941 (defun sideway-operation-depends-on (o c)
8942 `((,(or (sideway-operation o) o) ,@(component-sideway-dependencies c))))
8943 (defmethod component-depends-on ((o sideway-operation) (c component))
8944 `(,@(sideway-operation-depends-on o c) ,@(call-next-method)))
8945
8946 (defclass selfward-operation (operation)
8947 ((selfward-operation
8948 ;; NB: no :initform -- if an operation depends on others, it must explicitly specify which
8949 :type (or operation-designator list) :reader selfward-operation :allocation :class))
8950 (:documentation "A SELFWARD-OPERATION depends on another operation on the same component.
8951 I.e., if O is a SELFWARD-OPERATION, and its SELFWARD-OPERATION designates a list of operations L,
8952 then the action (O . C) of O on component C depends on each (S . C) for S in L.
8953 E.g. before a component may be loaded by LOAD-OP, it must have been compiled by COMPILE-OP.
8954 A operation-designator designates a singleton list of the designated operation;
8955 a list of operation-designators designates the list of designated operations;
8956 NIL is not a valid operation designator in that context. Note that any dependency
8957 ordering between the operations in a list of SELFWARD-OPERATION should be specified separately
8958 in the respective operation's COMPONENT-DEPENDS-ON methods so that they be scheduled properly."))
8959 (defun selfward-operation-depends-on (o c)
8960 (loop :for op :in (ensure-list (selfward-operation o)) :collect `(,op ,c)))
8961 (defmethod component-depends-on ((o selfward-operation) (c component))
8962 `(,@(selfward-operation-depends-on o c) ,@(call-next-method)))
8963
8964 (defclass non-propagating-operation (operation)
8965 ()
8966 (:documentation "A NON-PROPAGATING-OPERATION is an operation that propagates
8967 no dependencies whatsoever. It is supplied in order that the programmer be able
8968 to specify that s/he is intentionally specifying an operation which invokes no
8969 dependencies.")))
8970
8971
8972 ;;;---------------------------------------------------------------------------
8973 ;;; Help programmers catch obsolete OPERATION subclasses
8974 ;;;---------------------------------------------------------------------------
8975 (with-upgradability ()
8976 (define-condition operation-definition-warning (simple-warning)
8977 ()
8978 (:documentation "Warning condition related to definition of obsolete OPERATION objects."))
8979
8980 (define-condition operation-definition-error (simple-error)
8981 ()
8982 (:documentation "Error condition related to definition of incorrect OPERATION objects."))
8983
8984 (defmethod initialize-instance :before ((o operation) &key)
8985 (unless (typep o '(or downward-operation upward-operation sideway-operation
8986 selfward-operation non-propagating-operation))
8987 (warn 'operation-definition-warning
8988 :format-control
8989 "No dependency propagating scheme specified for operation class ~S.
8990 The class needs to be updated for ASDF 3.1 and specify appropriate propagation mixins."
8991 :format-arguments (list (type-of o)))))
8992
8993 (defmethod initialize-instance :before ((o non-propagating-operation) &key)
8994 (when (typep o '(or downward-operation upward-operation sideway-operation selfward-operation))
8995 (error 'operation-definition-error
8996 :format-control
8997 "Inconsistent class: ~S
8998 NON-PROPAGATING-OPERATION is incompatible with propagating operation classes as superclasses."
8999 :format-arguments
9000 (list (type-of o)))))
9001
9002 (defmethod component-depends-on ((o operation) (c component))
9003 `(;; Normal behavior, to allow user-specified in-order-to dependencies
9004 ,@(cdr (assoc (type-of o) (component-in-order-to c)))
9005 ;; For backward-compatibility with ASDF2, any operation that doesn't specify propagation
9006 ;; or non-propagation through an appropriate mixin will be downward and sideway.
9007 ,@(unless (typep o '(or downward-operation upward-operation sideway-operation
9008 selfward-operation non-propagating-operation))
9009 `(,@(sideway-operation-depends-on o c)
9010 ,@(when (typep c 'parent-component) (downward-operation-depends-on o c))))))
9011
9012 (defmethod downward-operation ((o operation)) nil)
9013 (defmethod sideway-operation ((o operation)) nil))
9014
9015
9016 ;;;---------------------------------------------------------------------------
9017 ;;; End of OPERATION class checking
9018 ;;;---------------------------------------------------------------------------
9019
9020
9021 ;;;; Inputs, Outputs, and invisible dependencies
9022 (with-upgradability ()
9023 (defgeneric* (output-files) (operation component)
9024 (:documentation "Methods for this function return two values: a list of output files
9025 corresponding to this action, and a boolean indicating if they have already been subjected
9026 to relevant output translations and should not be further translated.
9027
9028 Methods on PERFORM *must* call this function to determine where their outputs are to be located.
9029 They may rely on the order of the files to discriminate between outputs.
9030 "))
9031 (defgeneric* (input-files) (operation component)
9032 (:documentation "A list of input files corresponding to this action.
9033
9034 Methods on PERFORM *must* call this function to determine where their inputs are located.
9035 They may rely on the order of the files to discriminate between inputs.
9036 "))
9037 (defgeneric* (operation-done-p) (operation component)
9038 (:documentation "Returns a boolean which is NIL if the action must be performed (again)."))
9039 (define-convenience-action-methods output-files (operation component))
9040 (define-convenience-action-methods input-files (operation component))
9041 (define-convenience-action-methods operation-done-p (operation component))
9042
9043 (defmethod operation-done-p ((o operation) (c component))
9044 t)
9045
9046 ;; Translate output files, unless asked not to. Memoize the result.
9047 (defmethod output-files :around (operation component)
9048 operation component ;; hush genera, not convinced by declare ignorable(!)
9049 (do-asdf-cache `(output-files ,operation ,component)
9050 (values
9051 (multiple-value-bind (pathnames fixedp) (call-next-method)
9052 ;; 1- Make sure we have absolute pathnames
9053 (let* ((directory (pathname-directory-pathname
9054 (component-pathname (find-component () component))))
9055 (absolute-pathnames
9056 (loop
9057 :for pathname :in pathnames
9058 :collect (ensure-absolute-pathname pathname directory))))
9059 ;; 2- Translate those pathnames as required
9060 (if fixedp
9061 absolute-pathnames
9062 (mapcar *output-translation-function* absolute-pathnames))))
9063 t)))
9064 (defmethod output-files ((o operation) (c component))
9065 nil)
9066 (defun output-file (operation component)
9067 "The unique output file of performing OPERATION on COMPONENT"
9068 (let ((files (output-files operation component)))
9069 (assert (length=n-p files 1))
9070 (first files)))
9071
9072 ;; Memoize input files.
9073 (defmethod input-files :around (operation component)
9074 (do-asdf-cache `(input-files ,operation ,component)
9075 (call-next-method)))
9076
9077 ;; By default an action has no input-files.
9078 (defmethod input-files ((o operation) (c component))
9079 nil)
9080
9081 ;; An action with a selfward-operation by default gets its input-files from the output-files of
9082 ;; the actions using selfward-operations it depends on (and the same component),
9083 ;; or if there are none, on the component-pathname of the component if it's a file
9084 ;; -- and then on the results of the next-method.
9085 (defmethod input-files ((o selfward-operation) (c component))
9086 `(,@(or (loop :for dep-o :in (ensure-list (selfward-operation o))
9087 :append (or (output-files dep-o c) (input-files dep-o c)))
9088 (if-let ((pathname (component-pathname c)))
9089 (and (file-pathname-p pathname) (list pathname))))
9090 ,@(call-next-method))))
9091
9092
9093 ;;;; Done performing
9094 (with-upgradability ()
9095 ;; ASDF4: hide it behind plan-action-stamp
9096 (defgeneric component-operation-time (operation component)
9097 (:documentation "Return the timestamp for when an action was last performed"))
9098 (defgeneric (setf component-operation-time) (time operation component)
9099 (:documentation "Update the timestamp for when an action was last performed"))
9100 (define-convenience-action-methods component-operation-time (operation component))
9101
9102 ;; ASDF4: hide it behind (setf plan-action-stamp)
9103 (defgeneric mark-operation-done (operation component)
9104 (:documentation "Mark a action as having been just done.
9105
9106 Updates the action's COMPONENT-OPERATION-TIME to match the COMPUTE-ACTION-STAMP
9107 using the JUST-DONE flag."))
9108 (defgeneric compute-action-stamp (plan operation component &key just-done)
9109 (:documentation "Has this action been successfully done already,
9110 and at what known timestamp has it been done at or will it be done at?
9111 * PLAN is a plan object modelling future effects of actions,
9112 or NIL to denote what actually happened.
9113 * OPERATION and COMPONENT denote the action.
9114 Takes keyword JUST-DONE:
9115 * JUST-DONE is a boolean that is true if the action was just successfully performed,
9116 at which point we want compute the actual stamp and warn if files are missing;
9117 otherwise we are making plans, anticipating the effects of the action.
9118 Returns two values:
9119 * a STAMP saying when it was done or will be done,
9120 or T if the action involves files that need to be recomputed.
9121 * a boolean DONE-P that indicates whether the action has actually been done,
9122 and both its output-files and its in-image side-effects are up to date."))
9123
9124 (defclass action-status ()
9125 ((stamp
9126 :initarg :stamp :reader action-stamp
9127 :documentation "STAMP associated with the ACTION if it has been completed already
9128 in some previous image, or T if it needs to be done.")
9129 (done-p
9130 :initarg :done-p :reader action-done-p
9131 :documentation "a boolean, true iff the action was already done (before any planned action)."))
9132 (:documentation "Status of an action"))
9133
9134 (defmethod print-object ((status action-status) stream)
9135 (print-unreadable-object (status stream :type t)
9136 (with-slots (stamp done-p) status
9137 (format stream "~@{~S~^ ~}" :stamp stamp :done-p done-p))))
9138
9139 (defmethod component-operation-time ((o operation) (c component))
9140 (gethash (type-of o) (component-operation-times c)))
9141
9142 (defmethod (setf component-operation-time) (stamp (o operation) (c component))
9143 (setf (gethash (type-of o) (component-operation-times c)) stamp))
9144
9145 (defmethod mark-operation-done ((o operation) (c component))
9146 (setf (component-operation-time o c) (compute-action-stamp nil o c :just-done t))))
9147
9148
9149 ;;;; Perform
9150 (with-upgradability ()
9151 (defgeneric* (perform) (operation component)
9152 (:documentation "PERFORM an action, consuming its input-files and building its output-files"))
9153 (define-convenience-action-methods perform (operation component))
9154
9155 (defmethod perform :before ((o operation) (c component))
9156 (ensure-all-directories-exist (output-files o c)))
9157 (defmethod perform :after ((o operation) (c component))
9158 (mark-operation-done o c))
9159 (defmethod perform ((o operation) (c parent-component))
9160 nil)
9161 (defmethod perform ((o operation) (c source-file))
9162 ;; For backward compatibility, don't error on operations that don't specify propagation.
9163 (when (typep o '(or downward-operation upward-operation sideway-operation
9164 selfward-operation non-propagating-operation))
9165 (sysdef-error
9166 (compatfmt "~@<Required method ~S not implemented for ~/asdf-action:format-action/~@:>")
9167 'perform (cons o c))))
9168
9169 ;; The restarts of the perform-with-restarts variant matter in an interactive context.
9170 ;; The retry strategies of p-w-r itself, and/or the background workers of a multiprocess build
9171 ;; may call perform directly rather than call p-w-r.
9172 (defgeneric* (perform-with-restarts) (operation component)
9173 (:documentation "PERFORM an action in a context where suitable restarts are in place."))
9174 (defmethod perform-with-restarts (operation component)
9175 (perform operation component))
9176 (defmethod perform-with-restarts :around (operation component)
9177 (loop
9178 (restart-case
9179 (return (call-next-method))
9180 (retry ()
9181 :report
9182 (lambda (s)
9183 (format s (compatfmt "~@<Retry ~A.~@:>")
9184 (action-description operation component))))
9185 (accept ()
9186 :report
9187 (lambda (s)
9188 (format s (compatfmt "~@<Continue, treating ~A as having been successful.~@:>")
9189 (action-description operation component)))
9190 (mark-operation-done operation component)
9191 (return))))))
9192 ;;;; -------------------------------------------------------------------------
9193 ;;;; Actions to build Common Lisp software
9194
9195 (uiop/package:define-package :asdf/lisp-action
9196 (:recycle :asdf/lisp-action :asdf)
9197 (:intern #:proclamations #:flags)
9198 (:use :uiop/common-lisp :uiop :asdf/upgrade :asdf/cache
9199 :asdf/component :asdf/system :asdf/find-component :asdf/find-system
9200 :asdf/operation :asdf/action)
9201 (:export
9202 #:try-recompiling
9203 #:cl-source-file #:cl-source-file.cl #:cl-source-file.lsp
9204 #:basic-load-op #:basic-compile-op #:compile-op-flags #:compile-op-proclamations
9205 #:load-op #:prepare-op #:compile-op #:test-op #:load-source-op #:prepare-source-op
9206 #:call-with-around-compile-hook
9207 #:perform-lisp-compilation #:perform-lisp-load-fasl #:perform-lisp-load-source
9208 #:lisp-compilation-output-files #:flags))
9209 (in-package :asdf/lisp-action)
9210
9211
9212 ;;;; Component classes
9213 (with-upgradability ()
9214 (defclass cl-source-file (source-file)
9215 ((type :initform "lisp"))
9216 (:documentation "Component class for a Common Lisp source file (using type \"lisp\")"))
9217 (defclass cl-source-file.cl (cl-source-file)
9218 ((type :initform "cl"))
9219 (:documentation "Component class for a Common Lisp source file using type \"cl\""))
9220 (defclass cl-source-file.lsp (cl-source-file)
9221 ((type :initform "lsp"))
9222 (:documentation "Component class for a Common Lisp source file using type \"lsp\"")))
9223
9224
9225 ;;;; Operation classes
9226 (with-upgradability ()
9227 (defclass basic-load-op (operation) ()
9228 (:documentation "Base class for operations that apply the load-time effects of a file"))
9229 (defclass basic-compile-op (operation)
9230 ;; NB: These slots are deprecated. They are for backward compatibility only,
9231 ;; and will be removed at some point in the future.
9232 ((proclamations :initarg :proclamations :accessor compile-op-proclamations :initform nil)
9233 (flags :initarg :flags :accessor compile-op-flags :initform nil))
9234 (:documentation "Base class for operations that apply the compile-time effects of a file")))
9235
9236
9237 ;;; Our default operations: loading into the current lisp image
9238 (with-upgradability ()
9239 (defclass prepare-op (upward-operation sideway-operation)
9240 ((sideway-operation :initform 'load-op :allocation :class))
9241 (:documentation "Load the dependencies for the COMPILE-OP or LOAD-OP of a given COMPONENT."))
9242 (defclass load-op (basic-load-op downward-operation selfward-operation)
9243 ;; NB: even though compile-op depends on prepare-op it is not needed-in-image-p,
9244 ;; so we need to directly depend on prepare-op for its side-effects in the current image.
9245 ((selfward-operation :initform '(prepare-op compile-op) :allocation :class))
9246 (:documentation "Operation for loading the compiled FASL for a Lisp file"))
9247 (defclass compile-op (basic-compile-op downward-operation selfward-operation)
9248 ((selfward-operation :initform 'prepare-op :allocation :class))
9249 (:documentation "Operation for compiling a Lisp file to a FASL"))
9250
9251
9252 (defclass prepare-source-op (upward-operation sideway-operation)
9253 ((sideway-operation :initform 'load-source-op :allocation :class))
9254 (:documentation "Operation for loading the dependencies of a Lisp file as source."))
9255 (defclass load-source-op (basic-load-op downward-operation selfward-operation)
9256 ((selfward-operation :initform 'prepare-source-op :allocation :class))
9257 (:documentation "Operation for loading a Lisp file as source."))
9258
9259 (defclass test-op (selfward-operation)
9260 ((selfward-operation :initform 'load-op :allocation :class))
9261 (:documentation "Operation for running the tests for system.
9262 If the tests fail, an error will be signaled.")))
9263
9264
9265 ;;;; Methods for prepare-op, compile-op and load-op
9266
9267 ;;; prepare-op
9268 (with-upgradability ()
9269 (defmethod action-description ((o prepare-op) (c component))
9270 (format nil (compatfmt "~@<loading dependencies of ~3i~_~A~@:>") c))
9271 (defmethod perform ((o prepare-op) (c component))
9272 nil)
9273 (defmethod input-files ((o prepare-op) (s system))
9274 (if-let (it (system-source-file s)) (list it))))
9275
9276 ;;; compile-op
9277 (with-upgradability ()
9278 (defmethod action-description ((o compile-op) (c component))
9279 (format nil (compatfmt "~@<compiling ~3i~_~A~@:>") c))
9280 (defmethod action-description ((o compile-op) (c parent-component))
9281 (format nil (compatfmt "~@<completing compilation for ~3i~_~A~@:>") c))
9282 (defgeneric call-with-around-compile-hook (component thunk)
9283 (:documentation "A method to be called around the PERFORM'ing of actions that apply the
9284 compile-time side-effects of file (i.e., COMPILE-OP or LOAD-SOURCE-OP). This method can be used
9285 to setup readtables and other variables that control reading, macroexpanding, and compiling, etc.
9286 Note that it will NOT be called around the performing of LOAD-OP."))
9287 (defmethod call-with-around-compile-hook ((c component) function)
9288 (call-around-hook (around-compile-hook c) function))
9289 (defun perform-lisp-compilation (o c)
9290 "Perform the compilation of the Lisp file associated to the specified action (O . C)."
9291 (let (;; Before 2.26.53, that was unfortunately component-pathname. Now,
9292 ;; we consult input-files, the first of which should be the one to compile-file
9293 (input-file (first (input-files o c)))
9294 ;; On some implementations, there are more than one output-file,
9295 ;; but the first one should always be the primary fasl that gets loaded.
9296 (outputs (output-files o c)))
9297 (multiple-value-bind (output warnings-p failure-p)
9298 (destructuring-bind
9299 (output-file
9300 &optional
9301 #+(or clasp ecl mkcl) object-file
9302 #+clisp lib-file
9303 warnings-file &rest rest) outputs
9304 ;; Allow for extra outputs that are not of type warnings-file
9305 ;; The way we do it is kludgy. In ASDF4, output-files shall not be positional.
9306 (declare (ignore rest))
9307 (when warnings-file
9308 (unless (equal (pathname-type warnings-file) (warnings-file-type))
9309 (setf warnings-file nil)))
9310 (call-with-around-compile-hook
9311 c #'(lambda (&rest flags)
9312 (apply 'compile-file* input-file
9313 :output-file output-file
9314 :external-format (component-external-format c)
9315 :warnings-file warnings-file
9316 (append
9317 #+clisp (list :lib-file lib-file)
9318 #+(or clasp ecl mkcl) (list :object-file object-file)
9319 flags (compile-op-flags o))))))
9320 (check-lisp-compile-results output warnings-p failure-p
9321 "~/asdf-action::format-action/" (list (cons o c))))))
9322 (defun report-file-p (f)
9323 "Is F a build report file containing, e.g., warnings to check?"
9324 (equalp (pathname-type f) "build-report"))
9325 (defun perform-lisp-warnings-check (o c)
9326 "Check the warnings associated with the dependencies of an action."
9327 (let* ((expected-warnings-files (remove-if-not #'warnings-file-p (input-files o c)))
9328 (actual-warnings-files (loop :for w :in expected-warnings-files
9329 :when (get-file-stamp w)
9330 :collect w
9331 :else :do (warn "Missing warnings file ~S while ~A"
9332 w (action-description o c)))))
9333 (check-deferred-warnings actual-warnings-files)
9334 (let* ((output (output-files o c))
9335 (report (find-if #'report-file-p output)))
9336 (when report
9337 (with-open-file (s report :direction :output :if-exists :supersede)
9338 (format s ":success~%"))))))
9339 (defmethod perform ((o compile-op) (c cl-source-file))
9340 (perform-lisp-compilation o c))
9341 (defun lisp-compilation-output-files (o c)
9342 "Compute the output-files for compiling the Lisp file for the specified action (O . C),
9343 an OPERATION and a COMPONENT."
9344 (let* ((i (first (input-files o c)))
9345 (f (compile-file-pathname
9346 i #+clasp :output-type #+ecl :type #+(or clasp ecl) :fasl
9347 #+mkcl :fasl-p #+mkcl t)))
9348 `(,f ;; the fasl is the primary output, in first position
9349 #+clasp
9350 ,@(unless nil ;; was (use-ecl-byte-compiler-p)
9351 `(,(compile-file-pathname i :output-type :object)))
9352 #+clisp
9353 ,@`(,(make-pathname :type "lib" :defaults f))
9354 #+ecl
9355 ,@(unless (use-ecl-byte-compiler-p)
9356 `(,(compile-file-pathname i :type :object)))
9357 #+mkcl
9358 ,(compile-file-pathname i :fasl-p nil) ;; object file
9359 ,@(when (and *warnings-file-type* (not (builtin-system-p (component-system c))))
9360 `(,(make-pathname :type *warnings-file-type* :defaults f))))))
9361 (defmethod output-files ((o compile-op) (c cl-source-file))
9362 (lisp-compilation-output-files o c))
9363 (defmethod perform ((o compile-op) (c static-file))
9364 nil)
9365
9366 ;; Performing compile-op on a system will check the deferred warnings for the system
9367 (defmethod perform ((o compile-op) (c system))
9368 (when (and *warnings-file-type* (not (builtin-system-p c)))
9369 (perform-lisp-warnings-check o c)))
9370 (defmethod input-files ((o compile-op) (c system))
9371 (when (and *warnings-file-type* (not (builtin-system-p c)))
9372 ;; The most correct way to do it would be to use:
9373 ;; (traverse-sub-actions o c :other-systems nil :keep-operation 'compile-op :keep-component 'cl-source-file)
9374 ;; but it's expensive and we don't care too much about file order or ASDF extensions.
9375 (loop :for sub :in (sub-components c :type 'cl-source-file)
9376 :nconc (remove-if-not 'warnings-file-p (output-files o sub)))))
9377 (defmethod output-files ((o compile-op) (c system))
9378 (when (and *warnings-file-type* (not (builtin-system-p c)))
9379 (if-let ((pathname (component-pathname c)))
9380 (list (subpathname pathname (coerce-filename c) :type "build-report"))))))
9381
9382 ;;; load-op
9383 (with-upgradability ()
9384 (defmethod action-description ((o load-op) (c cl-source-file))
9385 (format nil (compatfmt "~@<loading FASL for ~3i~_~A~@:>") c))
9386 (defmethod action-description ((o load-op) (c parent-component))
9387 (format nil (compatfmt "~@<completing load for ~3i~_~A~@:>") c))
9388 (defmethod action-description ((o load-op) (c component))
9389 (format nil (compatfmt "~@<loading ~3i~_~A~@:>") c))
9390 (defmethod perform-with-restarts ((o load-op) (c cl-source-file))
9391 (loop
9392 (restart-case
9393 (return (call-next-method))
9394 (try-recompiling ()
9395 :report (lambda (s)
9396 (format s "Recompile ~a and try loading it again"
9397 (component-name c)))
9398 (perform (find-operation o 'compile-op) c)))))
9399 (defun perform-lisp-load-fasl (o c)
9400 "Perform the loading of a FASL associated to specified action (O . C),
9401 an OPERATION and a COMPONENT."
9402 (if-let (fasl (first (input-files o c)))
9403 (load* fasl)))
9404 (defmethod perform ((o load-op) (c cl-source-file))
9405 (perform-lisp-load-fasl o c))
9406 (defmethod perform ((o load-op) (c static-file))
9407 nil))
9408
9409
9410 ;;;; prepare-source-op, load-source-op
9411
9412 ;;; prepare-source-op
9413 (with-upgradability ()
9414 (defmethod action-description ((o prepare-source-op) (c component))
9415 (format nil (compatfmt "~@<loading source for dependencies of ~3i~_~A~@:>") c))
9416 (defmethod input-files ((o prepare-source-op) (s system))
9417 (if-let (it (system-source-file s)) (list it)))
9418 (defmethod perform ((o prepare-source-op) (c component))
9419 nil))
9420
9421 ;;; load-source-op
9422 (with-upgradability ()
9423 (defmethod action-description ((o load-source-op) (c component))
9424 (format nil (compatfmt "~@<Loading source of ~3i~_~A~@:>") c))
9425 (defmethod action-description ((o load-source-op) (c parent-component))
9426 (format nil (compatfmt "~@<Loaded source of ~3i~_~A~@:>") c))
9427 (defun perform-lisp-load-source (o c)
9428 "Perform the loading of a Lisp file as associated to specified action (O . C)"
9429 (call-with-around-compile-hook
9430 c #'(lambda ()
9431 (load* (first (input-files o c))
9432 :external-format (component-external-format c)))))
9433
9434 (defmethod perform ((o load-source-op) (c cl-source-file))
9435 (perform-lisp-load-source o c))
9436 (defmethod perform ((o load-source-op) (c static-file))
9437 nil))
9438
9439
9440 ;;;; test-op
9441 (with-upgradability ()
9442 (defmethod perform ((o test-op) (c component))
9443 nil)
9444 (defmethod operation-done-p ((o test-op) (c system))
9445 "Testing a system is _never_ done."
9446 nil))
9447 ;;;; -------------------------------------------------------------------------
9448 ;;;; Plan
9449
9450 (uiop/package:define-package :asdf/plan
9451 (:recycle :asdf/plan :asdf)
9452 (:use :uiop/common-lisp :uiop :asdf/upgrade
9453 :asdf/component :asdf/operation :asdf/system
9454 :asdf/cache :asdf/find-system :asdf/find-component
9455 :asdf/operation :asdf/action :asdf/lisp-action)
9456 (:export
9457 #:component-operation-time
9458 #:plan #:plan-traversal #:sequential-plan #:*default-plan-class*
9459 #:planned-action-status #:plan-action-status #:action-already-done-p
9460 #:circular-dependency #:circular-dependency-actions
9461 #:node-for #:needed-in-image-p
9462 #:action-index #:action-planned-p #:action-valid-p
9463 #:plan-record-dependency
9464 #:normalize-forced-systems #:action-forced-p #:action-forced-not-p
9465 #:map-direct-dependencies #:reduce-direct-dependencies #:direct-dependencies
9466 #:compute-action-stamp #:traverse-action
9467 #:circular-dependency #:circular-dependency-actions
9468 #:call-while-visiting-action #:while-visiting-action
9469 #:make-plan #:plan-actions #:perform-plan #:plan-operates-on-p
9470 #:planned-p #:index #:forced #:forced-not #:total-action-count
9471 #:planned-action-count #:planned-output-action-count #:visited-actions
9472 #:visiting-action-set #:visiting-action-list #:plan-actions-r
9473 #:required-components #:filtered-sequential-plan
9474 #:plan-system
9475 #:plan-action-filter #:plan-component-type #:plan-keep-operation #:plan-keep-component
9476 #:traverse-actions #:traverse-sub-actions))
9477 (in-package :asdf/plan)
9478
9479 ;;;; Generic plan traversal class
9480 (with-upgradability ()
9481 (defclass plan () ()
9482 (:documentation "Base class for a plan based on which ASDF can build a system"))
9483 (defclass plan-traversal (plan)
9484 (;; The system for which the plan is computed
9485 (system :initform nil :initarg :system :accessor plan-system)
9486 ;; Table of systems specified via :force arguments
9487 (forced :initform nil :initarg :force :accessor plan-forced)
9488 ;; Table of systems specified via :force-not argument (and/or immutable)
9489 (forced-not :initform nil :initarg :force-not :accessor plan-forced-not)
9490 ;; Counts of total actions in plan
9491 (total-action-count :initform 0 :accessor plan-total-action-count)
9492 ;; Count of actions that need to be performed
9493 (planned-action-count :initform 0 :accessor plan-planned-action-count)
9494 ;; Count of actions that need to be performed that have a non-empty list of output-files.
9495 (planned-output-action-count :initform 0 :accessor plan-planned-output-action-count)
9496 ;; Table that to actions already visited while walking the dependencies associates status
9497 (visited-actions :initform (make-hash-table :test 'equal) :accessor plan-visited-actions)
9498 ;; Actions that depend on those being currently walked through, to detect circularities
9499 (visiting-action-set ;; as a set
9500 :initform (make-hash-table :test 'equal) :accessor plan-visiting-action-set)
9501 (visiting-action-list :initform () :accessor plan-visiting-action-list)) ;; as a list
9502 (:documentation "Base class for plans that simply traverse dependencies")))
9503
9504
9505 ;;;; Planned action status
9506 (with-upgradability ()
9507 (defgeneric plan-action-status (plan operation component)
9508 (:documentation "Returns the ACTION-STATUS associated to
9509 the action of OPERATION on COMPONENT in the PLAN"))
9510
9511 (defgeneric (setf plan-action-status) (new-status plan operation component)
9512 (:documentation "Sets the ACTION-STATUS associated to
9513 the action of OPERATION on COMPONENT in the PLAN"))
9514
9515 (defclass planned-action-status (action-status)
9516 ((planned-p
9517 :initarg :planned-p :reader action-planned-p
9518 :documentation "a boolean, true iff the action was included in the plan.")
9519 (index
9520 :initarg :index :reader action-index
9521 :documentation "an integer, counting all traversed actions in traversal order."))
9522 (:documentation "Status of an action in a plan"))
9523
9524 (defmethod print-object ((status planned-action-status) stream)
9525 (print-unreadable-object (status stream :type t :identity nil)
9526 (with-slots (stamp done-p planned-p index) status
9527 (format stream "~@{~S~^ ~}" :stamp stamp :done-p done-p :planned-p planned-p :index index))))
9528
9529 (defmethod action-planned-p ((action-status t))
9530 t) ; default method for non planned-action-status objects
9531
9532 ;; TODO: either confirm there are no operation-original-initargs, eliminate NODE-FOR,
9533 ;; and use (CONS O C); or keep the operation initargs, and here use MAKE-OPERATION.
9534 ;; However, see also component-operation-time and mark-operation-done
9535 (defun node-for (o c)
9536 "Given operation O and component C, return an object to use as key in action-indexed tables."
9537 (cons (type-of o) c))
9538
9539 (defun action-already-done-p (plan operation component)
9540 "According to this plan, is this action already done and up to date?"
9541 (action-done-p (plan-action-status plan operation component)))
9542
9543 (defmethod plan-action-status ((plan null) (o operation) (c component))
9544 (multiple-value-bind (stamp done-p) (component-operation-time o c)
9545 (make-instance 'action-status :stamp stamp :done-p done-p)))
9546
9547 (defmethod (setf plan-action-status) (new-status (plan null) (o operation) (c component))
9548 (let ((to (type-of o))
9549 (times (component-operation-times c)))
9550 (if (action-done-p new-status)
9551 (remhash to times)
9552 (setf (gethash to times) (action-stamp new-status))))
9553 new-status))
9554
9555
9556 ;;;; forcing
9557 (with-upgradability ()
9558 (defgeneric action-forced-p (plan operation component)
9559 (:documentation "Is this action forced to happen in this plan?"))
9560 (defgeneric action-forced-not-p (plan operation component)
9561 (:documentation "Is this action forced to not happen in this plan?
9562 Takes precedence over action-forced-p."))
9563
9564 (defun normalize-forced-systems (force system)
9565 "Given a SYSTEM on which operate is called and the specified FORCE argument,
9566 extract a hash-set of systems that are forced, or a predicate on system names,
9567 or NIL if none are forced, or :ALL if all are."
9568 (etypecase force
9569 ((or (member nil :all) hash-table function) force)
9570 (cons (list-to-hash-set (mapcar #'coerce-name force)))
9571 ((eql t) (when system (list-to-hash-set (list (coerce-name system)))))))
9572
9573 (defun normalize-forced-not-systems (force-not system)
9574 "Given a SYSTEM on which operate is called, the specified FORCE-NOT argument,
9575 and the set of IMMUTABLE systems, extract a hash-set of systems that are effectively forced-not,
9576 or predicate on system names, or NIL if none are forced, or :ALL if all are."
9577 (let ((requested
9578 (etypecase force-not
9579 ((or (member nil :all) hash-table function) force-not)
9580 (cons (list-to-hash-set (mapcar #'coerce-name force-not)))
9581 ((eql t) (if system (let ((name (coerce-name system)))
9582 #'(lambda (x) (not (equal x name))))
9583 :all)))))
9584 (if (and *immutable-systems* requested)
9585 #'(lambda (x) (or (call-function requested x)
9586 (call-function *immutable-systems* x)))
9587 (or *immutable-systems* requested))))
9588
9589 ;; TODO: shouldn't we be looking up the primary system name, rather than the system name?
9590 (defun action-override-p (plan operation component override-accessor)
9591 "Given a plan, an action, and a function that given the plan accesses a set of overrides
9592 (i.e. force or force-not), see if the override applies to the current action."
9593 (declare (ignore operation))
9594 (call-function (funcall override-accessor plan)
9595 (coerce-name (component-system (find-component () component)))))
9596
9597 (defmethod action-forced-p (plan operation component)
9598 (and
9599 ;; Did the user ask us to re-perform the action?
9600 (action-override-p plan operation component 'plan-forced)
9601 ;; You really can't force a builtin system and :all doesn't apply to it,
9602 ;; except if it's the specifically the system currently being built.
9603 (not (let ((system (component-system component)))
9604 (and (builtin-system-p system)
9605 (not (eq system (plan-system plan))))))))
9606
9607 (defmethod action-forced-not-p (plan operation component)
9608 ;; Did the user ask us to not re-perform the action?
9609 ;; NB: force-not takes precedence over force, as it should
9610 (action-override-p plan operation component 'plan-forced-not))
9611
9612 (defmethod action-forced-p ((plan null) (operation operation) (component component))
9613 nil)
9614
9615 (defmethod action-forced-not-p ((plan null) (operation operation) (component component))
9616 nil))
9617
9618
9619 ;;;; action-valid-p
9620 (with-upgradability ()
9621 (defun action-valid-p (operation component)
9622 "Is this action valid to include amongst dependencies?"
9623 ;; If either the operation or component was resolved to nil, the action is invalid.
9624 ;; :if-feature will invalidate actions on components for which the features don't apply.
9625 (and operation component
9626 (if-let (it (component-if-feature component)) (featurep it) t))))
9627
9628 ;;;; Is the action needed in this image?
9629 (with-upgradability ()
9630 (defgeneric needed-in-image-p (operation component)
9631 (:documentation "Is the action of OPERATION on COMPONENT needed in the current image
9632 to be meaningful, or could it just as well have been done in another Lisp image?"))
9633
9634 (defmethod needed-in-image-p ((o operation) (c component))
9635 ;; We presume that actions that modify the filesystem don't need be run
9636 ;; in the current image if they have already been done in another,
9637 ;; and can be run in another process (e.g. a fork),
9638 ;; whereas those that don't are meant to side-effect the current image and can't.
9639 (not (output-files o c))))
9640
9641
9642 ;;;; Visiting dependencies of an action and computing action stamps
9643 (with-upgradability ()
9644 (defun (map-direct-dependencies) (plan operation component fun)
9645 "Call FUN on all the valid dependencies of the given action in the given plan"
9646 (declare (ignore plan))
9647 (loop* :for (dep-o-spec . dep-c-specs) :in (component-depends-on operation component)
9648 :for dep-o = (find-operation operation dep-o-spec)
9649 :when dep-o
9650 :do (loop :for dep-c-spec :in dep-c-specs
9651 :for dep-c = (and dep-c-spec (resolve-dependency-spec component dep-c-spec))
9652 :when (action-valid-p dep-o dep-c)
9653 :do (funcall fun dep-o dep-c))))
9654
9655 (defun (reduce-direct-dependencies) (plan operation component combinator seed)
9656 "Reduce the direct dependencies to a value computed by iteratively calling COMBINATOR
9657 for each dependency action on the dependency's operation and component and an accumulator
9658 initialized with SEED."
9659 (map-direct-dependencies
9660 plan operation component
9661 #'(lambda (dep-o dep-c)
9662 (setf seed (funcall combinator dep-o dep-c seed))))
9663 seed)
9664
9665 (defun (direct-dependencies) (plan operation component)
9666 "Compute a list of the direct dependencies of the action within the plan"
9667 (reduce-direct-dependencies plan operation component #'acons nil))
9668
9669 ;; In a distant future, get-file-stamp, component-operation-time and latest-stamp
9670 ;; shall also be parametrized by the plan, or by a second model object,
9671 ;; so they need not refer to the state of the filesystem,
9672 ;; and the stamps could be cryptographic checksums rather than timestamps.
9673 ;; Such a change remarkably would only affect COMPUTE-ACTION-STAMP.
9674
9675 (defmethod compute-action-stamp (plan (o operation) (c component) &key just-done)
9676 ;; Given an action, figure out at what time in the past it has been done,
9677 ;; or if it has just been done, return the time that it has.
9678 ;; Returns two values:
9679 ;; 1- the TIMESTAMP of the action if it has already been done and is up to date,
9680 ;; or T is either hasn't been done or is out of date.
9681 ;; 2- the DONE-IN-IMAGE-P boolean flag that is T if the action has already been done
9682 ;; in the current image, or NIL if it hasn't.
9683 ;; Note that if e.g. LOAD-OP only depends on up-to-date files, but
9684 ;; hasn't been done in the current image yet, then it can have a non-T timestamp,
9685 ;; yet a NIL done-in-image-p flag: we can predict what timestamp it will have once loaded,
9686 ;; i.e. that of the input-files.
9687 (nest
9688 (block ())
9689 (let ((dep-stamp ; collect timestamp from dependencies (or T if forced or out-of-date)
9690 (reduce-direct-dependencies
9691 plan o c
9692 #'(lambda (o c stamp)
9693 (if-let (it (plan-action-status plan o c))
9694 (latest-stamp stamp (action-stamp it))
9695 t))
9696 nil)))
9697 ;; out-of-date dependency: don't bother expensively querying the filesystem
9698 (when (and (eq dep-stamp t) (not just-done)) (return (values t nil))))
9699 ;; collect timestamps from inputs, and exit early if any is missing
9700 (let* ((in-files (input-files o c))
9701 (in-stamps (mapcar #'get-file-stamp in-files))
9702 (missing-in (loop :for f :in in-files :for s :in in-stamps :unless s :collect f))
9703 (latest-in (stamps-latest (cons dep-stamp in-stamps))))
9704 (when (and missing-in (not just-done)) (return (values t nil))))
9705 ;; collect timestamps from outputs, and exit early if any is missing
9706 (let* ((out-files (remove-if 'null (output-files o c)))
9707 (out-stamps (mapcar (if just-done 'register-file-stamp 'get-file-stamp) out-files))
9708 (missing-out (loop :for f :in out-files :for s :in out-stamps :unless s :collect f))
9709 (earliest-out (stamps-earliest out-stamps)))
9710 (when (and missing-out (not just-done)) (return (values t nil))))
9711 (let* (;; There are three kinds of actions:
9712 (out-op (and out-files t)) ; those that create files on the filesystem
9713 ;;(image-op (and in-files (null out-files))) ; those that load stuff into the image
9714 ;;(null-op (and (null out-files) (null in-files))) ; placeholders that do nothing
9715 ;; When was the thing last actually done? (Now, or ask.)
9716 (op-time (or just-done (component-operation-time o c)))
9717 ;; Time stamps from the files at hand, and whether any is missing
9718 (all-present (not (or missing-in missing-out)))
9719 ;; Has any input changed since we last generated the files?
9720 (up-to-date-p (stamp<= latest-in earliest-out))
9721 ;; If everything is up to date, the latest of inputs and outputs is our stamp
9722 (done-stamp (stamps-latest (cons latest-in out-stamps))))
9723 ;; Warn if some files are missing:
9724 ;; either our model is wrong or some other process is messing with our files.
9725 (when (and just-done (not all-present))
9726 (warn "~A completed without ~:[~*~;~*its input file~:p~2:*~{ ~S~}~*~]~
9727 ~:[~; or ~]~:[~*~;~*its output file~:p~2:*~{ ~S~}~*~]"
9728 (action-description o c)
9729 missing-in (length missing-in) (and missing-in missing-out)
9730 missing-out (length missing-out))))
9731 ;; Note that we use stamp<= instead of stamp< to play nice with generated files.
9732 ;; Any race condition is intrinsic to the limited timestamp resolution.
9733 (if (or just-done ;; The done-stamp is valid: if we're just done, or
9734 ;; if all filesystem effects are up-to-date and there's no invalidating reason.
9735 (and all-present up-to-date-p (operation-done-p o c) (not (action-forced-p plan o c))))
9736 (values done-stamp ;; return the hard-earned timestamp
9737 (or just-done
9738 out-op ;; a file-creating op is done when all files are up to date
9739 ;; a image-effecting a placeholder op is done when it was actually run,
9740 (and op-time (eql op-time done-stamp)))) ;; with the matching stamp
9741 ;; done-stamp invalid: return a timestamp in an indefinite future, action not done yet
9742 (values t nil)))))
9743
9744
9745 ;;;; Generic support for plan-traversal
9746 (with-upgradability ()
9747 (defmethod initialize-instance :after ((plan plan-traversal)
9748 &key force force-not system
9749 &allow-other-keys)
9750 (with-slots (forced forced-not) plan
9751 (setf forced (normalize-forced-systems force system))
9752 (setf forced-not (normalize-forced-not-systems force-not system))))
9753
9754 (defgeneric plan-actions (plan)
9755 (:documentation "Extract from a plan a list of actions to perform in sequence"))
9756 (defmethod plan-actions ((plan list))
9757 plan)
9758
9759 (defmethod (setf plan-action-status) (new-status (p plan-traversal) (o operation) (c component))
9760 (setf (gethash (node-for o c) (plan-visited-actions p)) new-status))
9761
9762 (defmethod plan-action-status ((p plan-traversal) (o operation) (c component))
9763 (or (and (action-forced-not-p p o c) (plan-action-status nil o c))
9764 (values (gethash (node-for o c) (plan-visited-actions p)))))
9765
9766 (defgeneric plan-record-dependency (plan operation component)
9767 (:documentation "Record an action as a dependency in the current plan")))
9768
9769
9770 ;;;; Detection of circular dependencies
9771 (with-upgradability ()
9772 (define-condition circular-dependency (system-definition-error)
9773 ((actions :initarg :actions :reader circular-dependency-actions))
9774 (:report (lambda (c s)
9775 (format s (compatfmt "~@<Circular dependency: ~3i~_~S~@:>")
9776 (circular-dependency-actions c)))))
9777
9778 (defgeneric call-while-visiting-action (plan operation component function)
9779 (:documentation "Detect circular dependencies"))
9780
9781 (defmethod call-while-visiting-action ((plan plan-traversal) operation component fun)
9782 (with-accessors ((action-set plan-visiting-action-set)
9783 (action-list plan-visiting-action-list)) plan
9784 (let ((action (cons operation component)))
9785 (when (gethash action action-set)
9786 (error 'circular-dependency :actions
9787 (member action (reverse action-list) :test 'equal)))
9788 (setf (gethash action action-set) t)
9789 (push action action-list)
9790 (unwind-protect
9791 (funcall fun)
9792 (pop action-list)
9793 (setf (gethash action action-set) nil)))))
9794
9795 ;; Syntactic sugar for call-while-visiting-action
9796 (defmacro while-visiting-action ((p o c) &body body)
9797 `(call-while-visiting-action ,p ,o ,c #'(lambda () ,@body))))
9798
9799
9800 ;;;; Actual traversal: traverse-action
9801 (with-upgradability ()
9802 (defgeneric traverse-action (plan operation component needed-in-image-p))
9803
9804 ;; TRAVERSE-ACTION, in the context of a given PLAN object that accumulates dependency data,
9805 ;; visits the action defined by its OPERATION and COMPONENT arguments,
9806 ;; and all its transitive dependencies (unless already visited),
9807 ;; in the context of the action being (or not) NEEDED-IN-IMAGE-P,
9808 ;; i.e. needs to be done in the current image vs merely have been done in a previous image.
9809 ;; For actions that are up-to-date, it returns a STAMP identifying the state of the action
9810 ;; (that's timestamp, but it could be a cryptographic digest in some ASDF extension),
9811 ;; or T if the action needs to be done again.
9812 ;;
9813 ;; Note that for an XCVB-like plan with one-image-per-file-outputting-action,
9814 ;; the below method would be insufficient, since it assumes a single image
9815 ;; to traverse each node at most twice; non-niip actions would be traversed only once,
9816 ;; but niip nodes could be traversed once per image, i.e. once plus once per non-niip action.
9817
9818 (defmethod traverse-action (plan operation component needed-in-image-p)
9819 (block nil
9820 ;; ACTION-VALID-P among other things, handles forcing logic, including FORCE-NOT,
9821 ;; and IF-FEATURE filtering.
9822 (unless (action-valid-p operation component) (return nil))
9823 ;; the following hook is needed by POIU, which tracks a full dependency graph,
9824 ;; instead of just a dependency order as in vanilla ASDF
9825 (plan-record-dependency plan operation component)
9826 ;; needed in image distinguishes b/w things that must happen in the
9827 ;; current image and those things that simply need to have been done in a previous one.
9828 (let* ((aniip (needed-in-image-p operation component)) ; action-specific needed-in-image
9829 ;; effective niip: meaningful for the action and required by the plan as traversed
9830 (eniip (and aniip needed-in-image-p))
9831 ;; status: have we traversed that action previously, and if so what was its status?
9832 (status (plan-action-status plan operation component)))
9833 (when (and status (or (action-done-p status) (action-planned-p status) (not eniip)))
9834 (return (action-stamp status))) ; Already visited with sufficient need-in-image level!
9835 (labels ((visit-action (niip) ; We may visit the action twice, once with niip NIL, then T
9836 (map-direct-dependencies ; recursively traverse dependencies
9837 t operation component #'(lambda (o c) (traverse-action plan o c niip)))
9838 (multiple-value-bind (stamp done-p) ; AFTER dependencies have been traversed,
9839 (compute-action-stamp plan operation component) ; compute action stamp
9840 (let ((add-to-plan-p (or (eql stamp t) (and niip (not done-p)))))
9841 (cond ; it needs be done if it's out of date or needed in image but absent
9842 ((and add-to-plan-p (not niip)) ; if we need to do it,
9843 (visit-action t)) ; then we need to do it *in the (current) image*!
9844 (t
9845 (setf (plan-action-status plan operation component) ; update status:
9846 (make-instance
9847 'planned-action-status
9848 :stamp stamp ; computed stamp
9849 :done-p (and done-p (not add-to-plan-p)) ; done *and* up-to-date?
9850 :planned-p add-to-plan-p ; included in list of things to be done?
9851 :index (if status ; index of action amongst all nodes in traversal
9852 (action-index status) ;; if already visited, keep index
9853 (incf (plan-total-action-count plan))))) ; else new index
9854 (when (and done-p (not add-to-plan-p))
9855 (setf (component-operation-time operation component) stamp))
9856 (when add-to-plan-p ; if it needs to be added to the plan,
9857 (incf (plan-planned-action-count plan)) ; count it
9858 (unless aniip ; if it's output-producing,
9859 (incf (plan-planned-output-action-count plan)))) ; count it
9860 stamp)))))) ; return the stamp
9861 (while-visiting-action (plan operation component) ; maintain context, handle circularity.
9862 (visit-action eniip))))))) ; visit the action
9863
9864
9865 ;;;; Sequential plans (the default)
9866 (with-upgradability ()
9867 (defclass sequential-plan (plan-traversal)
9868 ((actions-r :initform nil :accessor plan-actions-r))
9869 (:documentation "Simplest, default plan class, accumulating a sequence of actions"))
9870
9871 (defmethod plan-actions ((plan sequential-plan))
9872 (reverse (plan-actions-r plan)))
9873
9874 ;; No need to record a dependency to build a full graph, just accumulate nodes in order.
9875 (defmethod plan-record-dependency ((plan sequential-plan) (o operation) (c component))
9876 (values))
9877
9878 (defmethod (setf plan-action-status) :after
9879 (new-status (p sequential-plan) (o operation) (c component))
9880 (when (action-planned-p new-status)
9881 (push (cons o c) (plan-actions-r p)))))
9882
9883
9884 ;;;; High-level interface: traverse, perform-plan, plan-operates-on-p
9885 (with-upgradability ()
9886 (defgeneric make-plan (plan-class operation component &key &allow-other-keys)
9887 (:documentation "Generate and return a plan for performing OPERATION on COMPONENT."))
9888 (define-convenience-action-methods make-plan (plan-class operation component &key))
9889
9890 (defgeneric perform-plan (plan &key)
9891 (:documentation "Actually perform a plan and build the requested actions"))
9892 (defgeneric plan-operates-on-p (plan component)
9893 (:documentation "Does this PLAN include any operation on given COMPONENT?"))
9894
9895 (defvar *default-plan-class* 'sequential-plan
9896 "The default plan class to use when building with ASDF")
9897
9898 (defmethod make-plan (plan-class (o operation) (c component) &rest keys &key &allow-other-keys)
9899 (let ((plan (apply 'make-instance (or plan-class *default-plan-class*)
9900 :system (component-system c) keys)))
9901 (traverse-action plan o c t)
9902 plan))
9903
9904 (defmethod perform-plan :around ((plan t) &key)
9905 #+xcl (declare (ignorable plan))
9906 (let ((*package* *package*)
9907 (*readtable* *readtable*))
9908 (with-compilation-unit () ;; backward-compatibility.
9909 (call-next-method)))) ;; Going forward, see deferred-warning support in lisp-build.
9910
9911 (defmethod perform-plan ((plan t) &rest keys &key &allow-other-keys)
9912 (apply 'perform-plan (plan-actions plan) keys))
9913
9914 (defmethod perform-plan ((steps list) &key force &allow-other-keys)
9915 (loop* :for (o . c) :in steps
9916 :when (or force (not (nth-value 1 (compute-action-stamp nil o c))))
9917 :do (perform-with-restarts o c)))
9918
9919 (defmethod plan-operates-on-p ((plan plan-traversal) (component-path list))
9920 (plan-operates-on-p (plan-actions plan) component-path))
9921
9922 (defmethod plan-operates-on-p ((plan list) (component-path list))
9923 (find component-path (mapcar 'cdr plan)
9924 :test 'equal :key 'component-find-path)))
9925
9926
9927 ;;;; Incidental traversals
9928
9929 ;;; Making a FILTERED-SEQUENTIAL-PLAN can be used to, e.g., all of the source
9930 ;;; files required by a bundling operation.
9931 (with-upgradability ()
9932 (defclass filtered-sequential-plan (sequential-plan)
9933 ((action-filter :initform t :initarg :action-filter :reader plan-action-filter)
9934 (component-type :initform t :initarg :component-type :reader plan-component-type)
9935 (keep-operation :initform t :initarg :keep-operation :reader plan-keep-operation)
9936 (keep-component :initform t :initarg :keep-component :reader plan-keep-component))
9937 (:documentation "A variant of SEQUENTIAL-PLAN that only records a subset of actions."))
9938
9939 (defmethod initialize-instance :after ((plan filtered-sequential-plan)
9940 &key force force-not
9941 other-systems)
9942 (declare (ignore force force-not))
9943 ;; Ignore force and force-not, rely on other-systems:
9944 ;; force traversal of what we're interested in, i.e. current system or also others;
9945 ;; force-not traversal of what we're not interested in, i.e. other systems unless other-systems.
9946 (with-slots (forced forced-not action-filter system) plan
9947 (setf forced (normalize-forced-systems (if other-systems :all t) system))
9948 (setf forced-not (normalize-forced-not-systems (if other-systems nil t) system))
9949 (setf action-filter (ensure-function action-filter))))
9950
9951 (defmethod traverse-actions (actions &rest keys &key plan-class &allow-other-keys)
9952 "Given a list of actions, build a plan with these actions as roots."
9953 (let ((plan (apply 'make-instance (or plan-class 'filtered-sequential-plan) keys)))
9954 (loop* :for (o . c) :in actions :do (traverse-action plan o c t))
9955 plan))
9956
9957 (define-convenience-action-methods traverse-sub-actions (operation component &key))
9958 (defmethod traverse-sub-actions ((operation operation) (component component)
9959 &rest keys &key &allow-other-keys)
9960 (apply 'traverse-actions (direct-dependencies t operation component)
9961 :system (component-system component) keys))
9962
9963 (defmethod plan-actions ((plan filtered-sequential-plan))
9964 (with-slots (keep-operation keep-component) plan
9965 (loop* :for (o . c) :in (call-next-method)
9966 :when (and (typep o keep-operation) (typep c keep-component))
9967 :collect (cons o c))))
9968
9969 (defmethod required-components (system &rest keys &key (goal-operation 'load-op) &allow-other-keys)
9970 "Given a SYSTEM and a GOAL-OPERATION (default LOAD-OP), traverse the dependencies and
9971 return a list of the components involved in building the desired action."
9972 (remove-duplicates
9973 (mapcar 'cdr (plan-actions
9974 (apply 'traverse-sub-actions goal-operation system
9975 (remove-plist-key :goal-operation keys))))
9976 :from-end t)))
9977
9978 ;;;; -------------------------------------------------------------------------
9979 ;;;; Invoking Operations
9980
9981 (uiop/package:define-package :asdf/operate
9982 (:recycle :asdf/operate :asdf)
9983 (:use :uiop/common-lisp :uiop :asdf/upgrade :asdf/cache
9984 :asdf/component :asdf/system :asdf/operation :asdf/action
9985 :asdf/find-system :asdf/find-component :asdf/lisp-action :asdf/plan)
9986 (:export
9987 #:operate #:oos
9988 #:*systems-being-operated*
9989 #:build-op #:make
9990 #:load-system #:load-systems #:load-systems*
9991 #:compile-system #:test-system #:require-system
9992 #:*load-system-operation* #:module-provide-asdf
9993 #:component-loaded-p #:already-loaded-systems))
9994 (in-package :asdf/operate)
9995
9996 (with-upgradability ()
9997 (defgeneric* (operate) (operation component &key &allow-other-keys)
9998 (:documentation
9999 "Operate does mainly four things for the user:
10000
10001 1. Resolves the OPERATION designator into an operation object.
10002 OPERATION is typically a symbol denoting an operation class, instantiated with MAKE-OPERATION.
10003 2. Resolves the COMPONENT designator into a component object.
10004 COMPONENT is typically a string or symbol naming a system, loaded from disk using FIND-SYSTEM.
10005 3. It then calls MAKE-PLAN with the operation and system as arguments.
10006 4. Finally calls PERFORM-PLAN on the resulting plan to actually build the system.
10007
10008 The entire computation is wrapped in WITH-COMPILATION-UNIT and error handling code.
10009 If a VERSION argument is supplied, then operate also ensures that the system found satisfies it
10010 using the VERSION-SATISFIES method.
10011 If a PLAN-CLASS argument is supplied, that class is used for the plan.
10012
10013 The :FORCE or :FORCE-NOT argument to OPERATE can be:
10014 T to force the inside of the specified system to be rebuilt (resp. not),
10015 without recursively forcing the other systems we depend on.
10016 :ALL to force all systems including other systems we depend on to be rebuilt (resp. not).
10017 (SYSTEM1 SYSTEM2 ... SYSTEMN) to force systems named in a given list
10018 :FORCE-NOT has precedence over :FORCE; builtin systems cannot be forced.
10019
10020 For backward compatibility, all keyword arguments are passed to MAKE-OPERATION
10021 when instantiating a new operation, that will in turn be inherited by new operations.
10022 But do NOT depend on it, for this is deprecated behavior."))
10023
10024 (define-convenience-action-methods operate (operation component &key)
10025 ;; I'd like to at least remove-plist-keys :force :force-not :verbose,
10026 ;; but swank.asd relies on :force (!).
10027 :operation-initargs t ;; backward-compatibility with ASDF1. Deprecated.
10028 :if-no-component (error 'missing-component :requires component))
10029
10030 ;; TODO: actually, the use as a hash-set is write-only, so it can be reduced to a boolean,
10031 ;; and then possibly replaced by checking for say *asdf-cache*.
10032 (defvar *systems-being-operated* nil
10033 "A hash-set of names of systems being operated on, or NIL")
10034
10035 ;; This method ensures that an ASDF upgrade is attempted as the very first thing,
10036 ;; with suitable state preservation in case in case it actually happens,
10037 ;; and that a few suitable dynamic bindings are established.
10038 (defmethod operate :around (operation component &rest keys
10039 &key verbose
10040 (on-warnings *compile-file-warnings-behaviour*)
10041 (on-failure *compile-file-failure-behaviour*) &allow-other-keys)
10042 (let* ((systems-being-operated *systems-being-operated*)
10043 (*systems-being-operated* (or systems-being-operated (make-hash-table :test 'equal)))
10044 (operation-remaker ;; how to remake the operation after ASDF was upgraded (if it was)
10045 (etypecase operation
10046 (operation (let ((name (type-of operation))
10047 (initargs (operation-original-initargs operation)))
10048 #'(lambda () (apply 'make-operation name :original-initargs initargs initargs))))
10049 ((or symbol string) (constantly operation))))
10050 (component-path (typecase component ;; to remake the component after ASDF upgrade
10051 (component (component-find-path component))
10052 (t component))))
10053 ;; Before we operate on any system, make sure ASDF is up-to-date,
10054 ;; for if an upgrade is ever attempted at any later time, there may be BIG trouble.
10055 (unless systems-being-operated
10056 (when (upgrade-asdf)
10057 ;; If we were upgraded, restart OPERATE the hardest of ways, for
10058 ;; its function may have been redefined, its symbol uninterned, its package deleted.
10059 (return-from operate
10060 (apply 'operate (funcall operation-remaker) component-path keys))))
10061 ;; Setup proper bindings around any operate call.
10062 (with-asdf-cache ()
10063 (let* ((*verbose-out* (and verbose *standard-output*))
10064 (*compile-file-warnings-behaviour* on-warnings)
10065 (*compile-file-failure-behaviour* on-failure))
10066 (call-next-method)))))
10067
10068 (defmethod operate :before ((operation operation) (component component)
10069 &key version &allow-other-keys)
10070 (let ((system (component-system component)))
10071 (setf (gethash (coerce-name system) *systems-being-operated*) system))
10072 (unless (version-satisfies component version)
10073 (error 'missing-component-of-version :requires component :version version)))
10074
10075 (defmethod operate ((operation operation) (component component)
10076 &rest keys &key plan-class &allow-other-keys)
10077 (let ((plan (apply 'make-plan plan-class operation component keys)))
10078 (apply 'perform-plan plan keys)
10079 (values operation plan)))
10080
10081 (defun oos (operation component &rest args &key &allow-other-keys)
10082 (apply 'operate operation component args))
10083
10084 (setf (documentation 'oos 'function)
10085 (format nil "Short for _operate on system_ and an alias for the OPERATE function.~%~%~a"
10086 (documentation 'operate 'function))))
10087
10088
10089 ;;;; Common operations
10090 (with-upgradability ()
10091 (defvar *load-system-operation* 'load-op
10092 "Operation used by ASDF:LOAD-SYSTEM. By default, ASDF:LOAD-OP.
10093 You may override it with e.g. ASDF:LOAD-BUNDLE-OP from asdf/bundle
10094 or ASDF:LOAD-SOURCE-OP if your fasl loading is somehow broken.
10095
10096 The default operation may change in the future if we implement a
10097 component-directed strategy for how to load or compile systems.")
10098
10099 ;; In prepare-op for a system, propagate *load-system-operation* rather than load-op
10100 (defmethod component-depends-on ((o prepare-op) (s system))
10101 (loop :for (do . dc) :in (call-next-method)
10102 :collect (cons (if (eq do 'load-op) *load-system-operation* do) dc)))
10103
10104 (defclass build-op (non-propagating-operation) ()
10105 (:documentation "Since ASDF3, BUILD-OP is the recommended 'master' operation,
10106 to operate by default on a system or component, via the function BUILD.
10107 Its meaning is configurable via the :BUILD-OPERATION option of a component.
10108 which typically specifies the name of a specific operation to which to delegate the build,
10109 as a symbol or as a string later read as a symbol (after loading the defsystem-depends-on);
10110 if NIL is specified (the default), BUILD-OP falls back to the *LOAD-SYSTEM-OPERATION*
10111 that will load the system in the current image, and its typically LOAD-OP."))
10112 (defmethod component-depends-on ((o build-op) (c component))
10113 `((,(or (component-build-operation c) *load-system-operation*) ,c)
10114 ,@(call-next-method)))
10115
10116 (defun make (system &rest keys)
10117 "The recommended way to interact with ASDF3.1 is via (ASDF:MAKE :FOO).
10118 It will build system FOO using the operation BUILD-OP,
10119 the meaning of which is configurable by the system, and
10120 defaults to *LOAD-SYSTEM-OPERATION*, usually LOAD-OP,
10121 to load it in current image."
10122 (apply 'operate 'build-op system keys)
10123 t)
10124
10125 (defun load-system (system &rest keys &key force force-not verbose version &allow-other-keys)
10126 "Shorthand for `(operate 'asdf:load-op system)`. See OPERATE for details."
10127 (declare (ignore force force-not verbose version))
10128 (apply 'operate *load-system-operation* system keys)
10129 t)
10130
10131 (defun load-systems* (systems &rest keys)
10132 "Loading multiple systems at once."
10133 (dolist (s systems) (apply 'load-system s keys)))
10134
10135 (defun load-systems (&rest systems)
10136 "Loading multiple systems at once."
10137 (load-systems* systems))
10138
10139 (defun compile-system (system &rest args &key force force-not verbose version &allow-other-keys)
10140 "Shorthand for `(asdf:operate 'asdf:compile-op system)`. See OPERATE for details."
10141 (declare (ignore force force-not verbose version))
10142 (apply 'operate 'compile-op system args)
10143 t)
10144
10145 (defun test-system (system &rest args &key force force-not verbose version &allow-other-keys)
10146 "Shorthand for `(asdf:operate 'asdf:test-op system)`. See OPERATE for details."
10147 (declare (ignore force force-not verbose version))
10148 (apply 'operate 'test-op system args)
10149 t))
10150
10151 ;;;;; Define the function REQUIRE-SYSTEM, that, similarly to REQUIRE,
10152 ;; only tries to load its specified target if it's not loaded yet.
10153 (with-upgradability ()
10154 (defun component-loaded-p (component)
10155 "Has the given COMPONENT been successfully loaded in the current image (yet)?
10156 Note that this returns true even if the component is not up to date."
10157 (if-let ((component (find-component component () :registered t)))
10158 (action-already-done-p nil (make-instance 'load-op) component)))
10159
10160 (defun already-loaded-systems ()
10161 "return a list of the names of the systems that have been successfully loaded so far"
10162 (mapcar 'coerce-name (remove-if-not 'component-loaded-p (registered-systems*))))
10163
10164 (defun require-system (system &rest keys &key &allow-other-keys)
10165 "Ensure the specified SYSTEM is loaded, passing the KEYS to OPERATE, but do not update the
10166 system or its dependencies if they have already been loaded."
10167 (unless (component-loaded-p system)
10168 (apply 'load-system system :force-not (already-loaded-systems) keys))))
10169
10170
10171 ;;;; Define the class REQUIRE-SYSTEM, to be hooked into CL:REQUIRE when possible,
10172 ;; i.e. for ABCL, CLISP, ClozureCL, CMUCL, ECL, MKCL and SBCL
10173 ;; Note that despite the two being homonyms, the _function_ require-system
10174 ;; and the _class_ require-system are quite distinct entities, fulfilling independent purposes.
10175 (with-upgradability ()
10176 (defvar *modules-being-required* nil)
10177
10178 (defclass require-system (system)
10179 ((module :initarg :module :initform nil :accessor required-module))
10180 (:documentation "A SYSTEM subclass whose processing is handled by
10181 the implementation's REQUIRE rather than by internal ASDF mechanisms."))
10182
10183 (defmethod perform ((o compile-op) (c require-system))
10184 nil)
10185
10186 (defmethod perform ((o load-op) (s require-system))
10187 (let* ((module (or (required-module s) (coerce-name s)))
10188 (*modules-being-required* (cons module *modules-being-required*)))
10189 (assert (null (component-children s)))
10190 ;; CMUCL likes its module names to be all upcase.
10191 (require #-cmucl module #+cmucl (string-upcase module))))
10192
10193 (defmethod resolve-dependency-combination (component (combinator (eql :require)) arguments)
10194 (unless (and (length=n-p arguments 1)
10195 (typep (car arguments) '(or string (and symbol (not null)))))
10196 (parameter-error (compatfmt "~@<In ~S, bad dependency ~S for ~S. ~S takes one argument, a string or non-null symbol~@:>")
10197 'resolve-dependency-combination
10198 (cons combinator arguments) component combinator))
10199 ;; :require must be prepared for some implementations providing modules using ASDF,
10200 ;; as SBCL used to do, and others may might do. Thus, the system provided in the end
10201 ;; would be a downcased name as per module-provide-asdf above. For the same reason,
10202 ;; we cannot assume that the system in the end will be of type require-system,
10203 ;; but must check whether we can use find-system and short-circuit cl:require.
10204 ;; Otherwise, calling cl:require could result in nasty reentrant calls between
10205 ;; cl:require and asdf:operate that could potentially blow up the stack,
10206 ;; all the while defeating the consistency of the dependency graph.
10207 (let* ((module (car arguments)) ;; NB: we already checked that it was not null
10208 (name (string-downcase module))
10209 (system (find-system name nil)))
10210 (or system (let ((system (make-instance 'require-system :name name)))
10211 (register-system system)
10212 system))))
10213
10214 (defun module-provide-asdf (name)
10215 ;; We must use string-downcase, because modules are traditionally specified as symbols,
10216 ;; that implementations traditionally normalize as uppercase, for which we seek a system
10217 ;; with a name that is traditionally in lowercase. Case is lost along the way. That's fine.
10218 ;; We could make complex, non-portable rules to try to preserve case, and just documenting
10219 ;; them would be a hell that it would be a disservice to inflict on users.
10220 (let ((module (string-downcase name)))
10221 (unless (member module *modules-being-required* :test 'equal)
10222 (let ((*modules-being-required* (cons module *modules-being-required*))
10223 #+sbcl (sb-impl::*requiring* (remove module sb-impl::*requiring* :test 'equal)))
10224 (handler-bind
10225 ((style-warning #'muffle-warning)
10226 (missing-component (constantly nil))
10227 (fatal-condition
10228 #'(lambda (e)
10229 (format *error-output* (compatfmt "~@<ASDF could not load ~(~A~) because ~A.~@:>~%")
10230 name e))))
10231 (let ((*verbose-out* (make-broadcast-stream)))
10232 (let ((system (find-system module nil)))
10233 (when system
10234 (require-system system :verbose nil)
10235 t)))))))))
10236
10237
10238 ;;;; Some upgrade magic
10239 (with-upgradability ()
10240 (defun restart-upgraded-asdf ()
10241 ;; If we're in the middle of something, restart it.
10242 (when *asdf-cache*
10243 (let ((l (loop :for k :being :the hash-keys :of *asdf-cache*
10244 :when (eq (first k) 'find-system) :collect (second k))))
10245 (clrhash *asdf-cache*)
10246 (dolist (s l) (find-system s nil)))))
10247 (register-hook-function '*post-upgrade-restart-hook* 'restart-upgraded-asdf)
10248
10249 ;; The following function's symbol is from asdf/find-system.
10250 ;; It is defined here to resolve what would otherwise be forward package references.
10251 (defun mark-component-preloaded (component)
10252 "Mark a component as preloaded."
10253 (let ((component (find-component component nil :registered t)))
10254 ;; Recurse to children, so asdf/plan will hopefully be happy.
10255 (map () 'mark-component-preloaded (component-children component))
10256 ;; Mark the timestamps of the common lisp-action operations as 0.
10257 (let ((times (component-operation-times component)))
10258 (dolist (o '(load-op compile-op prepare-op))
10259 (setf (gethash o times) 0))))))
10260
10261 ;;;; ---------------------------------------------------------------------------
10262 ;;;; asdf-output-translations
10263
10264 (uiop/package:define-package :asdf/output-translations
10265 (:recycle :asdf/output-translations :asdf)
10266 (:use :uiop/common-lisp :uiop :asdf/upgrade)
10267 (:export
10268 #:*output-translations* #:*output-translations-parameter*
10269 #:invalid-output-translation
10270 #:output-translations #:output-translations-initialized-p
10271 #:initialize-output-translations #:clear-output-translations
10272 #:disable-output-translations #:ensure-output-translations
10273 #:apply-output-translations
10274 #:validate-output-translations-directive #:validate-output-translations-form
10275 #:validate-output-translations-file #:validate-output-translations-directory
10276 #:parse-output-translations-string #:wrapping-output-translations
10277 #:user-output-translations-pathname #:system-output-translations-pathname
10278 #:user-output-translations-directory-pathname #:system-output-translations-directory-pathname
10279 #:environment-output-translations #:process-output-translations
10280 #:compute-output-translations
10281 #+abcl #:translate-jar-pathname
10282 ))
10283 (in-package :asdf/output-translations)
10284
10285 ;; (setf output-translations) at some point used to be a macro for the sake of
10286 ;; obsolete versions of GCL. Make sure that macro doesn't come to haunt us.
10287 (when-upgrading () (undefine-function '(setf output-translations)))
10288
10289 (with-upgradability ()
10290 (define-condition invalid-output-translation (invalid-configuration warning)
10291 ((format :initform (compatfmt "~@<Invalid asdf output-translation ~S~@[ in ~S~]~@{ ~@?~}~@:>"))))
10292
10293 (defvar *output-translations* ()
10294 "Either NIL (for uninitialized), or a list of one element,
10295 said element itself being a sorted list of mappings.
10296 Each mapping is a pair of a source pathname and destination pathname,
10297 and the order is by decreasing length of namestring of the source pathname.")
10298
10299 (defun output-translations ()
10300 "Return the configured output-translations, if any"
10301 (car *output-translations*))
10302
10303 ;; Set the output-translations, by sorting the provided new-value.
10304 (defun set-output-translations (new-value)
10305 (setf *output-translations*
10306 (list
10307 (stable-sort (copy-list new-value) #'>
10308 :key #'(lambda (x)
10309 (etypecase (car x)
10310 ((eql t) -1)
10311 (pathname
10312 (let ((directory (pathname-directory (car x))))
10313 (if (listp directory) (length directory) 0))))))))
10314 new-value)
10315 (defun* ((setf output-translations)) (new-value) (set-output-translations new-value))
10316
10317 (defun output-translations-initialized-p ()
10318 "Have the output-translations been initialized yet?"
10319 (and *output-translations* t))
10320
10321 (defun clear-output-translations ()
10322 "Undoes any initialization of the output translations."
10323 (setf *output-translations* '())
10324 (values))
10325 (register-clear-configuration-hook 'clear-output-translations)
10326
10327
10328 ;;; Validation of the configuration directives...
10329
10330 (defun validate-output-translations-directive (directive)
10331 (or (member directive '(:enable-user-cache :disable-cache nil))
10332 (and (consp directive)
10333 (or (and (length=n-p directive 2)
10334 (or (and (eq (first directive) :include)
10335 (typep (second directive) '(or string pathname null)))
10336 (and (location-designator-p (first directive))
10337 (or (location-designator-p (second directive))
10338 (location-function-p (second directive))))))
10339 (and (length=n-p directive 1)
10340 (location-designator-p (first directive)))))))
10341
10342 (defun validate-output-translations-form (form &key location)
10343 (validate-configuration-form
10344 form
10345 :output-translations
10346 'validate-output-translations-directive
10347 :location location :invalid-form-reporter 'invalid-output-translation))
10348
10349 (defun validate-output-translations-file (file)
10350 (validate-configuration-file
10351 file 'validate-output-translations-form :description "output translations"))
10352
10353 (defun validate-output-translations-directory (directory)
10354 (validate-configuration-directory
10355 directory :output-translations 'validate-output-translations-directive
10356 :invalid-form-reporter 'invalid-output-translation))
10357
10358
10359 ;;; Parse the ASDF_OUTPUT_TRANSLATIONS environment variable and/or some file contents
10360 (defun parse-output-translations-string (string &key location)
10361 (cond
10362 ((or (null string) (equal string ""))
10363 '(:output-translations :inherit-configuration))
10364 ((not (stringp string))
10365 (error (compatfmt "~@<Environment string isn't: ~3i~_~S~@:>") string))
10366 ((eql (char string 0) #\")
10367 (parse-output-translations-string (read-from-string string) :location location))
10368 ((eql (char string 0) #\()
10369 (validate-output-translations-form (read-from-string string) :location location))
10370 (t
10371 (loop
10372 :with inherit = nil
10373 :with directives = ()
10374 :with start = 0
10375 :with end = (length string)
10376 :with source = nil
10377 :with separator = (inter-directory-separator)
10378 :for i = (or (position separator string :start start) end) :do
10379 (let ((s (subseq string start i)))
10380 (cond
10381 (source
10382 (push (list source (if (equal "" s) nil s)) directives)
10383 (setf source nil))
10384 ((equal "" s)
10385 (when inherit
10386 (error (compatfmt "~@<Only one inherited configuration allowed: ~3i~_~S~@:>")
10387 string))
10388 (setf inherit t)
10389 (push :inherit-configuration directives))
10390 (t
10391 (setf source s)))
10392 (setf start (1+ i))
10393 (when (> start end)
10394 (when source
10395 (error (compatfmt "~@<Uneven number of components in source to destination mapping: ~3i~_~S~@:>")
10396 string))
10397 (unless inherit
10398 (push :ignore-inherited-configuration directives))
10399 (return `(:output-translations ,@(nreverse directives)))))))))
10400
10401
10402 ;; The default sources of configuration for output-translations
10403 (defparameter* *default-output-translations*
10404 '(environment-output-translations
10405 user-output-translations-pathname
10406 user-output-translations-directory-pathname
10407 system-output-translations-pathname
10408 system-output-translations-directory-pathname))
10409
10410 ;; Compulsory implementation-dependent wrapping for the translations:
10411 ;; handle implementation-provided systems.
10412 (defun wrapping-output-translations ()
10413 `(:output-translations
10414 ;; Some implementations have precompiled ASDF systems,
10415 ;; so we must disable translations for implementation paths.
10416 #+(or clasp #|clozure|# ecl mkcl sbcl)
10417 ,@(let ((h (resolve-symlinks* (lisp-implementation-directory))))
10418 (when h `(((,h ,*wild-path*) ()))))
10419 #+mkcl (,(translate-logical-pathname "CONTRIB:") ())
10420 ;; All-import, here is where we want user stuff to be:
10421 :inherit-configuration
10422 ;; These are for convenience, and can be overridden by the user:
10423 #+abcl (#p"/___jar___file___root___/**/*.*" (:user-cache #p"**/*.*"))
10424 #+abcl (#p"jar:file:/**/*.jar!/**/*.*" (:function translate-jar-pathname))
10425 ;; We enable the user cache by default, and here is the place we do:
10426 :enable-user-cache))
10427
10428 ;; Relative pathnames of output-translations configuration to XDG configuration directory
10429 (defparameter *output-translations-file* (parse-unix-namestring "common-lisp/asdf-output-translations.conf"))
10430 (defparameter *output-translations-directory* (parse-unix-namestring "common-lisp/asdf-output-translations.conf.d/"))
10431
10432 ;; Locating various configuration pathnames, depending on input or output intent.
10433 (defun user-output-translations-pathname (&key (direction :input))
10434 (xdg-config-pathname *output-translations-file* direction))
10435 (defun system-output-translations-pathname (&key (direction :input))
10436 (find-preferred-file (system-config-pathnames *output-translations-file*)
10437 :direction direction))
10438 (defun user-output-translations-directory-pathname (&key (direction :input))
10439 (xdg-config-pathname *output-translations-directory* direction))
10440 (defun system-output-translations-directory-pathname (&key (direction :input))
10441 (find-preferred-file (system-config-pathnames *output-translations-directory*)
10442 :direction direction))
10443 (defun environment-output-translations ()
10444 (getenv "ASDF_OUTPUT_TRANSLATIONS"))
10445
10446
10447 ;;; Processing the configuration.
10448
10449 (defgeneric process-output-translations (spec &key inherit collect))
10450
10451 (defun inherit-output-translations (inherit &key collect)
10452 (when inherit
10453 (process-output-translations (first inherit) :collect collect :inherit (rest inherit))))
10454
10455 (defun* (process-output-translations-directive) (directive &key inherit collect)
10456 (if (atom directive)
10457 (ecase directive
10458 ((:enable-user-cache)
10459 (process-output-translations-directive '(t :user-cache) :collect collect))
10460 ((:disable-cache)
10461 (process-output-translations-directive '(t t) :collect collect))
10462 ((:inherit-configuration)
10463 (inherit-output-translations inherit :collect collect))
10464 ((:ignore-inherited-configuration :ignore-invalid-entries nil)
10465 nil))
10466 (let ((src (first directive))
10467 (dst (second directive)))
10468 (if (eq src :include)
10469 (when dst
10470 (process-output-translations (pathname dst) :inherit nil :collect collect))
10471 (when src
10472 (let ((trusrc (or (eql src t)
10473 (let ((loc (resolve-location src :ensure-directory t :wilden t)))
10474 (if (absolute-pathname-p loc) (resolve-symlinks* loc) loc)))))
10475 (cond
10476 ((location-function-p dst)
10477 (funcall collect
10478 (list trusrc (ensure-function (second dst)))))
10479 ((typep dst 'boolean)
10480 (funcall collect (list trusrc t)))
10481 (t
10482 (let* ((trudst (resolve-location dst :ensure-directory t :wilden t)))
10483 (funcall collect (list trudst t))
10484 (funcall collect (list trusrc trudst)))))))))))
10485
10486 (defmethod process-output-translations ((x symbol) &key
10487 (inherit *default-output-translations*)
10488 collect)
10489 (process-output-translations (funcall x) :inherit inherit :collect collect))
10490 (defmethod process-output-translations ((pathname pathname) &key inherit collect)
10491 (cond
10492 ((directory-pathname-p pathname)
10493 (process-output-translations (validate-output-translations-directory pathname)
10494 :inherit inherit :collect collect))
10495 ((probe-file* pathname :truename *resolve-symlinks*)
10496 (process-output-translations (validate-output-translations-file pathname)
10497 :inherit inherit :collect collect))
10498 (t
10499 (inherit-output-translations inherit :collect collect))))
10500 (defmethod process-output-translations ((string string) &key inherit collect)
10501 (process-output-translations (parse-output-translations-string string)
10502 :inherit inherit :collect collect))
10503 (defmethod process-output-translations ((x null) &key inherit collect)
10504 (inherit-output-translations inherit :collect collect))
10505 (defmethod process-output-translations ((form cons) &key inherit collect)
10506 (dolist (directive (cdr (validate-output-translations-form form)))
10507 (process-output-translations-directive directive :inherit inherit :collect collect)))
10508
10509
10510 ;;; Top-level entry-points to configure output-translations
10511
10512 (defun compute-output-translations (&optional parameter)
10513 "read the configuration, return it"
10514 (remove-duplicates
10515 (while-collecting (c)
10516 (inherit-output-translations
10517 `(wrapping-output-translations ,parameter ,@*default-output-translations*) :collect #'c))
10518 :test 'equal :from-end t))
10519
10520 ;; Saving the user-provided parameter to output-translations, if any,
10521 ;; so we can recompute the translations after code upgrade.
10522 (defvar *output-translations-parameter* nil)
10523
10524 ;; Main entry-point for users.
10525 (defun initialize-output-translations (&optional (parameter *output-translations-parameter*))
10526 "read the configuration, initialize the internal configuration variable,
10527 return the configuration"
10528 (setf *output-translations-parameter* parameter
10529 (output-translations) (compute-output-translations parameter)))
10530
10531 (defun disable-output-translations ()
10532 "Initialize output translations in a way that maps every file to itself,
10533 effectively disabling the output translation facility."
10534 (initialize-output-translations
10535 '(:output-translations :disable-cache :ignore-inherited-configuration)))
10536
10537 ;; checks an initial variable to see whether the state is initialized
10538 ;; or cleared. In the former case, return current configuration; in
10539 ;; the latter, initialize. ASDF will call this function at the start
10540 ;; of (asdf:find-system).
10541 (defun ensure-output-translations ()
10542 (if (output-translations-initialized-p)
10543 (output-translations)
10544 (initialize-output-translations)))
10545
10546
10547 ;; Top-level entry-point to _use_ output-translations
10548 (defun* (apply-output-translations) (path)
10549 (etypecase path
10550 (logical-pathname
10551 path)
10552 ((or pathname string)
10553 (ensure-output-translations)
10554 (loop* :with p = (resolve-symlinks* path)
10555 :for (source destination) :in (car *output-translations*)
10556 :for root = (when (or (eq source t)
10557 (and (pathnamep source)
10558 (not (absolute-pathname-p source))))
10559 (pathname-root p))
10560 :for absolute-source = (cond
10561 ((eq source t) (wilden root))
10562 (root (merge-pathnames* source root))
10563 (t source))
10564 :when (or (eq source t) (pathname-match-p p absolute-source))
10565 :return (translate-pathname* p absolute-source destination root source)
10566 :finally (return p)))))
10567
10568
10569 ;; Hook into uiop's output-translation mechanism
10570 #-cormanlisp
10571 (setf *output-translation-function* 'apply-output-translations)
10572
10573
10574 ;;; Implementation-dependent hacks
10575 #+abcl ;; ABCL: make it possible to use systems provided in the ABCL jar.
10576 (defun translate-jar-pathname (source wildcard)
10577 (declare (ignore wildcard))
10578 (flet ((normalize-device (pathname)
10579 (if (find :windows *features*)
10580 pathname
10581 (make-pathname :defaults pathname :device :unspecific))))
10582 (let* ((jar
10583 (pathname (first (pathname-device source))))
10584 (target-root-directory-namestring
10585 (format nil "/___jar___file___root___/~@[~A/~]"
10586 (and (find :windows *features*)
10587 (pathname-device jar))))
10588 (relative-source
10589 (relativize-pathname-directory source))
10590 (relative-jar
10591 (relativize-pathname-directory (ensure-directory-pathname jar)))
10592 (target-root-directory
10593 (normalize-device
10594 (pathname-directory-pathname
10595 (parse-namestring target-root-directory-namestring))))
10596 (target-root
10597 (merge-pathnames* relative-jar target-root-directory))
10598 (target
10599 (merge-pathnames* relative-source target-root)))
10600 (normalize-device (apply-output-translations target))))))
10601
10602 ;;;; -----------------------------------------------------------------
10603 ;;;; Source Registry Configuration, by Francois-Rene Rideau
10604 ;;;; See the Manual and https://bugs.launchpad.net/asdf/+bug/485918
10605
10606 (uiop/package:define-package :asdf/source-registry
10607 (:recycle :asdf/source-registry :asdf)
10608 (:use :uiop/common-lisp :uiop :asdf/upgrade :asdf/find-system)
10609 (:export
10610 #:*source-registry-parameter* #:*default-source-registries*
10611 #:invalid-source-registry
10612 #:source-registry-initialized-p
10613 #:initialize-source-registry #:clear-source-registry #:*source-registry*
10614 #:ensure-source-registry #:*source-registry-parameter*
10615 #:*default-source-registry-exclusions* #:*source-registry-exclusions*
10616 #:*wild-asd* #:directory-asd-files #:register-asd-directory
10617 #:*recurse-beyond-asds* #:collect-asds-in-directory #:collect-sub*directories-asd-files
10618 #:validate-source-registry-directive #:validate-source-registry-form
10619 #:validate-source-registry-file #:validate-source-registry-directory
10620 #:parse-source-registry-string #:wrapping-source-registry
10621 #:default-user-source-registry #:default-system-source-registry
10622 #:user-source-registry #:system-source-registry
10623 #:user-source-registry-directory #:system-source-registry-directory
10624 #:environment-source-registry #:process-source-registry #:inherit-source-registry
10625 #:compute-source-registry #:flatten-source-registry
10626 #:sysdef-source-registry-search))
10627 (in-package :asdf/source-registry)
10628
10629 (with-upgradability ()
10630 (define-condition invalid-source-registry (invalid-configuration warning)
10631 ((format :initform (compatfmt "~@<Invalid source registry ~S~@[ in ~S~]~@{ ~@?~}~@:>"))))
10632
10633 ;; Default list of directories under which the source-registry tree search won't recurse
10634 (defvar *default-source-registry-exclusions*
10635 '(;;-- Using ack 1.2 exclusions
10636 ".bzr" ".cdv"
10637 ;; "~.dep" "~.dot" "~.nib" "~.plst" ; we don't support ack wildcards
10638 ".git" ".hg" ".pc" ".svn" "CVS" "RCS" "SCCS" "_darcs"
10639 "_sgbak" "autom4te.cache" "cover_db" "_build"
10640 ;;-- debian often builds stuff under the debian directory... BAD.
10641 "debian"))
10642
10643 ;; Actual list of directories under which the source-registry tree search won't recurse
10644 (defvar *source-registry-exclusions* *default-source-registry-exclusions*)
10645
10646 ;; The state of the source-registry after search in configured locations
10647 (defvar *source-registry* nil
10648 "Either NIL (for uninitialized), or an equal hash-table, mapping
10649 system names to pathnames of .asd files")
10650
10651 ;; Saving the user-provided parameter to the source-registry, if any,
10652 ;; so we can recompute the source-registry after code upgrade.
10653 (defvar *source-registry-parameter* nil)
10654
10655 (defun source-registry-initialized-p ()
10656 (typep *source-registry* 'hash-table))
10657
10658 (defun clear-source-registry ()
10659 "Undoes any initialization of the source registry."
10660 (setf *source-registry* nil)
10661 (values))
10662 (register-clear-configuration-hook 'clear-source-registry)
10663
10664 (defparameter *wild-asd*
10665 (make-pathname :directory nil :name *wild* :type "asd" :version :newest))
10666
10667 (defun directory-asd-files (directory)
10668 (directory-files directory *wild-asd*))
10669
10670 (defun collect-asds-in-directory (directory collect)
10671 (let ((asds (directory-asd-files directory)))
10672 (map () collect asds)
10673 asds))
10674
10675 (defvar *recurse-beyond-asds* t
10676 "Should :tree entries of the source-registry recurse in subdirectories
10677 after having found a .asd file? True by default.")
10678
10679 ;; When walking down a filesystem tree, if in a directory there is a .cl-source-registry.cache,
10680 ;; read its contents instead of further recursively querying the filesystem.
10681 (defun process-source-registry-cache (directory collect)
10682 (let ((cache (ignore-errors
10683 (safe-read-file-form (subpathname directory ".cl-source-registry.cache")))))
10684 (when (and (listp cache) (eq :source-registry-cache (first cache)))
10685 (loop :for s :in (rest cache) :do (funcall collect (subpathname directory s)))
10686 t)))
10687
10688 (defun collect-sub*directories-asd-files
10689 (directory &key (exclude *default-source-registry-exclusions*) collect
10690 (recurse-beyond-asds *recurse-beyond-asds*) ignore-cache)
10691 (let ((visited (make-hash-table :test 'equalp)))
10692 (flet ((collectp (dir)
10693 (unless (and (not ignore-cache) (process-source-registry-cache directory collect))
10694 (let ((asds (collect-asds-in-directory dir collect)))
10695 (or recurse-beyond-asds (not asds)))))
10696 (recursep (x) ; x will be a directory pathname
10697 (and
10698 (not (member (car (last (pathname-directory x))) exclude :test #'equal))
10699 (flet ((pathname-key (x)
10700 (namestring (truename* x))))
10701 (let ((visitedp (gethash (pathname-key x) visited)))
10702 (if visitedp nil
10703 (setf (gethash (pathname-key x) visited) t)))))))
10704 (collect-sub*directories directory #'collectp #'recursep (constantly nil)))))
10705
10706
10707 ;;; Validate the configuration forms
10708
10709 (defun validate-source-registry-directive (directive)
10710 (or (member directive '(:default-registry))
10711 (and (consp directive)
10712 (let ((rest (rest directive)))
10713 (case (first directive)
10714 ((:include :directory :tree)
10715 (and (length=n-p rest 1)
10716 (location-designator-p (first rest))))
10717 ((:exclude :also-exclude)
10718 (every #'stringp rest))
10719 ((:default-registry)
10720 (null rest)))))))
10721
10722 (defun validate-source-registry-form (form &key location)
10723 (validate-configuration-form
10724 form :source-registry 'validate-source-registry-directive
10725 :location location :invalid-form-reporter 'invalid-source-registry))
10726
10727 (defun validate-source-registry-file (file)
10728 (validate-configuration-file
10729 file 'validate-source-registry-form :description "a source registry"))
10730
10731 (defun validate-source-registry-directory (directory)
10732 (validate-configuration-directory
10733 directory :source-registry 'validate-source-registry-directive
10734 :invalid-form-reporter 'invalid-source-registry))
10735
10736
10737 ;;; Parse the configuration string
10738
10739 (defun parse-source-registry-string (string &key location)
10740 (cond
10741 ((or (null string) (equal string ""))
10742 '(:source-registry :inherit-configuration))
10743 ((not (stringp string))
10744 (error (compatfmt "~@<Environment string isn't: ~3i~_~S~@:>") string))
10745 ((find (char string 0) "\"(")
10746 (validate-source-registry-form (read-from-string string) :location location))
10747 (t
10748 (loop
10749 :with inherit = nil
10750 :with directives = ()
10751 :with start = 0
10752 :with end = (length string)
10753 :with separator = (inter-directory-separator)
10754 :for pos = (position separator string :start start) :do
10755 (let ((s (subseq string start (or pos end))))
10756 (flet ((check (dir)
10757 (unless (absolute-pathname-p dir)
10758 (error (compatfmt "~@<source-registry string must specify absolute pathnames: ~3i~_~S~@:>") string))
10759 dir))
10760 (cond
10761 ((equal "" s) ; empty element: inherit
10762 (when inherit
10763 (error (compatfmt "~@<Only one inherited configuration allowed: ~3i~_~S~@:>")
10764 string))
10765 (setf inherit t)
10766 (push ':inherit-configuration directives))
10767 ((string-suffix-p s "//") ;; TODO: allow for doubling of separator even outside Unix?
10768 (push `(:tree ,(check (subseq s 0 (- (length s) 2)))) directives))
10769 (t
10770 (push `(:directory ,(check s)) directives))))
10771 (cond
10772 (pos
10773 (setf start (1+ pos)))
10774 (t
10775 (unless inherit
10776 (push '(:ignore-inherited-configuration) directives))
10777 (return `(:source-registry ,@(nreverse directives))))))))))
10778
10779 (defun register-asd-directory (directory &key recurse exclude collect)
10780 (if (not recurse)
10781 (collect-asds-in-directory directory collect)
10782 (collect-sub*directories-asd-files
10783 directory :exclude exclude :collect collect)))
10784
10785 (defparameter* *default-source-registries*
10786 '(environment-source-registry
10787 user-source-registry
10788 user-source-registry-directory
10789 default-user-source-registry
10790 system-source-registry
10791 system-source-registry-directory
10792 default-system-source-registry)
10793 "List of default source registries" "3.1.0.102")
10794
10795 (defparameter *source-registry-file* (parse-unix-namestring "common-lisp/source-registry.conf"))
10796 (defparameter *source-registry-directory* (parse-unix-namestring "common-lisp/source-registry.conf.d/"))
10797
10798 (defun wrapping-source-registry ()
10799 `(:source-registry
10800 #+(or clasp ecl sbcl) (:tree ,(resolve-symlinks* (lisp-implementation-directory)))
10801 :inherit-configuration
10802 #+mkcl (:tree ,(translate-logical-pathname "SYS:"))
10803 #+cmucl (:tree #p"modules:")
10804 #+scl (:tree #p"file://modules/")))
10805 (defun default-user-source-registry ()
10806 `(:source-registry
10807 (:tree (:home "common-lisp/"))
10808 #+sbcl (:directory (:home ".sbcl/systems/"))
10809 (:directory ,(xdg-data-home "common-lisp/systems/"))
10810 (:tree ,(xdg-data-home "common-lisp/source/"))
10811 :inherit-configuration))
10812 (defun default-system-source-registry ()
10813 `(:source-registry
10814 ,@(loop :for dir :in (xdg-data-dirs "common-lisp/")
10815 :collect `(:directory (,dir "systems/"))
10816 :collect `(:tree (,dir "source/")))
10817 :inherit-configuration))
10818 (defun user-source-registry (&key (direction :input))
10819 (xdg-config-pathname *source-registry-file* direction))
10820 (defun system-source-registry (&key (direction :input))
10821 (find-preferred-file (system-config-pathnames *source-registry-file*)
10822 :direction direction))
10823 (defun user-source-registry-directory (&key (direction :input))
10824 (xdg-config-pathname *source-registry-directory* direction))
10825 (defun system-source-registry-directory (&key (direction :input))
10826 (find-preferred-file (system-config-pathnames *source-registry-directory*)
10827 :direction direction))
10828 (defun environment-source-registry ()
10829 (getenv "CL_SOURCE_REGISTRY"))
10830
10831
10832 ;;; Process the source-registry configuration
10833
10834 (defgeneric* (process-source-registry) (spec &key inherit register))
10835
10836 (defun* (inherit-source-registry) (inherit &key register)
10837 (when inherit
10838 (process-source-registry (first inherit) :register register :inherit (rest inherit))))
10839
10840 (defun* (process-source-registry-directive) (directive &key inherit register)
10841 (destructuring-bind (kw &rest rest) (if (consp directive) directive (list directive))
10842 (ecase kw
10843 ((:include)
10844 (destructuring-bind (pathname) rest
10845 (process-source-registry (resolve-location pathname) :inherit nil :register register)))
10846 ((:directory)
10847 (destructuring-bind (pathname) rest
10848 (when pathname
10849 (funcall register (resolve-location pathname :ensure-directory t)))))
10850 ((:tree)
10851 (destructuring-bind (pathname) rest
10852 (when pathname
10853 (funcall register (resolve-location pathname :ensure-directory t)
10854 :recurse t :exclude *source-registry-exclusions*))))
10855 ((:exclude)
10856 (setf *source-registry-exclusions* rest))
10857 ((:also-exclude)
10858 (appendf *source-registry-exclusions* rest))
10859 ((:default-registry)
10860 (inherit-source-registry
10861 '(default-user-source-registry default-system-source-registry) :register register))
10862 ((:inherit-configuration)
10863 (inherit-source-registry inherit :register register))
10864 ((:ignore-inherited-configuration)
10865 nil)))
10866 nil)
10867
10868 (defmethod process-source-registry ((x symbol) &key inherit register)
10869 (process-source-registry (funcall x) :inherit inherit :register register))
10870 (defmethod process-source-registry ((pathname pathname) &key inherit register)
10871 (cond
10872 ((directory-pathname-p pathname)
10873 (let ((*here-directory* (resolve-symlinks* pathname)))
10874 (process-source-registry (validate-source-registry-directory pathname)
10875 :inherit inherit :register register)))
10876 ((probe-file* pathname :truename *resolve-symlinks*)
10877 (let ((*here-directory* (pathname-directory-pathname pathname)))
10878 (process-source-registry (validate-source-registry-file pathname)
10879 :inherit inherit :register register)))
10880 (t
10881 (inherit-source-registry inherit :register register))))
10882 (defmethod process-source-registry ((string string) &key inherit register)
10883 (process-source-registry (parse-source-registry-string string)
10884 :inherit inherit :register register))
10885 (defmethod process-source-registry ((x null) &key inherit register)
10886 (inherit-source-registry inherit :register register))
10887 (defmethod process-source-registry ((form cons) &key inherit register)
10888 (let ((*source-registry-exclusions* *default-source-registry-exclusions*))
10889 (dolist (directive (cdr (validate-source-registry-form form)))
10890 (process-source-registry-directive directive :inherit inherit :register register))))
10891
10892
10893 ;; Flatten the user-provided configuration into an ordered list of directories and trees
10894 (defun flatten-source-registry (&optional (parameter *source-registry-parameter*))
10895 (remove-duplicates
10896 (while-collecting (collect)
10897 (with-pathname-defaults () ;; be location-independent
10898 (inherit-source-registry
10899 `(wrapping-source-registry
10900 ,parameter
10901 ,@*default-source-registries*)
10902 :register #'(lambda (directory &key recurse exclude)
10903 (collect (list directory :recurse recurse :exclude exclude))))))
10904 :test 'equal :from-end t))
10905
10906 ;; Will read the configuration and initialize all internal variables.
10907 (defun compute-source-registry (&optional (parameter *source-registry-parameter*)
10908 (registry *source-registry*))
10909 (dolist (entry (flatten-source-registry parameter))
10910 (destructuring-bind (directory &key recurse exclude) entry
10911 (let* ((h (make-hash-table :test 'equal))) ; table to detect duplicates
10912 (register-asd-directory
10913 directory :recurse recurse :exclude exclude :collect
10914 #'(lambda (asd)
10915 (let* ((name (pathname-name asd))
10916 (name (if (typep asd 'logical-pathname)
10917 ;; logical pathnames are upper-case,
10918 ;; at least in the CLHS and on SBCL,
10919 ;; yet (coerce-name :foo) is lower-case.
10920 ;; won't work well with (load-system "Foo")
10921 ;; instead of (load-system 'foo)
10922 (string-downcase name)
10923 name)))
10924 (cond
10925 ((gethash name registry) ; already shadowed by something else
10926 nil)
10927 ((gethash name h) ; conflict at current level
10928 (when *verbose-out*
10929 (warn (compatfmt "~@<In source-registry entry ~A~@[/~*~] ~
10930 found several entries for ~A - picking ~S over ~S~:>")
10931 directory recurse name (gethash name h) asd)))
10932 (t
10933 (setf (gethash name registry) asd)
10934 (setf (gethash name h) asd))))))
10935 h)))
10936 (values))
10937
10938 (defun initialize-source-registry (&optional (parameter *source-registry-parameter*))
10939 ;; Record the parameter used to configure the registry
10940 (setf *source-registry-parameter* parameter)
10941 ;; Clear the previous registry database:
10942 (setf *source-registry* (make-hash-table :test 'equal))
10943 ;; Do it!
10944 (compute-source-registry parameter))
10945
10946 ;; Checks an initial variable to see whether the state is initialized
10947 ;; or cleared. In the former case, return current configuration; in
10948 ;; the latter, initialize. ASDF will call this function at the start
10949 ;; of (asdf:find-system) to make sure the source registry is initialized.
10950 ;; However, it will do so *without* a parameter, at which point it
10951 ;; will be too late to provide a parameter to this function, though
10952 ;; you may override the configuration explicitly by calling
10953 ;; initialize-source-registry directly with your parameter.
10954 (defun ensure-source-registry (&optional parameter)
10955 (unless (source-registry-initialized-p)
10956 (initialize-source-registry parameter))
10957 (values))
10958
10959 (defun sysdef-source-registry-search (system)
10960 (ensure-source-registry)
10961 (values (gethash (primary-system-name system) *source-registry*))))
10962
10963
10964 ;;;; -------------------------------------------------------------------------
10965 ;;;; Defsystem
10966
10967 (uiop/package:define-package :asdf/parse-defsystem
10968 (:recycle :asdf/parse-defsystem :asdf/defsystem :asdf)
10969 (:nicknames :asdf/defsystem) ;; previous name, to be compatible with, in case anyone cares
10970 (:use :uiop/common-lisp :asdf/driver :asdf/upgrade
10971 :asdf/cache :asdf/component :asdf/system
10972 :asdf/find-system :asdf/find-component :asdf/action :asdf/lisp-action :asdf/operate)
10973 (:import-from :asdf/system #:depends-on #:weakly-depends-on)
10974 (:export
10975 #:defsystem #:register-system-definition
10976 #:class-for-type #:*default-component-class*
10977 #:determine-system-directory #:parse-component-form
10978 #:non-toplevel-system #:non-system-system
10979 #:sysdef-error-component #:check-component-input))
10980 (in-package :asdf/parse-defsystem)
10981
10982 ;;; Pathname
10983 (with-upgradability ()
10984 (defun determine-system-directory (pathname)
10985 ;; The defsystem macro calls this function to determine the pathname of a system as follows:
10986 ;; 1. If the pathname argument is an pathname object (NOT a namestring),
10987 ;; that is already an absolute pathname, return it.
10988 ;; 2. Otherwise, the directory containing the LOAD-PATHNAME
10989 ;; is considered (as deduced from e.g. *LOAD-PATHNAME*), and
10990 ;; if it is indeed available and an absolute pathname, then
10991 ;; the PATHNAME argument is normalized to a relative pathname
10992 ;; as per PARSE-UNIX-NAMESTRING (with ENSURE-DIRECTORY T)
10993 ;; and merged into that DIRECTORY as per SUBPATHNAME.
10994 ;; Note: avoid *COMPILE-FILE-PATHNAME* because the .asd is loaded as source,
10995 ;; but may be from within the EVAL-WHEN of a file compilation.
10996 ;; If no absolute pathname was found, we return NIL.
10997 (check-type pathname (or null string pathname))
10998 (pathname-directory-pathname
10999 (resolve-symlinks*
11000 (ensure-absolute-pathname
11001 (parse-unix-namestring pathname :type :directory)
11002 #'(lambda () (ensure-absolute-pathname
11003 (load-pathname) 'get-pathname-defaults nil))
11004 nil)))))
11005
11006
11007 ;;; Component class
11008 (with-upgradability ()
11009 ;; What :file gets interpreted as, unless overridden by a :default-component-class
11010 (defvar *default-component-class* 'cl-source-file)
11011
11012 (defun class-for-type (parent type)
11013 (or (coerce-class type :package :asdf/interface :super 'component :error nil)
11014 (and (eq type :file)
11015 (coerce-class
11016 (or (loop :for p = parent :then (component-parent p) :while p
11017 :thereis (module-default-component-class p))
11018 *default-component-class*)
11019 :package :asdf/interface :super 'component :error nil))
11020 (sysdef-error "don't recognize component type ~S" type))))
11021
11022
11023 ;;; Check inputs
11024 (with-upgradability ()
11025 (define-condition non-system-system (system-definition-error)
11026 ((name :initarg :name :reader non-system-system-name)
11027 (class-name :initarg :class-name :reader non-system-system-class-name))
11028 (:report (lambda (c s)
11029 (format s (compatfmt "~@<Error while defining system ~S: class ~S isn't a subclass of ~S~@:>")
11030 (non-system-system-name c) (non-system-system-class-name c) 'system))))
11031
11032 (define-condition non-toplevel-system (system-definition-error)
11033 ((parent :initarg :parent :reader non-toplevel-system-parent)
11034 (name :initarg :name :reader non-toplevel-system-name))
11035 (:report (lambda (c s)
11036 (format s (compatfmt "~@<Error while defining system: component ~S claims to have a system ~S as a child~@:>")
11037 (non-toplevel-system-parent c) (non-toplevel-system-name c)))))
11038
11039 (defun sysdef-error-component (msg type name value)
11040 (sysdef-error (strcat msg (compatfmt "~&~@<The value specified for ~(~A~) ~A is ~S~@:>"))
11041 type name value))
11042
11043 (defun check-component-input (type name weakly-depends-on
11044 depends-on components)
11045 "A partial test of the values of a component."
11046 (unless (listp depends-on)
11047 (sysdef-error-component ":depends-on must be a list."
11048 type name depends-on))
11049 (unless (listp weakly-depends-on)
11050 (sysdef-error-component ":weakly-depends-on must be a list."
11051 type name weakly-depends-on))
11052 (unless (listp components)
11053 (sysdef-error-component ":components must be NIL or a list of components."
11054 type name components)))
11055
11056 ;; Given a form used as :version specification, in the context of a system definition
11057 ;; in a file at PATHNAME, for given COMPONENT with given PARENT, normalize the form
11058 ;; to an acceptable ASDF-format version.
11059 (defun* (normalize-version) (form &key pathname component parent)
11060 (labels ((invalid (&optional (continuation "using NIL instead"))
11061 (warn (compatfmt "~@<Invalid :version specifier ~S~@[ for component ~S~]~@[ in ~S~]~@[ from file ~S~]~@[, ~A~]~@:>")
11062 form component parent pathname continuation))
11063 (invalid-parse (control &rest args)
11064 (unless (if-let (target (find-component parent component)) (builtin-system-p target))
11065 (apply 'warn control args)
11066 (invalid))))
11067 (if-let (v (typecase form
11068 ((or string null) form)
11069 (real
11070 (invalid "Substituting a string")
11071 (format nil "~D" form)) ;; 1.0 becomes "1.0"
11072 (cons
11073 (case (first form)
11074 ((:read-file-form)
11075 (destructuring-bind (subpath &key (at 0)) (rest form)
11076 (safe-read-file-form (subpathname pathname subpath)
11077 :at at :package :asdf-user)))
11078 ((:read-file-line)
11079 (destructuring-bind (subpath &key (at 0)) (rest form)
11080 (safe-read-file-line (subpathname pathname subpath)
11081 :at at)))
11082 (otherwise
11083 (invalid))))
11084 (t
11085 (invalid))))
11086 (if-let (pv (parse-version v #'invalid-parse))
11087 (unparse-version pv)
11088 (invalid))))))
11089
11090
11091 ;;; "inline methods"
11092 (with-upgradability ()
11093 (defparameter* +asdf-methods+
11094 '(perform-with-restarts perform explain output-files operation-done-p))
11095
11096 (defun %remove-component-inline-methods (component)
11097 (dolist (name +asdf-methods+)
11098 (map ()
11099 ;; this is inefficient as most of the stored
11100 ;; methods will not be for this particular gf
11101 ;; But this is hardly performance-critical
11102 #'(lambda (m)
11103 (remove-method (symbol-function name) m))
11104 (component-inline-methods component)))
11105 (component-inline-methods component) nil)
11106
11107 (defun %define-component-inline-methods (ret rest)
11108 (loop* :for (key value) :on rest :by #'cddr
11109 :for name = (and (keywordp key) (find key +asdf-methods+ :test 'string=))
11110 :when name :do
11111 (destructuring-bind (op &rest body) value
11112 (loop :for arg = (pop body)
11113 :while (atom arg)
11114 :collect arg :into qualifiers
11115 :finally
11116 (destructuring-bind (o c) arg
11117 (pushnew
11118 (eval `(defmethod ,name ,@qualifiers ((,o ,op) (,c (eql ,ret))) ,@body))
11119 (component-inline-methods ret)))))))
11120
11121 (defun %refresh-component-inline-methods (component rest)
11122 ;; clear methods, then add the new ones
11123 (%remove-component-inline-methods component)
11124 (%define-component-inline-methods component rest)))
11125
11126
11127 ;;; Main parsing function
11128 (with-upgradability ()
11129 (defun parse-dependency-def (dd)
11130 (if (listp dd)
11131 (case (first dd)
11132 (:feature
11133 (unless (= (length dd) 3)
11134 (sysdef-error "Ill-formed feature dependency: ~s" dd))
11135 (let ((embedded (parse-dependency-def (third dd))))
11136 `(:feature ,(second dd) ,embedded)))
11137 (feature
11138 (sysdef-error "`feature' has been removed from the dependency spec language of ASDF. Use :feature instead in ~s." dd))
11139 (:require
11140 (unless (= (length dd) 2)
11141 (sysdef-error "Ill-formed require dependency: ~s" dd))
11142 dd)
11143 (:version
11144 (unless (= (length dd) 3)
11145 (sysdef-error "Ill-formed version dependency: ~s" dd))
11146 `(:version ,(coerce-name (second dd)) ,(third dd)))
11147 (otherwise (sysdef-error "Ill-formed dependency: ~s" dd)))
11148 (coerce-name dd)))
11149
11150 (defun parse-dependency-defs (dd-list)
11151 "Parse the dependency defs in DD-LIST into canonical form by translating all
11152 system names contained using COERCE-NAME. Return the result."
11153 (mapcar 'parse-dependency-def dd-list))
11154
11155 (defun (parse-component-form) (parent options &key previous-serial-component)
11156 (destructuring-bind
11157 (type name &rest rest &key
11158 (builtin-system-p () bspp)
11159 ;; the following list of keywords is reproduced below in the
11160 ;; remove-plist-keys form. important to keep them in sync
11161 components pathname perform explain output-files operation-done-p
11162 weakly-depends-on depends-on serial
11163 do-first if-component-dep-fails version
11164 ;; list ends
11165 &allow-other-keys) options
11166 (declare (ignore perform explain output-files operation-done-p builtin-system-p))
11167 (check-component-input type name weakly-depends-on depends-on components)
11168 (when (and parent
11169 (find-component parent name)
11170 (not ;; ignore the same object when rereading the defsystem
11171 (typep (find-component parent name)
11172 (class-for-type parent type))))
11173 (error 'duplicate-names :name name))
11174 (when do-first (error "DO-FIRST is not supported anymore as of ASDF 3"))
11175 (let* ((name (coerce-name name))
11176 (args `(:name ,name
11177 :pathname ,pathname
11178 ,@(when parent `(:parent ,parent))
11179 ,@(remove-plist-keys
11180 '(:components :pathname :if-component-dep-fails :version
11181 :perform :explain :output-files :operation-done-p
11182 :weakly-depends-on :depends-on :serial)
11183 rest)))
11184 (component (find-component parent name))
11185 (class (class-for-type parent type)))
11186 (when (and parent (subtypep class 'system))
11187 (error 'non-toplevel-system :parent parent :name name))
11188 (if component ; preserve identity
11189 (apply 'reinitialize-instance component args)
11190 (setf component (apply 'make-instance class args)))
11191 (component-pathname component) ; eagerly compute the absolute pathname
11192 (when (typep component 'system)
11193 ;; cache information for introspection
11194 (setf (slot-value component 'depends-on)
11195 (parse-dependency-defs depends-on)
11196 (slot-value component 'weakly-depends-on)
11197 ;; these must be a list of systems, cannot be features or versioned systems
11198 (mapcar 'coerce-name weakly-depends-on)))
11199 (let ((sysfile (system-source-file (component-system component)))) ;; requires the previous
11200 (when (and (typep component 'system) (not bspp))
11201 (setf (builtin-system-p component) (lisp-implementation-pathname-p sysfile)))
11202 (setf version (normalize-version version :component name :parent parent :pathname sysfile)))
11203 ;; Don't use the accessor: kluge to avoid upgrade issue on CCL 1.8.
11204 ;; A better fix is required.
11205 (setf (slot-value component 'version) version)
11206 (when (typep component 'parent-component)
11207 (setf (component-children component)
11208 (loop
11209 :with previous-component = nil
11210 :for c-form :in components
11211 :for c = (parse-component-form component c-form
11212 :previous-serial-component previous-component)
11213 :for name = (component-name c)
11214 :collect c
11215 :when serial :do (setf previous-component name)))
11216 (compute-children-by-name component))
11217 (when previous-serial-component
11218 (push previous-serial-component depends-on))
11219 (when weakly-depends-on
11220 ;; ASDF4: deprecate this feature and remove it.
11221 (appendf depends-on
11222 (remove-if (complement #'(lambda (x) (find-system x nil))) weakly-depends-on)))
11223 ;; Used by POIU. ASDF4: rename to component-depends-on?
11224 (setf (component-sideway-dependencies component) depends-on)
11225 (%refresh-component-inline-methods component rest)
11226 (when if-component-dep-fails
11227 (error "The system definition for ~S uses deprecated ~
11228 ASDF option :IF-COMPONENT-DEP-FAILS. ~
11229 Starting with ASDF 3, please use :IF-FEATURE instead"
11230 (coerce-name (component-system component))))
11231 component)))
11232
11233 (defun register-system-definition
11234 (name &rest options &key pathname (class 'system) (source-file () sfp)
11235 defsystem-depends-on &allow-other-keys)
11236 ;; The system must be registered before we parse the body,
11237 ;; otherwise we recur when trying to find an existing system
11238 ;; of the same name to reuse options (e.g. pathname) from.
11239 ;; To avoid infinite recursion in cases where you defsystem a system
11240 ;; that is registered to a different location to find-system,
11241 ;; we also need to remember it in the asdf-cache.
11242 (with-asdf-cache ()
11243 (let* ((name (coerce-name name))
11244 (source-file (if sfp source-file (resolve-symlinks* (load-pathname))))
11245 ;; NB: handle defsystem-depends-on BEFORE to create the system object,
11246 ;; so that in case it fails, there is no incomplete object polluting the build.
11247 (checked-defsystem-depends-on
11248 (let* ((dep-forms (parse-dependency-defs defsystem-depends-on))
11249 (deps (loop :for spec :in dep-forms
11250 :when (resolve-dependency-spec nil spec)
11251 :collect :it)))
11252 (load-systems* deps)
11253 dep-forms))
11254 (registered (system-registered-p name))
11255 (registered! (if registered
11256 (rplaca registered (get-file-stamp source-file))
11257 (register-system
11258 (make-instance 'system :name name :source-file source-file))))
11259 (system (reset-system (cdr registered!)
11260 :name name :source-file source-file))
11261 (component-options
11262 (append
11263 (remove-plist-keys '(:defsystem-depends-on :class) options)
11264 ;; cache defsystem-depends-on in canonical form
11265 (when checked-defsystem-depends-on
11266 `(:defsystem-depends-on ,checked-defsystem-depends-on)))))
11267 ;; This works hand in hand with asdf/find-system:find-system-if-being-defined:
11268 (set-asdf-cache-entry `(find-system ,name) (list system))
11269 ;; We change-class AFTER we loaded the defsystem-depends-on
11270 ;; since the class might be defined as part of those.
11271 (let ((class (class-for-type nil class)))
11272 (unless (subtypep class 'system)
11273 (error 'non-system-system :name name :class-name (class-name class)))
11274 (unless (eq (type-of system) class)
11275 (change-class system class)))
11276 (parse-component-form
11277 nil (list*
11278 :module name
11279 :pathname (determine-system-directory pathname)
11280 component-options)))))
11281
11282 (defmacro defsystem (name &body options)
11283 `(apply 'register-system-definition ',name ',options)))
11284 ;;;; -------------------------------------------------------------------------
11285 ;;;; ASDF-Bundle
11286
11287 (uiop/package:define-package :asdf/bundle
11288 (:recycle :asdf/bundle :asdf)
11289 (:use :uiop/common-lisp :uiop :asdf/upgrade
11290 :asdf/component :asdf/system :asdf/find-system :asdf/find-component :asdf/operation
11291 :asdf/action :asdf/lisp-action :asdf/plan :asdf/operate :asdf/defsystem)
11292 (:export
11293 #:bundle-op #:bundle-type #:program-system
11294 #:bundle-system #:bundle-pathname-type #:direct-dependency-files
11295 #:monolithic-op #:monolithic-bundle-op #:operation-monolithic-p
11296 #:basic-compile-bundle-op #:prepare-bundle-op
11297 #:compile-bundle-op #:load-bundle-op #:monolithic-compile-bundle-op #:monolithic-load-bundle-op
11298 #:lib-op #:monolithic-lib-op
11299 #:dll-op #:monolithic-dll-op
11300 #:deliver-asd-op #:monolithic-deliver-asd-op
11301 #:program-op #:image-op #:compiled-file #:precompiled-system #:prebuilt-system
11302 #:user-system-p #:user-system #:trivial-system-p
11303 #:make-build
11304 #:build-args #:name-suffix #:prologue-code #:epilogue-code #:static-library))
11305 (in-package :asdf/bundle)
11306
11307 (with-upgradability ()
11308 (defclass bundle-op (basic-compile-op)
11309 ;; NB: use of instance-allocated slots for operations is DEPRECATED
11310 ;; and only supported in a temporary fashion for backward compatibility.
11311 ;; Supported replacement: Define slots on program-system instead.
11312 ((build-args :initarg :args :initform nil :accessor extra-build-args)
11313 (name-suffix :initarg :name-suffix :initform nil)
11314 (bundle-type :initform :no-output-file :reader bundle-type)
11315 #+(or clasp ecl) (lisp-files :initform nil :accessor extra-object-files))
11316 (:documentation "base class for operations that bundle outputs from multiple components"))
11317
11318 (defclass monolithic-op (operation) ()
11319 (:documentation "A MONOLITHIC operation operates on a system *and all of its
11320 dependencies*. So, for example, a monolithic concatenate operation will
11321 concatenate together a system's components and all of its dependencies, but a
11322 simple concatenate operation will concatenate only the components of the system
11323 itself."))
11324
11325 (defclass monolithic-bundle-op (monolithic-op bundle-op)
11326 ;; Old style way of specifying prologue and epilogue on ECL: in the monolithic operation.
11327 ;; DEPRECATED. Supported replacement: Define slots on program-system instead.
11328 ((prologue-code :initform nil :accessor prologue-code)
11329 (epilogue-code :initform nil :accessor epilogue-code))
11330 (:documentation "operations that are both monolithic-op and bundle-op"))
11331
11332 (defclass program-system (system)
11333 ;; New style (ASDF3.1) way of specifying prologue and epilogue on ECL: in the system
11334 ((prologue-code :initform nil :initarg :prologue-code :reader prologue-code)
11335 (epilogue-code :initform nil :initarg :epilogue-code :reader epilogue-code)
11336 (no-uiop :initform nil :initarg :no-uiop :reader no-uiop)
11337 (prefix-lisp-object-files :initarg :prefix-lisp-object-files
11338 :initform nil :accessor prefix-lisp-object-files)
11339 (postfix-lisp-object-files :initarg :postfix-lisp-object-files
11340 :initform nil :accessor postfix-lisp-object-files)
11341 (extra-object-files :initarg :extra-object-files
11342 :initform nil :accessor extra-object-files)
11343 (extra-build-args :initarg :extra-build-args
11344 :initform nil :accessor extra-build-args)))
11345
11346 (defmethod prologue-code ((x t)) nil)
11347 (defmethod epilogue-code ((x t)) nil)
11348 (defmethod no-uiop ((x t)) t)
11349 (defmethod prefix-lisp-object-files ((x t)) nil)
11350 (defmethod postfix-lisp-object-files ((x t)) nil)
11351 (defmethod extra-object-files ((x t)) nil)
11352 (defmethod extra-build-args ((x t)) nil)
11353
11354 (defclass link-op (bundle-op) ()
11355 (:documentation "Abstract operation for linking files together"))
11356
11357 (defclass gather-op (bundle-op)
11358 ;; TODO: rename the slot and reader gather-op to gather-operation
11359 ((gather-op :initform nil :allocation :class :reader gather-op)
11360 (gather-type :initform :no-output-file :allocation :class :reader gather-type))
11361 (:documentation "Abstract operation for gathering many input files from a system"))
11362
11363 (defun operation-monolithic-p (op)
11364 (typep op 'monolithic-op))
11365
11366 ;; Dependencies of a gather-op are the actions of the dependent
11367 ;; operation for all the (sorted) required components for loading
11368 ;; the system. Monolithic operations typically use lib-op as the
11369 ;; dependent operation, and all system-level dependencies as
11370 ;; required components. Non-monolithic operations typically use
11371 ;; basic-compile-op as the dependent operation, and all transitive
11372 ;; sub-components as required components (excluding other systems).
11373 (defmethod component-depends-on ((o gather-op) (s system))
11374 (let* ((mono (operation-monolithic-p o))
11375 (go (make-operation (or (gather-op o) 'compile-op)))
11376 (bundle-p (typep go 'bundle-op))
11377 ;; In a non-mono operation, don't recurse to other systems.
11378 ;; In a mono operation gathering bundles, don't recurse inside systems.
11379 (component-type (if mono (if bundle-p 'system t) '(not system)))
11380 ;; In the end, only keep system bundles or non-system bundles, depending.
11381 (keep-component (if bundle-p 'system '(not system)))
11382 (deps
11383 (required-components
11384 s :other-systems mono :component-type component-type :keep-component keep-component
11385 :goal-operation (find-operation o 'load-op)
11386 :keep-operation 'basic-compile-op)))
11387 `((,go ,@deps) ,@(call-next-method))))
11388
11389 ;; Create a single fasl for the entire library
11390 (defclass basic-compile-bundle-op (bundle-op)
11391 ((gather-type :initform #-(or clasp ecl mkcl) :fasl #+(or clasp ecl mkcl) :object
11392 :allocation :class)
11393 (bundle-type :initform :fasl :allocation :class))
11394 (:documentation "Base class for compiling into a bundle"))
11395
11396 ;; Analog to prepare-op, for load-bundle-op and compile-bundle-op
11397 (defclass prepare-bundle-op (sideway-operation)
11398 ((sideway-operation
11399 :initform #+(or clasp ecl mkcl) 'load-bundle-op #-(or clasp ecl mkcl) 'load-op
11400 :allocation :class))
11401 (:documentation "Operation class for loading the bundles of a system's dependencies"))
11402
11403 (defclass lib-op (link-op gather-op non-propagating-operation)
11404 ((gather-type :initform :object :allocation :class)
11405 (bundle-type :initform :lib :allocation :class))
11406 (:documentation "Compile the system and produce a linkable static library (.a/.lib)
11407 for all the linkable object files associated with the system. Compare with DLL-OP.
11408
11409 On most implementations, these object files only include extensions to the runtime
11410 written in C or another language with a compiler producing linkable object files.
11411 On CLASP, ECL, MKCL, these object files _also_ include the contents of Lisp files
11412 themselves. In any case, this operation will produce what you need to further build
11413 a static runtime for your system, or a dynamic library to load in an existing runtime."))
11414
11415 ;; What works: on ECL, CLASP(?), MKCL, we link many .o files from the system into the .so;
11416 ;; on other implementations, we combine the .fasl files into one.
11417 (defclass compile-bundle-op (basic-compile-bundle-op selfward-operation gather-op
11418 #+(or clasp ecl mkcl) link-op)
11419 ((selfward-operation :initform '(prepare-bundle-op) :allocation :class))
11420 (:documentation "This operator is an alternative to COMPILE-OP. Build a system
11421 and all of its dependencies, but build only a single (\"monolithic\") FASL, instead
11422 of one per source file, which may be more resource efficient. That monolithic
11423 FASL should be loaded with LOAD-BUNDLE-OP, rather than LOAD-OP."))
11424
11425 (defclass load-bundle-op (basic-load-op selfward-operation)
11426 ((selfward-operation :initform '(prepare-bundle-op compile-bundle-op) :allocation :class))
11427 (:documentation "This operator is an alternative to LOAD-OP. Build a system
11428 and all of its dependencies, using COMPILE-BUNDLE-OP. The difference with
11429 respect to LOAD-OP is that it builds only a single FASL, which may be
11430 faster and more resource efficient."))
11431
11432 ;; NB: since the monolithic-op's can't be sideway-operation's,
11433 ;; if we wanted lib-op, dll-op, deliver-asd-op to be sideway-operation's,
11434 ;; we'd have to have the monolithic-op not inherit from the main op,
11435 ;; but instead inherit from a basic-FOO-op as with basic-compile-bundle-op above.
11436
11437 (defclass dll-op (link-op gather-op non-propagating-operation)
11438 ((gather-type :initform :object :allocation :class)
11439 (bundle-type :initform :dll :allocation :class))
11440 (:documentation "Compile the system and produce a dynamic loadable library (.so/.dll)
11441 for all the linkable object files associated with the system. Compare with LIB-OP."))
11442
11443 (defclass deliver-asd-op (basic-compile-op selfward-operation)
11444 ((selfward-operation
11445 ;; TODO: implement link-op on all implementations, and make that
11446 ;; '(compile-bundle-op lib-op #-(or clasp ecl mkcl) dll-op)
11447 :initform '(compile-bundle-op #+(or clasp ecl mkcl) lib-op)
11448 :allocation :class))
11449 (:documentation "produce an asd file for delivering the system as a single fasl"))
11450
11451
11452 (defclass monolithic-deliver-asd-op (monolithic-bundle-op deliver-asd-op)
11453 ((selfward-operation
11454 ;; TODO: implement link-op on all implementations, and make that
11455 ;; '(monolithic-compile-bundle-op monolithic-lib-op #-(or clasp ecl mkcl) monolithic-dll-op)
11456 :initform '(monolithic-compile-bundle-op #+(or clasp ecl mkcl) monolithic-lib-op)
11457 :allocation :class))
11458 (:documentation "produce fasl and asd files for combined system and dependencies."))
11459
11460 (defclass monolithic-compile-bundle-op
11461 (monolithic-bundle-op basic-compile-bundle-op
11462 #+(or clasp ecl mkcl) link-op gather-op non-propagating-operation)
11463 ()
11464 (:documentation "Create a single fasl for the system and its dependencies."))
11465
11466 (defclass monolithic-load-bundle-op (monolithic-bundle-op load-bundle-op)
11467 ((selfward-operation :initform 'monolithic-compile-bundle-op :allocation :class))
11468 (:documentation "Load a single fasl for the system and its dependencies."))
11469
11470 (defclass monolithic-lib-op (monolithic-bundle-op lib-op non-propagating-operation)
11471 ((gather-type :initform :object :allocation :class))
11472 (:documentation "Compile the system and produce a linkable static library (.a/.lib)
11473 for all the linkable object files associated with the system or its dependencies. See LIB-OP."))
11474
11475 (defclass monolithic-dll-op (monolithic-bundle-op dll-op non-propagating-operation)
11476 ((gather-type :initform :object :allocation :class))
11477 (:documentation "Compile the system and produce a dynamic loadable library (.so/.dll)
11478 for all the linkable object files associated with the system or its dependencies. See LIB-OP"))
11479
11480 (defclass image-op (monolithic-bundle-op selfward-operation
11481 #+(or clasp ecl mkcl) link-op #+(or clasp ecl mkcl) gather-op)
11482 ((bundle-type :initform :image)
11483 (gather-op :initform 'lib-op :allocation :class)
11484 #+(or clasp ecl mkcl) (gather-type :initform :static-library :allocation :class)
11485 (selfward-operation :initform '(#-(or clasp ecl mkcl) load-op) :allocation :class))
11486 (:documentation "create an image file from the system and its dependencies"))
11487
11488 (defclass program-op (image-op)
11489 ((bundle-type :initform :program))
11490 (:documentation "create an executable file from the system and its dependencies"))
11491
11492 ;; From the ASDF-internal bundle-type identifier, get a filesystem-usable pathname type.
11493 (defun bundle-pathname-type (bundle-type)
11494 (etypecase bundle-type
11495 ((or null string) ;; pass through nil or string literal
11496 bundle-type)
11497 ((eql :no-output-file) ;; marker for a bundle-type that has NO output file
11498 (error "No output file, therefore no pathname type"))
11499 ((eql :fasl) ;; the type of a fasl
11500 #-(or clasp ecl mkcl) (compile-file-type) ; on image-based platforms, used as input and output
11501 #+(or clasp ecl mkcl) "fasb") ; on C-linking platforms, only used as output for system bundles
11502 ((member :image)
11503 #+allegro "dxl"
11504 #+(and clisp os-windows) "exe"
11505 #-(or allegro (and clisp os-windows)) "image")
11506 ;; NB: on CLASP and ECL these implementations, we better agree with
11507 ;; (compile-file-type :type bundle-type))
11508 ((eql :object) ;; the type of a linkable object file
11509 (os-cond ((os-unix-p) "o")
11510 ((os-windows-p) (if (featurep '(:or :mingw32 :mingw64)) "o" "obj"))))
11511 ((member :lib :static-library) ;; the type of a linkable library
11512 (os-cond ((os-unix-p) "a")
11513 ((os-windows-p) (if (featurep '(:or :mingw32 :mingw64)) "a" "lib"))))
11514 ((member :dll :shared-library) ;; the type of a shared library
11515 (os-cond ((os-macosx-p) "dylib") ((os-unix-p) "so") ((os-windows-p) "dll")))
11516 ((eql :program) ;; the type of an executable program
11517 (os-cond ((os-unix-p) nil) ((os-windows-p) "exe")))))
11518
11519 ;; Compute the output-files for a given bundle action
11520 (defun bundle-output-files (o c)
11521 (let ((bundle-type (bundle-type o)))
11522 (unless (or (eq bundle-type :no-output-file) ;; NIL already means something regarding type.
11523 (and (null (input-files o c)) (not (member bundle-type '(:image :program)))))
11524 (let ((name (or (component-build-pathname c)
11525 (format nil "~A~@[~A~]" (component-name c) (slot-value o 'name-suffix))))
11526 (type (bundle-pathname-type bundle-type)))
11527 (values (list (subpathname (component-pathname c) name :type type))
11528 (eq (class-of o) (coerce-class (component-build-operation c)
11529 :package :asdf/interface
11530 :super 'operation
11531 :error nil)))))))
11532
11533 (defmethod output-files ((o bundle-op) (c system))
11534 (bundle-output-files o c))
11535
11536 #-(or clasp ecl mkcl)
11537 (progn
11538 (defmethod perform ((o image-op) (c system))
11539 (dump-image (output-file o c) :executable (typep o 'program-op)))
11540 (defmethod perform :before ((o program-op) (c system))
11541 (setf *image-entry-point* (ensure-function (component-entry-point c)))))
11542
11543 (defclass compiled-file (file-component)
11544 ((type :initform #-(or clasp ecl mkcl) (compile-file-type) #+(or clasp ecl mkcl) "fasb"))
11545 (:documentation "Class for a file that is already compiled,
11546 e.g. as part of the implementation, of an outer build system that calls into ASDF,
11547 or of opaque libraries shipped along the source code."))
11548
11549 (defclass precompiled-system (system)
11550 ((build-pathname :initarg :fasl))
11551 (:documentation "Class For a system that is delivered as a precompiled fasl"))
11552
11553 (defclass prebuilt-system (system)
11554 ((build-pathname :initarg :static-library :initarg :lib
11555 :accessor prebuilt-system-static-library))
11556 (:documentation "Class for a system delivered with a linkable static library (.a/.lib)")))
11557
11558
11559 ;;;
11560 ;;; BUNDLE-OP
11561 ;;;
11562 ;;; This operation takes all components from one or more systems and
11563 ;;; creates a single output file, which may be
11564 ;;; a FASL, a statically linked library, a shared library, etc.
11565 ;;; The different targets are defined by specialization.
11566 ;;;
11567 (with-upgradability ()
11568 (defmethod initialize-instance :after ((instance bundle-op) &rest initargs
11569 &key (name-suffix nil name-suffix-p)
11570 &allow-other-keys)
11571 (declare (ignore initargs name-suffix))
11572 ;; TODO: make that class slots or methods, not instance slots
11573 (unless name-suffix-p
11574 (setf (slot-value instance 'name-suffix)
11575 (unless (typep instance 'program-op)
11576 ;; "." is no good separator for Logical Pathnames, so we use "--"
11577 (if (operation-monolithic-p instance) "--all-systems" #-(or clasp ecl mkcl) "--system"))))
11578 (when (typep instance 'monolithic-bundle-op)
11579 (destructuring-bind (&key lisp-files prologue-code epilogue-code
11580 &allow-other-keys)
11581 (operation-original-initargs instance)
11582 (setf (prologue-code instance) prologue-code
11583 (epilogue-code instance) epilogue-code)
11584 #-(or clasp ecl) (assert (null (or lisp-files #-mkcl epilogue-code #-mkcl prologue-code)))
11585 #+(or clasp ecl) (setf (extra-object-files instance) lisp-files)))
11586 (setf (extra-build-args instance)
11587 (remove-plist-keys
11588 '(:type :monolithic :name-suffix :epilogue-code :prologue-code :lisp-files
11589 :force :force-not :plan-class) ;; TODO: refactor so we don't mix plan and operation arguments
11590 (operation-original-initargs instance))))
11591
11592 (defgeneric* (trivial-system-p) (component))
11593
11594 (defun user-system-p (s)
11595 (and (typep s 'system)
11596 (not (builtin-system-p s))
11597 (not (trivial-system-p s)))))
11598
11599 (eval-when (#-lispworks :compile-toplevel :load-toplevel :execute)
11600 (deftype user-system () '(and system (satisfies user-system-p))))
11601
11602 ;;;
11603 ;;; First we handle monolithic bundles.
11604 ;;; These are standalone systems which contain everything,
11605 ;;; including other ASDF systems required by the current one.
11606 ;;; A PROGRAM is always monolithic.
11607 ;;;
11608 ;;; MONOLITHIC SHARED LIBRARIES, PROGRAMS, FASL
11609 ;;;
11610 (with-upgradability ()
11611 (defun direct-dependency-files (o c &key (test 'identity) (key 'output-files) &allow-other-keys)
11612 ;; This function selects output files from direct dependencies;
11613 ;; your component-depends-on method must gather the correct dependencies in the correct order.
11614 (while-collecting (collect)
11615 (map-direct-dependencies
11616 t o c #'(lambda (sub-o sub-c)
11617 (loop :for f :in (funcall key sub-o sub-c)
11618 :when (funcall test f) :do (collect f))))))
11619
11620 (defun pathname-type-equal-function (type)
11621 #'(lambda (p) (equalp (pathname-type p) type)))
11622
11623 (defmethod input-files ((o gather-op) (c system))
11624 (unless (eq (bundle-type o) :no-output-file)
11625 (direct-dependency-files
11626 o c :key 'output-files
11627 :test (pathname-type-equal-function (bundle-pathname-type (gather-type o))))))
11628
11629 ;; Find the operation that produces a given bundle-type
11630 (defun select-bundle-operation (type &optional monolithic)
11631 (ecase type
11632 ((:dll :shared-library)
11633 (if monolithic 'monolithic-dll-op 'dll-op))
11634 ((:lib :static-library)
11635 (if monolithic 'monolithic-lib-op 'lib-op))
11636 ((:fasl)
11637 (if monolithic 'monolithic-compile-bundle-op 'compile-bundle-op))
11638 ((:image)
11639 'image-op)
11640 ((:program)
11641 'program-op)))
11642
11643 ;; SUPPORTED ALTERNATIVE: Use program-op and program-system
11644 (defun make-build (system &rest args
11645 &key
11646 (monolithic nil)
11647 (type :fasl)
11648 (move-here nil move-here-p)
11649 (init-name nil)
11650 &allow-other-keys)
11651 (declare (ignore init-name))
11652 (let* ((operation-name (select-bundle-operation type monolithic))
11653 (move-here-path (if (and move-here
11654 (typep move-here '(or pathname string)))
11655 (ensure-pathname move-here :namestring :lisp :ensure-directory t)
11656 (system-relative-pathname system "asdf-output/")))
11657 (operation (apply 'operate operation-name
11658 system
11659 (remove-plist-keys '(:monolithic :type :move-here) args)))
11660 (system (find-system system))
11661 (files (and system (output-files operation system))))
11662 (if (or move-here (and (null move-here-p)
11663 (member operation-name '(:program :image))))
11664 (loop :with dest-path = (resolve-symlinks* (ensure-directories-exist move-here-path))
11665 :for f :in files
11666 :for new-f = (make-pathname :name (pathname-name f)
11667 :type (pathname-type f)
11668 :defaults dest-path)
11669 :do (handler-case (rename-file-overwriting-target f new-f)
11670 (file-error (c)
11671 (declare (ignore c))
11672 (copy-file f new-f)
11673 (delete-file-if-exists f)))
11674 :collect new-f)
11675 files)))
11676
11677 ;; Apparently, some users of ECL, MKCL and ABCL may still be using it;
11678 ;; but at the very least, this function should be renamed, and/or
11679 ;; some way of specifying the output directory should be provided.
11680 ;; As is, it is not such a useful interface.
11681 (defun bundle-system (system &rest args &key force (verbose t) version &allow-other-keys)
11682 (declare (ignore force verbose version))
11683 (apply 'operate 'deliver-asd-op system args)))
11684
11685 ;;;
11686 ;;; LOAD-BUNDLE-OP
11687 ;;;
11688 ;;; This is like ASDF's LOAD-OP, but using bundle fasl files.
11689 ;;;
11690 (with-upgradability ()
11691 (defmethod component-depends-on ((o load-bundle-op) (c system))
11692 `((,o ,@(component-sideway-dependencies c))
11693 (,(if (user-system-p c) 'compile-bundle-op 'load-op) ,c)
11694 ,@(call-next-method)))
11695
11696 (defmethod input-files ((o load-bundle-op) (c system))
11697 (when (user-system-p c)
11698 (output-files (find-operation o 'compile-bundle-op) c)))
11699
11700 (defmethod perform ((o load-bundle-op) (c system))
11701 (when (input-files o c)
11702 (perform-lisp-load-fasl o c)))
11703
11704 (defmethod mark-operation-done :after ((o load-bundle-op) (c system))
11705 (mark-operation-done (find-operation o 'load-op) c)))
11706
11707 ;;;
11708 ;;; PRECOMPILED FILES
11709 ;;;
11710 ;;; This component can be used to distribute ASDF systems in precompiled form.
11711 ;;; Only useful when the dependencies have also been precompiled.
11712 ;;;
11713 (with-upgradability ()
11714 (defmethod trivial-system-p ((s system))
11715 (every #'(lambda (c) (typep c 'compiled-file)) (component-children s)))
11716
11717 (defmethod input-files ((o operation) (c compiled-file))
11718 (list (component-pathname c)))
11719 (defmethod perform ((o load-op) (c compiled-file))
11720 (perform-lisp-load-fasl o c))
11721 (defmethod perform ((o load-source-op) (c compiled-file))
11722 (perform (find-operation o 'load-op) c))
11723 (defmethod perform ((o operation) (c compiled-file))
11724 nil))
11725
11726 ;;;
11727 ;;; Pre-built systems
11728 ;;;
11729 (with-upgradability ()
11730 (defmethod trivial-system-p ((s prebuilt-system))
11731 t)
11732
11733 (defmethod perform ((o link-op) (c prebuilt-system))
11734 nil)
11735
11736 (defmethod perform ((o basic-compile-bundle-op) (c prebuilt-system))
11737 nil)
11738
11739 (defmethod perform ((o lib-op) (c prebuilt-system))
11740 nil)
11741
11742 (defmethod perform ((o dll-op) (c prebuilt-system))
11743 nil)
11744
11745 (defmethod component-depends-on ((o gather-op) (c prebuilt-system))
11746 nil)
11747
11748 (defmethod output-files ((o lib-op) (c prebuilt-system))
11749 (values (list (prebuilt-system-static-library c)) t)))
11750
11751
11752 ;;;
11753 ;;; PREBUILT SYSTEM CREATOR
11754 ;;;
11755 (with-upgradability ()
11756 (defmethod output-files ((o deliver-asd-op) (s system))
11757 (list (make-pathname :name (component-name s) :type "asd"
11758 :defaults (component-pathname s))))
11759
11760 (defmethod perform ((o deliver-asd-op) (s system))
11761 (let* ((inputs (input-files o s))
11762 (fasl (first inputs))
11763 (library (second inputs))
11764 (asd (first (output-files o s)))
11765 (name (if (and fasl asd) (pathname-name asd) (return-from perform)))
11766 (version (component-version s))
11767 (dependencies
11768 (if (operation-monolithic-p o)
11769 ;; We want only dependencies, and we use
11770 ;; basic-load-op rather than load-op so that this
11771 ;; will keep working on systems when
11772 ;; *load-system-operation* is load-bundle-op
11773 (remove-if-not 'builtin-system-p
11774 (required-components s :component-type 'system
11775 :keep-operation 'basic-load-op))
11776 (while-collecting (x) ;; resolve the sideway-dependencies of s
11777 (map-direct-dependencies
11778 t 'load-op s
11779 #'(lambda (o c)
11780 (when (and (typep o 'load-op) (typep c 'system))
11781 (x c)))))))
11782 (depends-on (mapcar 'coerce-name dependencies)))
11783 (when (pathname-equal asd (system-source-file s))
11784 (cerror "overwrite the asd file"
11785 "~/asdf-action:format-action/ is going to overwrite the system definition file ~S which is probably not what you want; you probably need to tweak your output translations."
11786 (cons o s) asd))
11787 (with-open-file (s asd :direction :output :if-exists :supersede
11788 :if-does-not-exist :create)
11789 (format s ";;; Prebuilt~:[~; monolithic~] ASDF definition for system ~A~%"
11790 (operation-monolithic-p o) name)
11791 (format s ";;; Built for ~A ~A on a ~A/~A ~A~%"
11792 (lisp-implementation-type)
11793 (lisp-implementation-version)
11794 (software-type)
11795 (machine-type)
11796 (software-version))
11797 (let ((*package* (find-package :asdf-user)))
11798 (pprint `(defsystem ,name
11799 :class prebuilt-system
11800 :version ,version
11801 :depends-on ,depends-on
11802 :components ((:compiled-file ,(pathname-name fasl)))
11803 ,@(when library `(:lib ,(file-namestring library))))
11804 s)
11805 (terpri s)))))
11806
11807 #-(or clasp ecl mkcl)
11808 (defmethod perform ((o basic-compile-bundle-op) (c system))
11809 (let* ((input-files (input-files o c))
11810 (fasl-files (remove (compile-file-type) input-files :key #'pathname-type :test-not #'equalp))
11811 (non-fasl-files (remove (compile-file-type) input-files :key #'pathname-type :test #'equalp))
11812 (output-files (output-files o c))
11813 (output-file (first output-files)))
11814 (assert (eq (not input-files) (not output-files)))
11815 (when input-files
11816 (when non-fasl-files
11817 (error "On ~A, asdf/bundle can only bundle FASL files, but these were also produced: ~S"
11818 (implementation-type) non-fasl-files))
11819 (when (or (prologue-code o) (epilogue-code o)
11820 (prologue-code c) (epilogue-code c))
11821 (error "prologue-code and epilogue-code are not supported on ~A"
11822 (implementation-type)))
11823 (with-staging-pathname (output-file)
11824 (combine-fasls fasl-files output-file)))))
11825
11826 (defmethod input-files ((o load-op) (s precompiled-system))
11827 (bundle-output-files (find-operation o 'compile-bundle-op) s))
11828
11829 (defmethod perform ((o load-op) (s precompiled-system))
11830 (perform-lisp-load-fasl o s))
11831
11832 (defmethod component-depends-on ((o load-bundle-op) (s precompiled-system))
11833 #+xcl (declare (ignorable o))
11834 `((load-op ,s) ,@(call-next-method))))
11835
11836 #| ;; Example use:
11837 (asdf:defsystem :precompiled-asdf-utils :class asdf::precompiled-system :fasl (asdf:apply-output-translations (asdf:system-relative-pathname :asdf-utils "asdf-utils.system.fasl")))
11838 (asdf:load-system :precompiled-asdf-utils)
11839 |#
11840
11841 #+(or clasp ecl mkcl)
11842 (with-upgradability ()
11843
11844 ;; *load-system-operation* can't be determined at load time, because
11845 ;; bytecodes compiler may be installed after loading asdf.
11846 ;;
11847 ;; (unless (use-ecl-byte-compiler-p)
11848 ;; (setf *load-system-operation* 'load-bundle-op))
11849
11850 (defun system-module-pathname (module)
11851 (let ((name (coerce-name module)))
11852 (some
11853 'file-exists-p
11854 (list
11855 #+clasp (compile-file-pathname (make-pathname :name name :defaults "sys:") :output-type :object)
11856 #+ecl (compile-file-pathname (make-pathname :name name :defaults "sys:") :type :lib)
11857 #+ecl (compile-file-pathname (make-pathname :name name :defaults "sys:") :type :object)
11858 #+mkcl (make-pathname :name name :type (bundle-pathname-type :lib) :defaults #p"sys:")
11859 #+mkcl (make-pathname :name name :type (bundle-pathname-type :lib) :defaults #p"sys:contrib;")))))
11860
11861 (defun make-prebuilt-system (name &optional (pathname (system-module-pathname name)))
11862 "Creates a prebuilt-system if PATHNAME isn't NIL."
11863 (when pathname
11864 (make-instance 'prebuilt-system
11865 :name (coerce-name name)
11866 :static-library (resolve-symlinks* pathname))))
11867
11868 (defmethod component-depends-on :around ((o image-op) (c system))
11869 (destructuring-bind ((lib-op . deps)) (call-next-method)
11870 (labels ((ensure-linkable-system (x)
11871 (or (if-let (s (find-system x))
11872 (and (system-source-directory x)
11873 s))
11874 (if-let (p (system-module-pathname x))
11875 (make-prebuilt-system x p)))))
11876 `((,lib-op
11877 ,@(mapcar #'ensure-linkable-system
11878 (if (no-uiop c)
11879 deps
11880 (union deps '("cmp" "uiop" "asdf")))))))))
11881
11882 (defmethod perform ((o link-op) (c system))
11883 (let* ((object-files (input-files o c))
11884 (output (output-files o c))
11885 (bundle (first output))
11886 (programp (typep o 'program-op))
11887 (kind (bundle-type o)))
11888 (when output
11889 (apply 'create-image
11890 bundle (append
11891 (when programp (prefix-lisp-object-files c))
11892 object-files
11893 (when programp (postfix-lisp-object-files c)))
11894 :kind kind
11895 :prologue-code (or (prologue-code o) (when programp (prologue-code c)))
11896 :epilogue-code (or (epilogue-code o) (when programp (epilogue-code c)))
11897 :build-args (or (extra-build-args o) (when programp (extra-build-args c)))
11898 :extra-object-files (or (extra-object-files o) (when programp (extra-object-files c)))
11899 :no-uiop (no-uiop c)
11900 (when programp `(:entry-point ,(component-entry-point c))))))))
11901 ;;;; -------------------------------------------------------------------------
11902 ;;;; Concatenate-source
11903
11904 (uiop/package:define-package :asdf/concatenate-source
11905 (:recycle :asdf/concatenate-source :asdf)
11906 (:use :uiop/common-lisp :uiop :asdf/upgrade
11907 :asdf/component :asdf/operation
11908 :asdf/system :asdf/find-system
11909 :asdf/action :asdf/lisp-action :asdf/bundle)
11910 (:export
11911 #:concatenate-source-op
11912 #:load-concatenated-source-op
11913 #:compile-concatenated-source-op
11914 #:load-compiled-concatenated-source-op
11915 #:monolithic-concatenate-source-op
11916 #:monolithic-load-concatenated-source-op
11917 #:monolithic-compile-concatenated-source-op
11918 #:monolithic-load-compiled-concatenated-source-op))
11919 (in-package :asdf/concatenate-source)
11920
11921 ;;;
11922 ;;; Concatenate sources
11923 ;;;
11924 (with-upgradability ()
11925 ;; Base classes for both regular and monolithic concatenate-source operations
11926 (defclass basic-concatenate-source-op (bundle-op)
11927 ((bundle-type :initform "lisp")))
11928 (defclass basic-load-concatenated-source-op (basic-load-op selfward-operation) ())
11929 (defclass basic-compile-concatenated-source-op (basic-compile-op selfward-operation) ())
11930 (defclass basic-load-compiled-concatenated-source-op (basic-load-op selfward-operation) ())
11931
11932 ;; Regular concatenate-source operations
11933 (defclass concatenate-source-op (basic-concatenate-source-op non-propagating-operation) ()
11934 (:documentation "Operation to concatenate all sources in a system into a single file"))
11935 (defclass load-concatenated-source-op (basic-load-concatenated-source-op)
11936 ((selfward-operation :initform '(prepare-op concatenate-source-op) :allocation :class))
11937 (:documentation "Operation to load the result of concatenate-source-op as source"))
11938 (defclass compile-concatenated-source-op (basic-compile-concatenated-source-op)
11939 ((selfward-operation :initform '(prepare-op concatenate-source-op) :allocation :class))
11940 (:documentation "Operation to compile the result of concatenate-source-op"))
11941 (defclass load-compiled-concatenated-source-op (basic-load-compiled-concatenated-source-op)
11942 ((selfward-operation :initform '(prepare-op compile-concatenated-source-op) :allocation :class))
11943 (:documentation "Operation to load the result of compile-concatenated-source-op"))
11944
11945 (defclass monolithic-concatenate-source-op
11946 (basic-concatenate-source-op monolithic-bundle-op non-propagating-operation) ()
11947 (:documentation "Operation to concatenate all sources in a system and its dependencies
11948 into a single file"))
11949 (defclass monolithic-load-concatenated-source-op (basic-load-concatenated-source-op)
11950 ((selfward-operation :initform 'monolithic-concatenate-source-op :allocation :class))
11951 (:documentation "Operation to load the result of monolithic-concatenate-source-op as source"))
11952 (defclass monolithic-compile-concatenated-source-op (basic-compile-concatenated-source-op)
11953 ((selfward-operation :initform 'monolithic-concatenate-source-op :allocation :class))
11954 (:documentation "Operation to compile the result of monolithic-concatenate-source-op"))
11955 (defclass monolithic-load-compiled-concatenated-source-op
11956 (basic-load-compiled-concatenated-source-op)
11957 ((selfward-operation :initform 'monolithic-compile-concatenated-source-op :allocation :class))
11958 (:documentation "Operation to load the result of monolithic-compile-concatenated-source-op"))
11959
11960 (defmethod input-files ((operation basic-concatenate-source-op) (s system))
11961 (loop :with encoding = (or (component-encoding s) *default-encoding*)
11962 :with other-encodings = '()
11963 :with around-compile = (around-compile-hook s)
11964 :with other-around-compile = '()
11965 :for c :in (required-components
11966 s :goal-operation 'compile-op
11967 :keep-operation 'basic-compile-op
11968 :other-systems (operation-monolithic-p operation))
11969 :append
11970 (when (typep c 'cl-source-file)
11971 (let ((e (component-encoding c)))
11972 (unless (equal e encoding)
11973 (let ((a (assoc e other-encodings)))
11974 (if a (push (component-find-path c) (cdr a))
11975 (push (list a (component-find-path c)) other-encodings)))))
11976 (unless (equal around-compile (around-compile-hook c))
11977 (push (component-find-path c) other-around-compile))
11978 (input-files (make-operation 'compile-op) c)) :into inputs
11979 :finally
11980 (when other-encodings
11981 (warn "~S uses encoding ~A but has sources that use these encodings:~{ ~A~}"
11982 operation encoding
11983 (mapcar #'(lambda (x) (cons (car x) (list (reverse (cdr x)))))
11984 other-encodings)))
11985 (when other-around-compile
11986 (warn "~S uses around-compile hook ~A but has sources that use these hooks: ~A"
11987 operation around-compile other-around-compile))
11988 (return inputs)))
11989 (defmethod output-files ((o basic-compile-concatenated-source-op) (s system))
11990 (lisp-compilation-output-files o s))
11991
11992 (defmethod perform ((o basic-concatenate-source-op) (s system))
11993 (let* ((ins (input-files o s))
11994 (out (output-file o s))
11995 (tmp (tmpize-pathname out)))
11996 (concatenate-files ins tmp)
11997 (rename-file-overwriting-target tmp out)))
11998 (defmethod perform ((o basic-load-concatenated-source-op) (s system))
11999 (perform-lisp-load-source o s))
12000 (defmethod perform ((o basic-compile-concatenated-source-op) (s system))
12001 (perform-lisp-compilation o s))
12002 (defmethod perform ((o basic-load-compiled-concatenated-source-op) (s system))
12003 (perform-lisp-load-fasl o s)))
12004
12005 ;;;; -------------------------------------------------------------------------
12006 ;;;; Package systems in the style of quick-build or faslpath
12007
12008 (uiop:define-package :asdf/package-inferred-system
12009 (:recycle :asdf/package-inferred-system :asdf/package-system :asdf)
12010 (:use :uiop/common-lisp :uiop
12011 :asdf/defsystem ;; Using the old name of :asdf/parse-defsystem for compatibility
12012 :asdf/upgrade :asdf/component :asdf/system :asdf/find-system :asdf/lisp-action)
12013 (:export
12014 #:package-inferred-system #:sysdef-package-inferred-system-search
12015 #:package-system ;; backward compatibility only. To be removed.
12016 #:register-system-packages
12017 #:*defpackage-forms* #:*package-inferred-systems* #:package-inferred-system-missing-package-error))
12018 (in-package :asdf/package-inferred-system)
12019
12020 (with-upgradability ()
12021 ;; The names of the recognized defpackage forms.
12022 (defparameter *defpackage-forms* '(defpackage define-package))
12023
12024 (defun initial-package-inferred-systems-table ()
12025 ;; Mark all existing packages are preloaded.
12026 (let ((h (make-hash-table :test 'equal)))
12027 (dolist (p (list-all-packages))
12028 (dolist (n (package-names p))
12029 (setf (gethash n h) t)))
12030 h))
12031
12032 ;; Mapping from package names to systems that provide them.
12033 (defvar *package-inferred-systems* (initial-package-inferred-systems-table))
12034
12035 (defclass package-inferred-system (system)
12036 ()
12037 (:documentation "Class for primary systems for which secondary systems are automatically
12038 in the one-file, one-file, one-system style: system names are mapped to files under the primary
12039 system's system-source-directory, dependencies are inferred from the first defpackage form in
12040 every such file"))
12041
12042 ;; DEPRECATED. For backward compatibility only. To be removed in an upcoming release:
12043 (defclass package-system (package-inferred-system) ())
12044
12045 ;; Is a given form recognizable as a defpackage form?
12046 (defun defpackage-form-p (form)
12047 (and (consp form)
12048 (member (car form) *defpackage-forms*)))
12049
12050 ;; Find the first defpackage form in a stream, if any
12051 (defun stream-defpackage-form (stream)
12052 (loop :for form = (read stream nil nil) :while form
12053 :when (defpackage-form-p form) :return form))
12054
12055 (defun file-defpackage-form (file)
12056 "Return the first DEFPACKAGE form in FILE."
12057 (with-input-file (f file)
12058 (stream-defpackage-form f)))
12059
12060 (define-condition package-inferred-system-missing-package-error (system-definition-error)
12061 ((system :initarg :system :reader error-system)
12062 (pathname :initarg :pathname :reader error-pathname))
12063 (:report (lambda (c s)
12064 (format s (compatfmt "~@<No package form found while ~
12065 trying to define package-inferred-system ~A from file ~A~>")
12066 (error-system c) (error-pathname c)))))
12067
12068 (defun package-dependencies (defpackage-form)
12069 "Return a list of packages depended on by the package
12070 defined in DEFPACKAGE-FORM. A package is depended upon if
12071 the DEFPACKAGE-FORM uses it or imports a symbol from it."
12072 (assert (defpackage-form-p defpackage-form))
12073 (remove-duplicates
12074 (while-collecting (dep)
12075 (loop* :for (option . arguments) :in (cddr defpackage-form) :do
12076 (ecase option
12077 ((:use :mix :reexport :use-reexport :mix-reexport)
12078 (dolist (p arguments) (dep (string p))))
12079 ((:import-from :shadowing-import-from)
12080 (dep (string (first arguments))))
12081 ((:nicknames :documentation :shadow :export :intern :unintern :recycle)))))
12082 :from-end t :test 'equal))
12083
12084 (defun package-designator-name (package)
12085 "Normalize a package designator to a string"
12086 (etypecase package
12087 (package (package-name package))
12088 (string package)
12089 (symbol (string package))))
12090
12091 (defun register-system-packages (system packages)
12092 "Register SYSTEM as providing PACKAGES."
12093 (let ((name (or (eq system t) (coerce-name system))))
12094 (dolist (p (ensure-list packages))
12095 (setf (gethash (package-designator-name p) *package-inferred-systems*) name))))
12096
12097 (defun package-name-system (package-name)
12098 "Return the name of the SYSTEM providing PACKAGE-NAME, if such exists,
12099 otherwise return a default system name computed from PACKAGE-NAME."
12100 (check-type package-name string)
12101 (if-let ((system-name (gethash package-name *package-inferred-systems*)))
12102 system-name
12103 (string-downcase package-name)))
12104
12105 ;; Given a file in package-inferred-system style, find its dependencies
12106 (defun package-inferred-system-file-dependencies (file &optional system)
12107 (if-let (defpackage-form (file-defpackage-form file))
12108 (remove t (mapcar 'package-name-system (package-dependencies defpackage-form)))
12109 (error 'package-inferred-system-missing-package-error :system system :pathname file)))
12110
12111 ;; Given package-inferred-system object, check whether its specification matches
12112 ;; the provided parameters
12113 (defun same-package-inferred-system-p (system name directory subpath around-compile dependencies)
12114 (and (eq (type-of system) 'package-inferred-system)
12115 (equal (component-name system) name)
12116 (pathname-equal directory (component-pathname system))
12117 (equal dependencies (component-sideway-dependencies system))
12118 (equal around-compile (around-compile-hook system))
12119 (let ((children (component-children system)))
12120 (and (length=n-p children 1)
12121 (let ((child (first children)))
12122 (and (eq (type-of child) 'cl-source-file)
12123 (equal (component-name child) "lisp")
12124 (and (slot-boundp child 'relative-pathname)
12125 (equal (slot-value child 'relative-pathname) subpath))))))))
12126
12127 ;; sysdef search function to push into *system-definition-search-functions*
12128 (defun sysdef-package-inferred-system-search (system)
12129 (let ((primary (primary-system-name system)))
12130 (unless (equal primary system)
12131 (let ((top (find-system primary nil)))
12132 (when (typep top 'package-inferred-system)
12133 (if-let (dir (component-pathname top))
12134 (let* ((sub (subseq system (1+ (length primary))))
12135 (f (probe-file* (subpathname dir sub :type "lisp")
12136 :truename *resolve-symlinks*)))
12137 (when (file-pathname-p f)
12138 (let ((dependencies (package-inferred-system-file-dependencies f system))
12139 (previous (registered-system system))
12140 (around-compile (around-compile-hook top)))
12141 (if (same-package-inferred-system-p previous system dir sub around-compile dependencies)
12142 previous
12143 (eval `(defsystem ,system
12144 :class package-inferred-system
12145 :source-file nil
12146 :pathname ,dir
12147 :depends-on ,dependencies
12148 :around-compile ,around-compile
12149 :components ((cl-source-file "lisp" :pathname ,sub)))))))))))))))
12150
12151 (with-upgradability ()
12152 (pushnew 'sysdef-package-inferred-system-search *system-definition-search-functions*)
12153 (setf *system-definition-search-functions*
12154 (remove (find-symbol* :sysdef-package-system-search :asdf/package-system nil)
12155 *system-definition-search-functions*)))
12156 ;;;; -------------------------------------------------------------------------
12157 ;;; Internal hacks for backward-compatibility
12158
12159 (uiop/package:define-package :asdf/backward-internals
12160 (:recycle :asdf/backward-internals :asdf)
12161 (:use :uiop/common-lisp :uiop :asdf/upgrade :asdf/find-system)
12162 (:export #:load-sysdef))
12163 (in-package :asdf/backward-internals)
12164
12165 (with-upgradability ()
12166 (defun load-sysdef (name pathname)
12167 (declare (ignore name pathname))
12168 ;; Needed for backward compatibility with swank-asdf from SLIME 2015-12-01 or older.
12169 (error "Use asdf:load-asd instead of asdf::load-sysdef")))
12170 ;;;; -------------------------------------------------------------------------
12171 ;;; Backward-compatible interfaces
12172
12173 (uiop/package:define-package :asdf/backward-interface
12174 (:recycle :asdf/backward-interface :asdf)
12175 (:use :uiop/common-lisp :uiop :asdf/upgrade
12176 :asdf/component :asdf/system :asdf/find-system :asdf/operation :asdf/action
12177 :asdf/lisp-action :asdf/plan :asdf/operate :asdf/output-translations)
12178 (:export
12179 #:*asdf-verbose*
12180 #:operation-error #:compile-error #:compile-failed #:compile-warned
12181 #:error-component #:error-operation #:traverse
12182 #:component-load-dependencies
12183 #:enable-asdf-binary-locations-compatibility
12184 #:operation-forced
12185 #:operation-on-failure #:operation-on-warnings #:on-failure #:on-warnings
12186 #:component-property
12187 #:run-shell-command
12188 #:system-definition-pathname))
12189 (in-package :asdf/backward-interface)
12190
12191 (with-upgradability ()
12192 ;; These conditions from ASDF 1 and 2 are used by many packages in Quicklisp;
12193 ;; but ASDF3 replaced them with somewhat different variants of uiop:compile-condition
12194 ;; that do not involve ASDF actions.
12195 ;; TODO: find the offenders and stop them.
12196 (define-condition operation-error (error) ;; Bad, backward-compatible name
12197 ;; Used by SBCL, cffi-tests, clsql-mysql, clsql-uffi, qt, elephant, uffi-tests, sb-grovel
12198 ((component :reader error-component :initarg :component)
12199 (operation :reader error-operation :initarg :operation))
12200 (:report (lambda (c s)
12201 (format s (compatfmt "~@<~A while invoking ~A on ~A~@:>")
12202 (type-of c) (error-operation c) (error-component c)))))
12203 (define-condition compile-error (operation-error) ())
12204 (define-condition compile-failed (compile-error) ())
12205 (define-condition compile-warned (compile-error) ())
12206
12207 (defun component-load-dependencies (component)
12208 "DEPRECATED. Please use COMPONENT-SIDEWAY-DEPENDENCIES instead."
12209 ;; Old deprecated name for the same thing. Please update your software.
12210 (component-sideway-dependencies component))
12211
12212 (defgeneric operation-forced (operation)
12213 (:documentation "DEPRECATED. Assume it's (constantly t) instead."))
12214 ;; This method exists for backward compatibility with swank.asd, its only user,
12215 ;; that still uses it as of 2016-09-21.
12216 ;;
12217 ;; The magic PERFORM method in swank.asd only actually loads swank if it sees that
12218 ;; the operation was forced. But except for the first time, the only reason the action
12219 ;; would be performed to begin with is because it was forced; and the first time over,
12220 ;; it doesn't hurt that :reload t :delete t should be used. So the check is redundant.
12221 ;; More generally, if you have to do something when the operation was forced,
12222 ;; you should also do it when not, and vice-versa, because it really shouldn't matter.
12223 ;; Thus, the backward-compatible thing to do is to always return T.
12224 ;;
12225 ;; TODO: change this function to a defun that always returns T.
12226 (defmethod operation-forced ((o operation)) (getf (operation-original-initargs o) :force))
12227
12228
12229 ;; These old interfaces from ASDF1 have never been very meaningful
12230 ;; but are still used in obscure places.
12231 (defgeneric operation-on-warnings (operation)
12232 (:documentation "DEPRECATED. Please use UIOP:*COMPILE-FILE-WARNINGS-BEHAVIOUR* instead."))
12233 (defgeneric operation-on-failure (operation)
12234 (:documentation "DEPRECATED. Please use UIOP:*COMPILE-FILE-FAILURE-BEHAVIOUR* instead."))
12235 (defgeneric (setf operation-on-warnings) (x operation)
12236 (:documentation "DEPRECATED. Please SETF UIOP:*COMPILE-FILE-WARNINGS-BEHAVIOUR* instead."))
12237 (defgeneric (setf operation-on-failure) (x operation)
12238 (:documentation "DEPRECATED. Please SETF UIOP:*COMPILE-FILE-FAILURE-BEHAVIOUR* instead."))
12239 (defmethod operation-on-warnings ((o operation))
12240 *compile-file-warnings-behaviour*)
12241 (defmethod operation-on-failure ((o operation))
12242 *compile-file-failure-behaviour*)
12243 (defmethod (setf operation-on-warnings) (x (o operation))
12244 (setf *compile-file-warnings-behaviour* x))
12245 (defmethod (setf operation-on-failure) (x (o operation))
12246 (setf *compile-file-failure-behaviour* x))
12247
12248 (defun system-definition-pathname (x)
12249 ;; As of 2.014.8, we mean to make this function obsolete,
12250 ;; but that won't happen until all clients have been updated.
12251 ;;(cerror "Use ASDF:SYSTEM-SOURCE-FILE instead"
12252 "DEPRECATED. This function used to expose ASDF internals with subtle
12253 differences with respect to user expectations, that have been refactored
12254 away since. We recommend you use ASDF:SYSTEM-SOURCE-FILE instead for a
12255 mostly compatible replacement that we're supporting, or even
12256 ASDF:SYSTEM-SOURCE-DIRECTORY or ASDF:SYSTEM-RELATIVE-PATHNAME
12257 if that's whay you mean." ;;)
12258 (system-source-file x))
12259
12260
12261 ;; TRAVERSE is the function used to compute a plan in ASDF 1 and 2.
12262 ;; It was never officially exposed but some people still used it.
12263 (defgeneric* (traverse) (operation component &key &allow-other-keys)
12264 (:documentation
12265 "Generate and return a plan for performing OPERATION on COMPONENT.
12266
12267 The plan returned is a list of dotted-pairs. Each pair is the CONS
12268 of ASDF operation object and a COMPONENT object. The pairs will be
12269 processed in order by OPERATE."))
12270 (define-convenience-action-methods traverse (operation component &key))
12271
12272 (defmethod traverse ((o operation) (c component) &rest keys &key plan-class &allow-other-keys)
12273 (plan-actions (apply 'make-plan plan-class o c keys))))
12274
12275
12276 ;;;; ASDF-Binary-Locations compatibility
12277 ;; This remains supported for legacy user, but not recommended for new users.
12278 ;; We suspect there are no more legacy users in 2016.
12279 (with-upgradability ()
12280 (defun enable-asdf-binary-locations-compatibility
12281 (&key
12282 (centralize-lisp-binaries nil)
12283 (default-toplevel-directory
12284 (subpathname (user-homedir-pathname) ".fasls/")) ;; Use ".cache/common-lisp/" instead ???
12285 (include-per-user-information nil)
12286 (map-all-source-files (or #+(or clasp clisp ecl mkcl) t nil))
12287 (source-to-target-mappings nil)
12288 (file-types `(,(compile-file-type)
12289 "build-report"
12290 #+clasp (compile-file-type :output-type :object)
12291 #+ecl (compile-file-type :type :object)
12292 #+mkcl (compile-file-type :fasl-p nil)
12293 #+clisp "lib" #+sbcl "cfasl"
12294 #+sbcl "sbcl-warnings" #+clozure "ccl-warnings")))
12295 #+(or clasp clisp ecl mkcl)
12296 (when (null map-all-source-files)
12297 (error "asdf:enable-asdf-binary-locations-compatibility doesn't support :map-all-source-files nil on CLISP, ECL and MKCL"))
12298 (let* ((patterns (if map-all-source-files (list *wild-file*)
12299 (loop :for type :in file-types
12300 :collect (make-pathname :type type :defaults *wild-file*))))
12301 (destination-directory
12302 (if centralize-lisp-binaries
12303 `(,default-toplevel-directory
12304 ,@(when include-per-user-information
12305 (cdr (pathname-directory (user-homedir-pathname))))
12306 :implementation ,*wild-inferiors*)
12307 `(:root ,*wild-inferiors* :implementation))))
12308 (initialize-output-translations
12309 `(:output-translations
12310 ,@source-to-target-mappings
12311 #+abcl (#p"jar:file:/**/*.jar!/**/*.*" (:function translate-jar-pathname))
12312 #+abcl (#p"/___jar___file___root___/**/*.*" (,@destination-directory))
12313 ,@(loop :for pattern :in patterns
12314 :collect `((:root ,*wild-inferiors* ,pattern)
12315 (,@destination-directory ,pattern)))
12316 (t t)
12317 :ignore-inherited-configuration))))
12318
12319 (defmethod operate :before (operation-class system &rest args &key &allow-other-keys)
12320 (declare (ignore operation-class system args))
12321 (when (find-symbol* '#:output-files-for-system-and-operation :asdf nil)
12322 (error "ASDF 2 is not compatible with ASDF-BINARY-LOCATIONS, which you are using.
12323 ASDF 2 now achieves the same purpose with its builtin ASDF-OUTPUT-TRANSLATIONS,
12324 which should be easier to configure. Please stop using ASDF-BINARY-LOCATIONS,
12325 and instead use ASDF-OUTPUT-TRANSLATIONS. See the ASDF manual for details.
12326 In case you insist on preserving your previous A-B-L configuration, but
12327 do not know how to achieve the same effect with A-O-T, you may use function
12328 ASDF:ENABLE-ASDF-BINARY-LOCATIONS-COMPATIBILITY as documented in the manual;
12329 call that function where you would otherwise have loaded and configured A-B-L."))))
12330
12331
12332 ;;; run-shell-command
12333 ;; WARNING! The function below is not just deprecated but also dysfunctional.
12334 ;; Please use asdf/run-program:run-program instead.
12335 (with-upgradability ()
12336 (defun run-shell-command (control-string &rest args)
12337 "Interpolate ARGS into CONTROL-STRING as if by FORMAT, and
12338 synchronously execute the result using a Bourne-compatible shell, with
12339 output to *VERBOSE-OUT*. Returns the shell's exit code.
12340
12341 PLEASE DO NOT USE.
12342 Deprecated function, for backward-compatibility only.
12343 Please use UIOP:RUN-PROGRAM instead."
12344 (let ((command (apply 'format nil control-string args)))
12345 (asdf-message "; $ ~A~%" command)
12346 (let ((exit-code
12347 (ignore-errors
12348 (nth-value 2 (run-program command :force-shell t :ignore-error-status t
12349 :output *verbose-out*)))))
12350 (typecase exit-code
12351 ((integer 0 255) exit-code)
12352 (t 255))))))
12353
12354 (with-upgradability ()
12355 (defvar *asdf-verbose* nil)) ;; backward-compatibility with ASDF2 only. Unused.
12356
12357 ;; backward-compatibility methods. Do NOT use in new code. NOT SUPPORTED.
12358 (with-upgradability ()
12359 (defgeneric component-property (component property))
12360 (defgeneric (setf component-property) (new-value component property))
12361
12362 (defmethod component-property ((c component) property)
12363 (cdr (assoc property (slot-value c 'properties) :test #'equal)))
12364
12365 (defmethod (setf component-property) (new-value (c component) property)
12366 (let ((a (assoc property (slot-value c 'properties) :test #'equal)))
12367 (if a
12368 (setf (cdr a) new-value)
12369 (setf (slot-value c 'properties)
12370 (acons property new-value (slot-value c 'properties)))))
12371 new-value))
12372 ;;;; ---------------------------------------------------------------------------
12373 ;;;; Handle ASDF package upgrade, including implementation-dependent magic.
12374
12375 (uiop/package:define-package :asdf/interface
12376 (:nicknames :asdf :asdf-utilities)
12377 (:recycle :asdf/interface :asdf)
12378 (:unintern
12379 #:loaded-systems ; makes for annoying SLIME completion
12380 #:output-files-for-system-and-operation) ; ASDF-BINARY-LOCATION function we use to detect ABL
12381 (:use :uiop/common-lisp :uiop :asdf/upgrade :asdf/cache
12382 :asdf/component :asdf/system :asdf/find-system :asdf/find-component
12383 :asdf/operation :asdf/action :asdf/lisp-action
12384 :asdf/output-translations :asdf/source-registry
12385 :asdf/plan :asdf/operate :asdf/parse-defsystem :asdf/bundle :asdf/concatenate-source
12386 :asdf/backward-internals :asdf/backward-interface :asdf/package-inferred-system)
12387 ;; Note: (1) we are NOT automatically reexporting everything from previous packages.
12388 ;; (2) we only reexport UIOP functionality when backward-compatibility requires it.
12389 (:export
12390 #:defsystem #:find-system #:load-asd #:locate-system #:coerce-name #:primary-system-name
12391 #:oos #:operate #:make-plan #:perform-plan #:sequential-plan
12392 #:system-definition-pathname
12393 #:search-for-system-definition #:find-component #:component-find-path
12394 #:compile-system #:load-system #:load-systems #:load-systems*
12395 #:require-system #:test-system #:clear-system
12396 #:operation #:make-operation #:find-operation
12397 #:upward-operation #:downward-operation #:sideway-operation #:selfward-operation
12398 #:non-propagating-operation
12399 #:build-op #:make
12400 #:load-op #:prepare-op #:compile-op
12401 #:prepare-source-op #:load-source-op #:test-op
12402 #:feature #:version #:version-satisfies #:upgrade-asdf
12403 #:implementation-identifier #:implementation-type #:hostname
12404 #:input-files #:output-files #:output-file #:perform #:perform-with-restarts
12405 #:operation-done-p #:explain #:action-description #:component-sideway-dependencies
12406 #:needed-in-image-p
12407 #:component-load-dependencies #:run-shell-command ; deprecated, do not use
12408 #:bundle-op #:monolithic-bundle-op #:precompiled-system #:compiled-file #:bundle-system
12409 #:program-system #:make-build
12410 #:basic-compile-bundle-op #:prepare-bundle-op
12411 #:compile-bundle-op #:load-bundle-op #:monolithic-compile-bundle-op #:monolithic-load-bundle-op
12412 #:lib-op #:dll-op #:deliver-asd-op #:program-op #:image-op
12413 #:monolithic-lib-op #:monolithic-dll-op #:monolithic-deliver-asd-op
12414 #:concatenate-source-op
12415 #:load-concatenated-source-op
12416 #:compile-concatenated-source-op
12417 #:load-compiled-concatenated-source-op
12418 #:monolithic-concatenate-source-op
12419 #:monolithic-load-concatenated-source-op
12420 #:monolithic-compile-concatenated-source-op
12421 #:monolithic-load-compiled-concatenated-source-op
12422 #:operation-monolithic-p
12423 #:required-components
12424 #:component-loaded-p
12425
12426 #:component #:parent-component #:child-component #:system #:module
12427 #:file-component #:source-file #:c-source-file #:java-source-file
12428 #:cl-source-file #:cl-source-file.cl #:cl-source-file.lsp
12429 #:static-file #:doc-file #:html-file
12430 #:file-type #:source-file-type
12431
12432 #:register-preloaded-system #:sysdef-preloaded-system-search
12433 #:register-immutable-system #:sysdef-immutable-system-search
12434
12435 #:package-inferred-system #:register-system-packages
12436 #:package-system ;; backward-compatibility during migration, to be removed in a further release.
12437
12438 #:component-children ; component accessors
12439 #:component-children-by-name
12440 #:component-pathname
12441 #:component-relative-pathname
12442 #:component-name
12443 #:component-version
12444 #:component-parent
12445 #:component-system
12446 #:component-encoding
12447 #:component-external-format
12448
12449 #:component-depends-on ; backward-compatible name rather than action-depends-on
12450 #:module-components ; backward-compatibility
12451 #:operation-on-warnings #:operation-on-failure ; backward-compatibility
12452 #:component-property ; backward-compatibility
12453 #:traverse ; backward-compatibility
12454
12455 #:system-description
12456 #:system-long-description
12457 #:system-author
12458 #:system-maintainer
12459 #:system-license
12460 #:system-licence
12461 #:system-source-file
12462 #:system-source-directory
12463 #:system-relative-pathname
12464 #:system-homepage
12465 #:system-mailto
12466 #:system-bug-tracker
12467 #:system-long-name
12468 #:system-source-control
12469 #:map-systems
12470 #:system-defsystem-depends-on
12471 #:system-depends-on
12472 #:system-weakly-depends-on
12473
12474 #:*system-definition-search-functions* ; variables
12475 #:*central-registry*
12476 #:*compile-file-warnings-behaviour*
12477 #:*compile-file-failure-behaviour*
12478 #:*resolve-symlinks*
12479 #:*load-system-operation*
12480 #:*asdf-verbose* ;; unused. For backward-compatibility only.
12481 #:*verbose-out*
12482
12483 #:asdf-version
12484
12485 #:compile-condition #:compile-file-error #:compile-warned-error #:compile-failed-error
12486 #:compile-warned-warning #:compile-failed-warning
12487 #:operation-error #:compile-failed #:compile-warned #:compile-error ;; backward compatibility
12488 #:error-name
12489 #:error-pathname
12490 #:load-system-definition-error
12491 #:error-component #:error-operation
12492 #:system-definition-error
12493 #:missing-component
12494 #:missing-component-of-version
12495 #:missing-dependency
12496 #:missing-dependency-of-version
12497 #:circular-dependency ; errors
12498 #:duplicate-names #:non-toplevel-system #:non-system-system
12499 #:package-inferred-system-missing-package-error
12500 #:operation-definition-warning #:operation-definition-error
12501
12502 #:try-recompiling ; restarts
12503 #:retry
12504 #:accept
12505 #:coerce-entry-to-directory
12506 #:remove-entry-from-registry
12507 #:clear-configuration-and-retry
12508
12509
12510 #:*encoding-detection-hook*
12511 #:*encoding-external-format-hook*
12512 #:*default-encoding*
12513 #:*utf-8-external-format*
12514
12515 #:clear-configuration
12516 #:*output-translations-parameter*
12517 #:initialize-output-translations
12518 #:disable-output-translations
12519 #:clear-output-translations
12520 #:ensure-output-translations
12521 #:apply-output-translations
12522 #:compile-file*
12523 #:compile-file-pathname*
12524 #:*warnings-file-type* #:enable-deferred-warnings-check #:disable-deferred-warnings-check
12525 #:enable-asdf-binary-locations-compatibility
12526 #:*default-source-registries*
12527 #:*source-registry-parameter*
12528 #:initialize-source-registry
12529 #:compute-source-registry
12530 #:clear-source-registry
12531 #:ensure-source-registry
12532 #:process-source-registry
12533 #:system-registered-p #:registered-system #:registered-systems #:already-loaded-systems
12534 #:resolve-location
12535 #:asdf-message
12536 #:*user-cache*
12537 #:user-output-translations-pathname
12538 #:system-output-translations-pathname
12539 #:user-output-translations-directory-pathname
12540 #:system-output-translations-directory-pathname
12541 #:user-source-registry
12542 #:system-source-registry
12543 #:user-source-registry-directory
12544 #:system-source-registry-directory
12545 ))
12546
12547 ;;;; ---------------------------------------------------------------------------
12548 ;;;; ASDF-USER, where the action happens.
12549
12550 (uiop/package:define-package :asdf/user
12551 (:nicknames :asdf-user)
12552 ;; NB: releases before 3.1.2 this :use'd only uiop/package instead of uiop below.
12553 ;; They also :use'd uiop/common-lisp, that reexports common-lisp and is not included in uiop.
12554 ;; ASDF3 releases from 2.27 to 2.31 called uiop asdf-driver and asdf/foo uiop/foo.
12555 ;; ASDF1 and ASDF2 releases (2.26 and earlier) create a temporary package
12556 ;; that only :use's :cl and :asdf
12557 (:use :uiop/common-lisp :uiop :asdf/interface))
12558 ;;;; -----------------------------------------------------------------------
12559 ;;;; ASDF Footer: last words and cleanup
12560
12561 (uiop/package:define-package :asdf/footer
12562 (:recycle :asdf/footer :asdf)
12563 (:use :uiop/common-lisp :uiop
12564 :asdf/upgrade :asdf/find-system :asdf/operate :asdf/bundle)
12565 ;; Happily, all those implementations all have the same module-provider hook interface.
12566 #+(or abcl clasp cmucl clozure ecl mkcl sbcl)
12567 (:import-from #+abcl :sys #+(or clasp cmucl ecl) :ext #+clozure :ccl #+mkcl :mk-ext #+sbcl sb-ext
12568 #:*module-provider-functions*
12569 #+ecl #:*load-hooks*)
12570 #+(or clasp mkcl) (:import-from :si #:*load-hooks*))
12571
12572 (in-package :asdf/footer)
12573
12574 ;;;; Register ASDF itself and all its subsystems as preloaded.
12575 (with-upgradability ()
12576 (dolist (s '("asdf" "uiop" "asdf-defsystem" "asdf-package-system"))
12577 ;; Don't bother with these system names, no one relies on them anymore:
12578 ;; "asdf-utils" "asdf-bundle" "asdf-driver"
12579 (register-preloaded-system s :version *asdf-version*)))
12580
12581
12582 ;;;; Hook ASDF into the implementation's REQUIRE and other entry points.
12583 #+(or abcl clasp clisp clozure cmucl ecl mkcl sbcl)
12584 (with-upgradability ()
12585 ;; Hook into CL:REQUIRE.
12586 #-clisp (pushnew 'module-provide-asdf *module-provider-functions*)
12587 #+clisp (if-let (x (and #+clisp (find-symbol* '#:*module-provider-functions* :custom nil)))
12588 (eval `(pushnew 'module-provide-asdf ,x)))
12589
12590 #+(or clasp ecl mkcl)
12591 (progn
12592 (pushnew '("fasb" . si::load-binary) *load-hooks* :test 'equal :key 'car)
12593
12594 #+os-windows
12595 (unless (assoc "asd" *load-hooks* :test 'equal)
12596 (appendf *load-hooks* '(("asd" . si::load-source))))
12597
12598 ;; Wrap module provider functions in an idempotent, upgrade friendly way
12599 (defvar *wrapped-module-provider* (make-hash-table))
12600 (setf (gethash 'module-provide-asdf *wrapped-module-provider*) 'module-provide-asdf)
12601 (defun wrap-module-provider (provider name)
12602 (let ((results (multiple-value-list (funcall provider name))))
12603 (when (first results) (register-preloaded-system (coerce-name name)))
12604 (values-list results)))
12605 (defun wrap-module-provider-function (provider)
12606 (ensure-gethash provider *wrapped-module-provider*
12607 (constantly
12608 #'(lambda (module-name)
12609 (wrap-module-provider provider module-name)))))
12610 (setf *module-provider-functions*
12611 (mapcar #'wrap-module-provider-function *module-provider-functions*))))
12612
12613 #+cmucl ;; Hook into the CMUCL herald.
12614 (with-upgradability ()
12615 (defun herald-asdf (stream)
12616 (format stream " ASDF ~A" (asdf-version)))
12617 (setf (getf ext:*herald-items* :asdf) '(herald-asdf)))
12618
12619
12620 ;;;; Done!
12621 (with-upgradability ()
12622 #+allegro ;; restore *w-o-n-r-c* setting as saved in uiop/common-lisp
12623 (when (boundp 'excl:*warn-on-nested-reader-conditionals*)
12624 (setf excl:*warn-on-nested-reader-conditionals* uiop/common-lisp::*acl-warn-save*))
12625
12626 ;; Advertise the features we provide.
12627 (dolist (f '(:asdf :asdf2 :asdf3 :asdf3.1 :asdf-package-system)) (pushnew f *features*))
12628
12629 ;; Provide both lowercase and uppercase, to satisfy more people, especially LispWorks users.
12630 (provide "asdf") (provide "ASDF")
12631
12632 ;; Finally, call a function that will cleanup in case this is an upgrade of an older ASDF.
12633 (cleanup-upgraded-asdf))
12634
12635 (when *load-verbose*
12636 (asdf-message ";; ASDF, version ~a~%" (asdf-version)))