a2e61e18898c092d5ae4dc9dc4ff093d27c86392
[sbcl.git] / contrib / asdf / asdf.lisp
1 ;;; This is asdf: Another System Definition Facility.  1.72
2 ;;;
3 ;;; Feedback, bug reports, and patches are all welcome: please mail to
4 ;;; <cclan-list@lists.sf.net>.  But note first that the canonical
5 ;;; source for asdf is presently the cCLan CVS repository at
6 ;;; <URL:http://cvs.sourceforge.net/cgi-bin/viewcvs.cgi/cclan/asdf/>
7 ;;;
8 ;;; If you obtained this copy from anywhere else, and you experience
9 ;;; trouble using it, or find bugs, you may want to check at the
10 ;;; location above for a more recent version (and for documentation
11 ;;; and test files, if your copy came without them) before reporting
12 ;;; bugs.  There are usually two "supported" revisions - the CVS HEAD
13 ;;; is the latest development version, whereas the revision tagged
14 ;;; RELEASE may be slightly older but is considered `stable'
15
16 ;;; Copyright (c) 2001-2003 Daniel Barlow and contributors
17 ;;;
18 ;;; Permission is hereby granted, free of charge, to any person obtaining
19 ;;; a copy of this software and associated documentation files (the
20 ;;; "Software"), to deal in the Software without restriction, including
21 ;;; without limitation the rights to use, copy, modify, merge, publish,
22 ;;; distribute, sublicense, and/or sell copies of the Software, and to
23 ;;; permit persons to whom the Software is furnished to do so, subject to
24 ;;; the following conditions:
25 ;;;
26 ;;; The above copyright notice and this permission notice shall be
27 ;;; included in all copies or substantial portions of the Software.
28 ;;;
29 ;;; THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
30 ;;; EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
31 ;;; MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
32 ;;; NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
33 ;;; LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
34 ;;; OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
35 ;;; WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
36
37 ;;; the problem with writing a defsystem replacement is bootstrapping:
38 ;;; we can't use defsystem to compile it.  Hence, all in one file
39
40 (defpackage #:asdf
41   (:export #:defsystem #:oos #:operate #:find-system #:run-shell-command
42            #:system-definition-pathname #:find-component ; miscellaneous
43            #:hyperdocumentation #:hyperdoc
44            
45            #:compile-op #:load-op #:load-source-op #:test-system-version
46            #:test-op
47            #:operation                  ; operations
48            #:feature                    ; sort-of operation
49            #:version                    ; metaphorically sort-of an operation
50            
51            #:output-files #:perform     ; operation methods
52            #:operation-done-p #:explain
53            
54            #:component #:source-file 
55            #:c-source-file #:cl-source-file #:java-source-file
56            #:static-file
57            #:doc-file
58            #:html-file
59            #:text-file
60            #:source-file-type
61            #:module                     ; components
62            #:system
63            #:unix-dso
64            
65            #:module-components          ; component accessors
66            #:component-pathname
67            #:component-relative-pathname
68            #:component-name
69            #:component-version
70            #:component-parent
71            #:component-property
72            
73            #:component-depends-on
74            
75            ;#:*component-parent-pathname* 
76            #:*central-registry*         ; variables
77            
78            #:operation-error #:compile-failed #:compile-warned #:compile-error
79            #:system-definition-error 
80            #:missing-component
81            #:missing-dependency
82            #:circular-dependency        ; errors
83            )
84   (:use :cl))
85
86 #+nil
87 (error "The author of this file habitually uses #+nil to comment out forms.  But don't worry, it was unlikely to work in the New Implementation of Lisp anyway")
88
89
90 (in-package #:asdf)
91
92 (defvar *asdf-revision* (let* ((v "1.72")
93                                (colon (or (position #\: v) -1))
94                                (dot (position #\. v)))
95                           (and v colon dot 
96                                (list (parse-integer v :start (1+ colon)
97                                                     :junk-allowed t)
98                                      (parse-integer v :start (1+ dot)
99                                                     :junk-allowed t)))))
100
101 (defvar  *compile-file-warnings-behaviour* :warn)
102 (defvar  *compile-file-failure-behaviour* #+sbcl :error #-sbcl :warn)
103
104 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
105 ;; utility stuff
106
107 (defmacro aif (test then &optional else)
108   `(let ((it ,test)) (if it ,then ,else)))
109
110 (defun pathname-sans-name+type (pathname)
111   "Returns a new pathname with same HOST, DEVICE, DIRECTORY as PATHNAME,
112 and NIL NAME and TYPE components"
113   (make-pathname :name nil :type nil :defaults pathname))
114
115 (define-modify-macro appendf (&rest args) 
116                      append "Append onto list") 
117
118 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
119 ;; classes, condiitons
120
121 (define-condition system-definition-error (error) ()
122   ;; [this use of :report should be redundant, but unfortunately it's not.
123   ;; cmucl's lisp::output-instance prefers the kernel:slot-class-print-function
124   ;; over print-object; this is always conditions::%print-condition for
125   ;; condition objects, which in turn does inheritance of :report options at
126   ;; run-time.  fortunately, inheritance means we only need this kludge here in
127   ;; order to fix all conditions that build on it.  -- rgr, 28-Jul-02.]
128   #+cmu (:report print-object))
129
130 (define-condition formatted-system-definition-error (system-definition-error)
131   ((format-control :initarg :format-control :reader format-control)
132    (format-arguments :initarg :format-arguments :reader format-arguments))
133   (:report (lambda (c s)
134              (apply #'format s (format-control c) (format-arguments c)))))
135
136 (define-condition circular-dependency (system-definition-error)
137   ((components :initarg :components :reader circular-dependency-components)))
138
139 (define-condition missing-component (system-definition-error)
140   ((requires :initform "(unnamed)" :reader missing-requires :initarg :requires)
141    (version :initform nil :reader missing-version :initarg :version)
142    (parent :initform nil :reader missing-parent :initarg :parent)))
143
144 (define-condition missing-dependency (missing-component)
145   ((required-by :initarg :required-by :reader missing-required-by)))
146
147 (define-condition operation-error (error)
148   ((component :reader error-component :initarg :component)
149    (operation :reader error-operation :initarg :operation))
150   (:report (lambda (c s)
151              (format s (formatter "~@<erred while invoking ~A on ~A~@:>")
152                      (error-operation c) (error-component c)))))
153 (define-condition compile-error (operation-error) ())
154 (define-condition compile-failed (compile-error) ())
155 (define-condition compile-warned (compile-error) ())
156
157 (defclass component ()
158   ((name :type string :accessor component-name :initarg :name :documentation
159          "Component name, restricted to portable pathname characters")
160    (version :accessor component-version :initarg :version)
161    (in-order-to :initform nil :initarg :in-order-to)
162    ;;; XXX crap name
163    (do-first :initform nil :initarg :do-first)
164    ;; methods defined using the "inline" style inside a defsystem form:
165    ;; need to store them somewhere so we can delete them when the system
166    ;; is re-evaluated
167    (inline-methods :accessor component-inline-methods :initform nil)
168    (parent :initarg :parent :initform nil :reader component-parent)
169    ;; no direct accessor for pathname, we do this as a method to allow
170    ;; it to default in funky ways if not supplied
171    (relative-pathname :initarg :pathname)
172    (operation-times :initform (make-hash-table )
173                     :accessor component-operation-times)
174    ;; XXX we should provide some atomic interface for updating the
175    ;; component properties
176    (properties :accessor component-properties :initarg :properties
177                :initform nil)))
178
179 ;;;; methods: conditions
180
181 (defmethod print-object ((c missing-dependency) s)
182   (format s (formatter "~@<~A, required by ~A~@:>")
183           (call-next-method c nil)
184           (missing-required-by c)))
185
186 (defun sysdef-error (format &rest arguments)
187   (error 'formatted-system-definition-error :format-control format :format-arguments arguments))
188
189 ;;;; methods: components
190
191 (defmethod print-object ((c missing-component) s)
192   (format s (formatter "~@<component ~S not found~
193                         ~@[ or does not match version ~A~]~
194                         ~@[ in ~A~]~@:>")
195           (missing-requires c)
196           (missing-version c)
197           (when (missing-parent c)
198             (component-name (missing-parent c)))))
199
200 (defgeneric component-system (component)
201   (:documentation "Find the top-level system containing COMPONENT"))
202   
203 (defmethod component-system ((component component))
204   (aif (component-parent component)
205        (component-system it)
206        component))
207
208 (defmethod print-object ((c component) stream)
209   (print-unreadable-object (c stream :type t :identity t)
210     (ignore-errors
211       (prin1 (component-name c) stream))))
212
213 (defclass module (component)
214   ((components :initform nil :accessor module-components :initarg :components)
215    ;; what to do if we can't satisfy a dependency of one of this module's
216    ;; components.  This allows a limited form of conditional processing
217    (if-component-dep-fails :initform :fail
218                            :accessor module-if-component-dep-fails
219                            :initarg :if-component-dep-fails)
220    (default-component-class :accessor module-default-component-class
221      :initform 'cl-source-file :initarg :default-component-class)))
222
223 (defgeneric component-pathname (component)
224   (:documentation "Extracts the pathname applicable for a particular component."))
225
226 (defun component-parent-pathname (component)
227   (aif (component-parent component)
228        (component-pathname it)
229        *default-pathname-defaults*))
230
231 (defgeneric component-relative-pathname (component)
232   (:documentation "Extracts the relative pathname applicable for a particular component."))
233    
234 (defmethod component-relative-pathname ((component module))
235   (or (slot-value component 'relative-pathname)
236       (make-pathname
237        :directory `(:relative ,(component-name component))
238        :host (pathname-host (component-parent-pathname component)))))
239
240 (defmethod component-pathname ((component component))
241   (let ((*default-pathname-defaults* (component-parent-pathname component)))
242     (merge-pathnames (component-relative-pathname component))))
243
244 (defgeneric component-property (component property))
245
246 (defmethod component-property ((c component) property)
247   (cdr (assoc property (slot-value c 'properties))))
248
249 (defgeneric (setf component-property) (new-value component property))
250
251 (defmethod (setf component-property) (new-value (c component) property)
252   (let ((a (assoc property (slot-value c 'properties))))
253     (if a
254         (setf (cdr a) new-value)
255         (setf (slot-value c 'properties)
256               (acons property new-value (slot-value c 'properties))))))
257
258
259
260 (defclass system (module)
261   ((description :accessor system-description :initarg :description)
262    (long-description :accessor long-description :initarg :long-description)
263    (author :accessor system-author :initarg :author)
264    (maintainer :accessor system-maintainer :initarg :maintainer)
265    (licence :accessor system-licence :initarg :licence)))
266
267 ;;; version-satisfies
268
269 ;;; with apologies to christophe rhodes ...
270 (defun split (string &optional max (ws '(#\Space #\Tab)))
271   (flet ((is-ws (char) (find char ws)))
272     (nreverse
273      (let ((list nil) (start 0) (words 0) end)
274        (loop
275         (when (and max (>= words (1- max)))
276           (return (cons (subseq string start) list)))
277         (setf end (position-if #'is-ws string :start start))
278         (push (subseq string start end) list)
279         (incf words)
280         (unless end (return list))
281         (setf start (1+ end)))))))
282
283 (defgeneric version-satisfies (component version))
284
285 (defmethod version-satisfies ((c component) version)
286   (unless (and version (slot-boundp c 'version))
287     (return-from version-satisfies t))
288   (let ((x (mapcar #'parse-integer
289                    (split (component-version c) nil '(#\.))))
290         (y (mapcar #'parse-integer
291                    (split version nil '(#\.)))))
292     (labels ((bigger (x y)
293                (cond ((not y) t)
294                      ((not x) nil)
295                      ((> (car x) (car y)) t)
296                      ((= (car x) (car y))
297                       (bigger (cdr x) (cdr y))))))
298       (and (= (car x) (car y))
299            (or (not (cdr y)) (bigger (cdr x) (cdr y)))))))
300
301 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
302 ;;; finding systems
303
304 (defvar *defined-systems* (make-hash-table :test 'equal))
305 (defun coerce-name (name)
306    (typecase name
307      (component (component-name name))
308      (symbol (string-downcase (symbol-name name)))
309      (string name)
310      (t (sysdef-error (formatter "~@<invalid component designator ~A~@:>")
311                       name))))
312
313 ;;; for the sake of keeping things reasonably neat, we adopt a
314 ;;; convention that functions in this list are prefixed SYSDEF-
315
316 (defvar *system-definition-search-functions*
317   '(sysdef-central-registry-search))
318
319 (defun system-definition-pathname (system)
320   (some (lambda (x) (funcall x system))
321         *system-definition-search-functions*))
322         
323 (defvar *central-registry*
324   '(*default-pathname-defaults*
325     #+nil "/home/dan/src/sourceforge/cclan/asdf/systems/"
326     #+nil "telent:asdf;systems;"))
327
328 (defun sysdef-central-registry-search (system)
329   (let ((name (coerce-name system)))
330     (block nil
331       (dolist (dir *central-registry*)
332         (let* ((defaults (eval dir))
333                (file (and defaults
334                           (make-pathname
335                            :defaults defaults :version :newest
336                            :name name :type "asd" :case :local))))
337           (if (and file (probe-file file))
338               (return file)))))))
339
340
341 (defun find-system (name &optional (error-p t))
342   (let* ((name (coerce-name name))
343          (in-memory (gethash name *defined-systems*))
344          (on-disk (system-definition-pathname name)))    
345     (when (and on-disk
346                (or (not in-memory)
347                    (< (car in-memory) (file-write-date on-disk))))
348       (let ((*package* (make-package (gensym (package-name #.*package*))
349                                      :use '(:cl :asdf))))
350         (format t
351                 (formatter "~&~@<; ~@;loading system definition from ~A into ~A~@:>~%")
352                 ;; FIXME: This wants to be (ENOUGH-NAMESTRING
353                 ;; ON-DISK), but CMUCL barfs on that.
354                 on-disk
355                 *package*)
356         (load on-disk)))
357     (let ((in-memory (gethash name *defined-systems*)))
358       (if in-memory
359           (progn (if on-disk (setf (car in-memory) (file-write-date on-disk)))
360                  (cdr in-memory))
361           (if error-p (error 'missing-component :requires name))))))
362
363 (defun register-system (name system)
364   (format t (formatter "~&~@<; ~@;registering ~A as ~A~@:>~%") system name)
365   (setf (gethash (coerce-name  name) *defined-systems*)
366         (cons (get-universal-time) system)))
367
368 (defun system-registered-p (name)
369   (gethash (coerce-name name) *defined-systems*))
370
371 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
372 ;;; finding components
373
374 (defgeneric find-component (module name &optional version)
375   (:documentation "Finds the component with name NAME present in the
376 MODULE module; if MODULE is nil, then the component is assumed to be a
377 system."))
378
379 (defmethod find-component ((module module) name &optional version)
380   (if (slot-boundp module 'components)
381       (let ((m (find name (module-components module)
382                      :test #'equal :key #'component-name)))
383         (if (and m (version-satisfies m version)) m))))
384             
385
386 ;;; a component with no parent is a system
387 (defmethod find-component ((module (eql nil)) name &optional version)
388   (let ((m (find-system name nil)))
389     (if (and m (version-satisfies m version)) m)))
390
391 ;;; component subclasses
392
393 (defclass source-file (component) ())
394
395 (defclass cl-source-file (source-file) ())
396 (defclass c-source-file (source-file) ())
397 (defclass java-source-file (source-file) ())
398 (defclass static-file (source-file) ())
399 (defclass doc-file (static-file) ())
400 (defclass html-file (doc-file) ())
401
402 (defgeneric source-file-type (component system))
403 (defmethod source-file-type ((c cl-source-file) (s module)) "lisp")
404 (defmethod source-file-type ((c c-source-file) (s module)) "c")
405 (defmethod source-file-type ((c java-source-file) (s module)) "java")
406 (defmethod source-file-type ((c html-file) (s module)) "html")
407 (defmethod source-file-type ((c static-file) (s module)) nil)
408
409 (defmethod component-relative-pathname ((component source-file))
410   (let* ((*default-pathname-defaults* (component-parent-pathname component))
411          (name-type
412           (make-pathname
413            :name (component-name component)
414            :type (source-file-type component
415                                    (component-system component)))))
416     (if (slot-value component 'relative-pathname)
417         (merge-pathnames
418          (slot-value component 'relative-pathname)
419          name-type)
420         name-type)))
421
422 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
423 ;;; operations
424
425 ;;; one of these is instantiated whenever (operate ) is called
426
427 (defclass operation ()
428   ((forced :initform nil :initarg :force :accessor operation-forced)
429    (original-initargs :initform nil :initarg :original-initargs
430                       :accessor operation-original-initargs)
431    (visited-nodes :initform nil :accessor operation-visited-nodes)
432    (visiting-nodes :initform nil :accessor operation-visiting-nodes)
433    (parent :initform nil :initarg :parent :accessor operation-parent)))
434
435 (defmethod print-object ((o operation) stream)
436   (print-unreadable-object (o stream :type t :identity t)
437     (ignore-errors
438       (prin1 (operation-original-initargs o) stream))))
439
440 (defmethod shared-initialize :after ((operation operation) slot-names
441                                      &key force 
442                                      &allow-other-keys)
443   (declare (ignore slot-names force))
444   ;; empty method to disable initarg validity checking
445   )
446
447 (defgeneric perform (operation component))
448 (defgeneric operation-done-p (operation component))
449 (defgeneric explain (operation component))
450 (defgeneric output-files (operation component))
451 (defgeneric input-files (operation component))
452
453 (defun node-for (o c)
454   (cons (class-name (class-of o)) c))
455
456 (defgeneric operation-ancestor (operation)
457   (:documentation   "Recursively chase the operation's parent pointer until we get to the head of the tree"))
458
459 (defmethod operation-ancestor ((operation operation))
460   (aif (operation-parent operation)
461        (operation-ancestor it)
462        operation))
463
464
465 (defun make-sub-operation (c o dep-c dep-o)
466   (let* ((args (copy-list (operation-original-initargs o)))
467          (force-p (getf args :force)))
468     ;; note explicit comparison with T: any other non-NIL force value
469     ;; (e.g. :recursive) will pass through
470     (cond ((and (null (component-parent c))
471                 (null (component-parent dep-c))
472                 (not (eql c dep-c)))
473            (when (eql force-p t)
474              (setf (getf args :force) nil))
475            (apply #'make-instance dep-o
476                   :parent o
477                   :original-initargs args args))
478           ((subtypep (type-of o) dep-o)
479            o)
480           (t 
481            (apply #'make-instance dep-o
482                   :parent o :original-initargs args args)))))
483
484
485 (defgeneric visit-component (operation component data))
486
487 (defmethod visit-component ((o operation) (c component) data)
488   (unless (component-visited-p o c)
489     (push (cons (node-for o c) data)
490           (operation-visited-nodes (operation-ancestor o)))))
491
492 (defgeneric component-visited-p (operation component))
493
494 (defmethod component-visited-p ((o operation) (c component))
495   (assoc (node-for o c)
496          (operation-visited-nodes (operation-ancestor o))
497          :test 'equal))
498
499 (defgeneric (setf visiting-component) (new-value operation component))
500
501 (defmethod (setf visiting-component) (new-value operation component)
502   ;; MCL complains about unused lexical variables
503   (declare (ignorable new-value operation component)))
504
505 (defmethod (setf visiting-component) (new-value (o operation) (c component))
506   (let ((node (node-for o c))
507         (a (operation-ancestor o)))
508     (if new-value
509         (pushnew node (operation-visiting-nodes a) :test 'equal)
510         (setf (operation-visiting-nodes a)
511               (remove node  (operation-visiting-nodes a) :test 'equal)))))
512
513 (defgeneric component-visiting-p (operation component))
514
515 (defmethod component-visiting-p ((o operation) (c component))
516   (let ((node (cons o c)))
517     (member node (operation-visiting-nodes (operation-ancestor o))
518             :test 'equal)))
519
520 (defgeneric component-depends-on (operation component))
521
522 (defmethod component-depends-on ((o operation) (c component))
523   (cdr (assoc (class-name (class-of o))
524               (slot-value c 'in-order-to))))
525
526 (defgeneric component-self-dependencies (operation component))
527
528 (defmethod component-self-dependencies ((o operation) (c component))
529   (let ((all-deps (component-depends-on o c)))
530     (remove-if-not (lambda (x)
531                      (member (component-name c) (cdr x) :test #'string=))
532                    all-deps)))
533     
534 (defmethod input-files ((operation operation) (c component))
535   (let ((parent (component-parent c))
536         (self-deps (component-self-dependencies operation c)))
537     (if self-deps
538         (mapcan (lambda (dep)
539                   (destructuring-bind (op name) dep
540                     (output-files (make-instance op)
541                                   (find-component parent name))))
542                 self-deps)
543         ;; no previous operations needed?  I guess we work with the 
544         ;; original source file, then
545         (list (component-pathname c)))))
546
547 (defmethod input-files ((operation operation) (c module)) nil)
548
549 (defmethod operation-done-p ((o operation) (c component))
550   (let ((out-files (output-files o c))
551         (in-files (input-files o c)))
552     (cond ((and (not in-files) (not out-files))
553            ;; arbitrary decision: an operation that uses nothing to
554            ;; produce nothing probably isn't doing much 
555            t)
556           ((not out-files) 
557            (let ((op-done
558                   (gethash (type-of o)
559                            (component-operation-times c))))
560              (and op-done
561                   (>= op-done
562                       (or (apply #'max
563                                  (mapcar #'file-write-date in-files)) 0)))))
564           ((not in-files) nil)
565           (t
566            (and
567             (every #'probe-file out-files)
568             (> (apply #'min (mapcar #'file-write-date out-files))
569                (apply #'max (mapcar #'file-write-date in-files)) ))))))
570
571 ;;; So you look at this code and think "why isn't it a bunch of
572 ;;; methods".  And the answer is, because standard method combination
573 ;;; runs :before methods most->least-specific, which is back to front
574 ;;; for our purposes.  And CLISP doesn't have non-standard method
575 ;;; combinations, so let's keep it simple and aspire to portability
576
577 (defgeneric traverse (operation component))
578 (defmethod traverse ((operation operation) (c component))
579   (let ((forced nil))
580     (labels ((do-one-dep (required-op required-c required-v)
581                (let* ((dep-c (or (find-component
582                                   (component-parent c)
583                                   ;; XXX tacky.  really we should build the
584                                   ;; in-order-to slot with canonicalized
585                                   ;; names instead of coercing this late
586                                   (coerce-name required-c) required-v)
587                                  (error 'missing-dependency :required-by c
588                                         :version required-v
589                                         :requires required-c)))
590                       (op (make-sub-operation c operation dep-c required-op)))
591                  (traverse op dep-c)))             
592              (do-dep (op dep)
593                (cond ((eq op 'feature)
594                       (or (member (car dep) *features*)
595                           (error 'missing-dependency :required-by c
596                                  :requires (car dep) :version nil)))
597                      (t
598                       (dolist (d dep)
599                         (cond ((consp d)
600                                (assert (string-equal
601                                         (symbol-name (first d))
602                                         "VERSION"))
603                                (appendf forced
604                                         (do-one-dep op (second d) (third d))))
605                               (t
606                                (appendf forced (do-one-dep op d nil)))))))))
607       (aif (component-visited-p operation c)
608            (return-from traverse
609              (if (cdr it) (list (cons 'pruned-op c)) nil)))
610       ;; dependencies
611       (if (component-visiting-p operation c)
612           (error 'circular-dependency :components (list c)))
613       (setf (visiting-component operation c) t)
614       (loop for (required-op . deps) in (component-depends-on operation c)
615             do (do-dep required-op deps))
616       ;; constituent bits
617       (let ((module-ops
618              (when (typep c 'module)
619                (let ((at-least-one nil)
620                      (forced nil)
621                      (error nil))
622                  (loop for kid in (module-components c)
623                        do (handler-case
624                               (appendf forced (traverse operation kid ))
625                             (missing-dependency (condition)
626                               (if (eq (module-if-component-dep-fails c) :fail)
627                                   (error condition))
628                               (setf error condition))
629                             (:no-error (c)
630                               (declare (ignore c))
631                               (setf at-least-one t))))
632                  (when (and (eq (module-if-component-dep-fails c) :try-next)
633                             (not at-least-one))
634                    (error error))
635                  forced))))
636         ;; now the thing itself
637         (when (or forced module-ops
638                   (not (operation-done-p operation c))
639                   (let ((f (operation-forced (operation-ancestor operation))))
640                     (and f (or (not (consp f))
641                                (member (component-name
642                                         (operation-ancestor operation))
643                                        (mapcar #'coerce-name f)
644                                        :test #'string=)))))
645           (let ((do-first (cdr (assoc (class-name (class-of operation))
646                                       (slot-value c 'do-first)))))
647             (loop for (required-op . deps) in do-first
648                   do (do-dep required-op deps)))
649           (setf forced (append (delete 'pruned-op forced :key #'car)
650                                (delete 'pruned-op module-ops :key #'car)
651                                (list (cons operation c))))))
652       (setf (visiting-component operation c) nil)
653       (visit-component operation c (and forced t))
654       forced)))
655   
656
657 (defmethod perform ((operation operation) (c source-file))
658   (sysdef-error
659    (formatter "~@<required method PERFORM not implemented~
660                for operation ~A, component ~A~@:>")
661    (class-of operation) (class-of c)))
662
663 (defmethod perform ((operation operation) (c module))
664   nil)
665
666 (defmethod explain ((operation operation) (component component))
667   (format *trace-output* "~&;;; ~A on ~A~%"
668           operation component))
669
670 ;;; compile-op
671
672 (defclass compile-op (operation)
673   ((proclamations :initarg :proclamations :accessor compile-op-proclamations :initform nil)
674    (on-warnings :initarg :on-warnings :accessor operation-on-warnings
675                 :initform *compile-file-warnings-behaviour*)
676    (on-failure :initarg :on-failure :accessor operation-on-failure
677                :initform *compile-file-failure-behaviour*)))
678
679 (defmethod perform :before ((operation compile-op) (c source-file))
680   (map nil #'ensure-directories-exist (output-files operation c)))
681
682 (defmethod perform :after ((operation operation) (c component))
683   (setf (gethash (type-of operation) (component-operation-times c))
684         (get-universal-time)))
685
686 ;;; perform is required to check output-files to find out where to put
687 ;;; its answers, in case it has been overridden for site policy
688 (defmethod perform ((operation compile-op) (c cl-source-file))
689   (let ((source-file (component-pathname c))
690         (output-file (car (output-files operation c))))
691     (multiple-value-bind (output warnings-p failure-p)
692         (compile-file source-file
693                       :output-file output-file)
694       ;(declare (ignore output))
695       (when warnings-p
696         (case (operation-on-warnings operation)
697           (:warn (warn "COMPILE-FILE warned while performing ~A on ~A"
698                        c operation))
699           (:error (error 'compile-warned :component c :operation operation))
700           (:ignore nil)))
701       (when failure-p
702         (case (operation-on-failure operation)
703           (:warn (warn "COMPILE-FILE failed while performing ~A on ~A"
704                        c operation))
705           (:error (error 'compile-failed :component c :operation operation))
706           (:ignore nil)))
707       (unless output
708         (error 'compile-error :component c :operation operation)))))
709
710 (defmethod output-files ((operation compile-op) (c cl-source-file))
711   (list (compile-file-pathname (component-pathname c))))
712
713 (defmethod perform ((operation compile-op) (c static-file))
714   nil)
715
716 (defmethod output-files ((operation compile-op) (c static-file))
717   nil)
718
719 ;;; load-op
720
721 (defclass load-op (operation) ())
722
723 (defmethod perform ((o load-op) (c cl-source-file))
724   (mapcar #'load (input-files o c)))
725
726 (defmethod perform ((operation load-op) (c static-file))
727   nil)
728 (defmethod operation-done-p ((operation load-op) (c static-file))
729   t)
730
731 (defmethod output-files ((o operation) (c component))
732   nil)
733
734 (defmethod component-depends-on ((operation load-op) (c component))
735   (cons (list 'compile-op (component-name c))
736         (call-next-method)))
737
738 ;;; load-source-op
739
740 (defclass load-source-op (operation) ())
741
742 (defmethod perform ((o load-source-op) (c cl-source-file))
743   (let ((source (component-pathname c)))
744     (setf (component-property c 'last-loaded-as-source)
745           (and (load source)
746                (get-universal-time)))))
747
748 (defmethod perform ((operation load-source-op) (c static-file))
749   nil)
750
751 (defmethod output-files ((operation load-source-op) (c component))
752   nil)
753
754 ;;; FIXME: we simply copy load-op's dependencies.  this is Just Not Right.
755 (defmethod component-depends-on ((o load-source-op) (c component))
756   (let ((what-would-load-op-do (cdr (assoc 'load-op
757                                            (slot-value c 'in-order-to)))))
758     (mapcar (lambda (dep)
759               (if (eq (car dep) 'load-op)
760                   (cons 'load-source-op (cdr dep))
761                   dep))
762             what-would-load-op-do)))
763
764 (defmethod operation-done-p ((o load-source-op) (c source-file))
765   (if (or (not (component-property c 'last-loaded-as-source))
766           (> (file-write-date (component-pathname c))
767              (component-property c 'last-loaded-as-source)))
768       nil t))
769
770 (defclass test-op (operation) ())
771
772 (defmethod perform ((operation test-op) (c component))
773   nil)
774
775 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
776 ;;; invoking operations
777
778 (defun operate (operation-class system &rest args)
779   (let* ((op (apply #'make-instance operation-class
780                     :original-initargs args args))
781          (system (if (typep system 'component) system (find-system system)))
782          (steps (traverse op system)))
783     (with-compilation-unit ()
784       (loop for (op . component) in steps do
785             (loop
786              (restart-case 
787                  (progn (perform op component)
788                         (return))
789                (retry-component ())
790                (skip-component () (return))))))))
791
792 (defun oos (&rest args)
793   "Alias of OPERATE function"
794   (apply #'operate args))
795
796 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
797 ;;; syntax
798
799 (defun remove-keyword (key arglist)
800   (labels ((aux (key arglist)
801              (cond ((null arglist) nil)
802                    ((eq key (car arglist)) (cddr arglist))
803                    (t (cons (car arglist) (cons (cadr arglist)
804                                                 (remove-keyword
805                                                  key (cddr arglist))))))))
806     (aux key arglist)))
807
808 (defmacro defsystem (name &body options)
809   (destructuring-bind (&key pathname (class 'system) &allow-other-keys) options
810     (let ((component-options (remove-keyword :class options)))
811       `(progn
812         ;; system must be registered before we parse the body, otherwise
813         ;; we recur when trying to find an existing system of the same name
814         ;; to reuse options (e.g. pathname) from
815         (let ((s (system-registered-p ',name)))
816           (cond ((and s (eq (type-of (cdr s)) ',class))
817                  (setf (car s) (get-universal-time)))
818                 (s
819                  #+clisp
820                  (sysdef-error "Cannot redefine the existing system ~A with a different class" s)
821                  #-clisp
822                  (change-class (cdr s) ',class))
823                 (t
824                  (register-system (quote ,name)
825                                   (make-instance ',class :name ',name)))))
826         (parse-component-form nil (apply
827                                    #'list
828                                    :module (coerce-name ',name)
829                                    :pathname
830                                    (or ,pathname
831                                        (pathname-sans-name+type
832                                         (resolve-symlinks *load-truename*))
833                                        *default-pathname-defaults*)
834                                    ',component-options))))))
835   
836
837 (defun class-for-type (parent type)
838   (let ((class (find-class
839                 (or (find-symbol (symbol-name type) *package*)
840                     (find-symbol (symbol-name type) #.*package*)) nil)))
841     (or class
842         (and (eq type :file)
843              (or (module-default-component-class parent)
844                  (find-class 'cl-source-file)))
845         (sysdef-error (formatter "~@<don't recognize component type ~A~@:>")
846                       type))))
847
848 (defun maybe-add-tree (tree op1 op2 c)
849   "Add the node C at /OP1/OP2 in TREE, unless it's there already.
850 Returns the new tree (which probably shares structure with the old one)"
851   (let ((first-op-tree (assoc op1 tree)))
852     (if first-op-tree
853         (progn
854           (aif (assoc op2 (cdr first-op-tree))
855                (if (find c (cdr it))
856                    nil
857                    (setf (cdr it) (cons c (cdr it))))
858                (setf (cdr first-op-tree)
859                      (acons op2 (list c) (cdr first-op-tree))))
860           tree)
861         (acons op1 (list (list op2 c)) tree))))
862                 
863 (defun union-of-dependencies (&rest deps)
864   (let ((new-tree nil))
865     (dolist (dep deps)
866       (dolist (op-tree dep)
867         (dolist (op  (cdr op-tree))
868           (dolist (c (cdr op))
869             (setf new-tree
870                   (maybe-add-tree new-tree (car op-tree) (car op) c))))))
871     new-tree))
872
873
874 (defun remove-keys (key-names args)
875   (loop for ( name val ) on args by #'cddr
876         unless (member (symbol-name name) key-names 
877                        :key #'symbol-name :test 'equal)
878         append (list name val)))
879
880 (defvar *serial-depends-on*)
881
882 (defun parse-component-form (parent options)
883   (destructuring-bind
884         (type name &rest rest &key
885               ;; the following list of keywords is reproduced below in the
886               ;; remove-keys form.  important to keep them in sync
887               components pathname default-component-class
888               perform explain output-files operation-done-p
889               depends-on serial in-order-to
890               ;; list ends
891               &allow-other-keys) options
892     (check-component-input type name depends-on components in-order-to)
893     (let* ((other-args (remove-keys
894                         '(components pathname default-component-class
895                           perform explain output-files operation-done-p
896                           depends-on serial in-order-to)
897                         rest))
898            (ret
899             (or (find-component parent name)
900                 (make-instance (class-for-type parent type)))))
901       (when (boundp '*serial-depends-on*)
902         (setf depends-on
903               (concatenate 'list *serial-depends-on* depends-on)))
904       (apply #'reinitialize-instance
905              ret
906              :name (coerce-name name)
907              :pathname pathname
908              :parent parent
909              other-args)
910       (when (typep ret 'module)
911         (setf (module-default-component-class ret)
912               (or default-component-class
913                   (and (typep parent 'module)
914                        (module-default-component-class parent))))
915         (let ((*serial-depends-on* nil))
916           (setf (module-components ret)
917                 (loop for c-form in components
918                       for c = (parse-component-form ret c-form)
919                       collect c
920                       if serial
921                       do (push (component-name c) *serial-depends-on*)))))
922       
923       (setf (slot-value ret 'in-order-to)
924             (union-of-dependencies
925              in-order-to
926              `((compile-op (compile-op ,@depends-on))
927                (load-op (load-op ,@depends-on))))
928             (slot-value ret 'do-first) `((compile-op (load-op ,@depends-on))))
929       
930       (loop for (n v) in `((perform ,perform) (explain ,explain)
931                            (output-files ,output-files)
932                            (operation-done-p ,operation-done-p))
933             do (map 'nil
934                     ;; this is inefficient as most of the stored
935                     ;; methods will not be for this particular gf n
936                     ;; But this is hardly performance-critical
937                     (lambda (m) (remove-method (symbol-function n) m))
938                     (component-inline-methods ret))
939             when v
940             do (destructuring-bind (op qual (o c) &body body) v
941                  (pushnew
942                   (eval `(defmethod ,n ,qual ((,o ,op) (,c (eql ,ret)))
943                           ,@body))
944                   (component-inline-methods ret))))
945       ret)))
946
947 (defun check-component-input (type name depends-on components in-order-to)
948   "A partial test of the values of a component."
949   (unless (listp depends-on)
950     (sysdef-error-component ":depends-on must be a list."
951                             type name depends-on))
952   (unless (listp components)
953     (sysdef-error-component ":components must be NIL or a list of components."
954                             type name components))
955   (unless (and (listp in-order-to) (listp (car in-order-to)))
956     (sysdef-error-component ":in-order-to must be NIL or a list of components."
957                            type name in-order-to)))
958
959 (defun sysdef-error-component (msg type name value)
960   (sysdef-error (concatenate 'string msg
961                              "~&The value specified for ~(~A~) ~A is ~W")
962                 type name value))
963
964 (defun resolve-symlinks (path)
965   #-allegro (truename path)
966   #+allegro (excl:pathname-resolve-symbolic-links path)
967   )
968
969 ;;; optional extras
970
971 ;;; run-shell-command functions for other lisp implementations will be
972 ;;; gratefully accepted, if they do the same thing.  If the docstring
973 ;;; is ambiguous, send a bug report
974
975 (defun run-shell-command (control-string &rest args)
976   "Interpolate ARGS into CONTROL-STRING as if by FORMAT, and
977 synchronously execute the result using a Bourne-compatible shell, with
978 output to *trace-output*.  Returns the shell's exit code."
979   (let ((command (apply #'format nil control-string args)))
980     (format *trace-output* "; $ ~A~%" command)
981     #+sbcl
982     (sb-impl::process-exit-code
983      (sb-ext:run-program  
984       "/bin/sh"
985       (list  "-c" command)
986       :input nil :output *trace-output*))
987     
988     #+(or cmu scl)
989     (ext:process-exit-code
990      (ext:run-program  
991       "/bin/sh"
992       (list  "-c" command)
993       :input nil :output *trace-output*))
994
995     #+allegro
996     (excl:run-shell-command command :input nil :output *trace-output*)
997     
998     #+lispworks
999     (system:call-system-showing-output
1000      command
1001      :shell-type "/bin/sh"
1002      :output-stream *trace-output*)
1003     
1004     #+clisp                             ;XXX not exactly *trace-output*, I know
1005     (ext:run-shell-command  command :output :terminal :wait t)
1006
1007     #+openmcl
1008     (nth-value 1
1009                (ccl:external-process-status
1010                 (ccl:run-program "/bin/sh" (list "-c" command)
1011                                  :input nil :output *trace-output*
1012                                  :wait t)))
1013
1014     #-(or openmcl clisp lispworks allegro scl cmu sbcl)
1015     (error "RUN-SHELL-PROGRAM not implemented for this Lisp")
1016     ))
1017
1018
1019 (defgeneric hyperdocumentation (package name doc-type))
1020 (defmethod hyperdocumentation ((package symbol) name doc-type)
1021   (hyperdocumentation (find-package package) name doc-type))
1022
1023 (defun hyperdoc (name doc-type)
1024   (hyperdocumentation (symbol-package name) name doc-type))
1025
1026
1027 (pushnew :asdf *features*)
1028
1029 #+sbcl
1030 (eval-when (:compile-toplevel :load-toplevel :execute)
1031   (when (sb-ext:posix-getenv "SBCL_BUILDING_CONTRIB")
1032     (pushnew :sbcl-hooks-require *features*)))
1033
1034 #+(and sbcl sbcl-hooks-require)
1035 (progn
1036   (defun module-provide-asdf (name)
1037     (let ((system (asdf:find-system name nil)))
1038       (when system
1039         (asdf:operate 'asdf:load-op name)
1040         t)))
1041
1042   (pushnew
1043    '(merge-pathnames "systems/"
1044      (truename (sb-ext:posix-getenv "SBCL_HOME")))
1045    *central-registry*)
1046   
1047   (pushnew
1048    '(merge-pathnames "site-systems/"
1049      (truename (sb-ext:posix-getenv "SBCL_HOME")))
1050    *central-registry*)
1051   
1052   (pushnew
1053    '(merge-pathnames ".sbcl/systems/"
1054      (user-homedir-pathname))
1055    *central-registry*)
1056   
1057   (pushnew 'module-provide-asdf sb-ext:*module-provider-functions*))