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