162ba558bdcfcc6cd373afa0f6bfe781c76e29fa
[sbcl.git] / src / pcl / cpl.lisp
1 ;;;; This software is part of the SBCL system. See the README file for
2 ;;;; more information.
3
4 ;;;; This software is derived from software originally released by Xerox
5 ;;;; Corporation. Copyright and release statements follow. Later modifications
6 ;;;; to the software are in the public domain and are provided with
7 ;;;; absolutely no warranty. See the COPYING and CREDITS files for more
8 ;;;; information.
9
10 ;;;; copyright information from original PCL sources:
11 ;;;;
12 ;;;; Copyright (c) 1985, 1986, 1987, 1988, 1989, 1990 Xerox Corporation.
13 ;;;; All rights reserved.
14 ;;;;
15 ;;;; Use and copying of this software and preparation of derivative works based
16 ;;;; upon this software are permitted. Any distribution of this software or
17 ;;;; derivative works must comply with all applicable United States export
18 ;;;; control laws.
19 ;;;;
20 ;;;; This software is made available AS IS, and Xerox Corporation makes no
21 ;;;; warranty about the software, its performance or its conformity to any
22 ;;;; specification.
23
24 (in-package "SB-PCL")
25 \f
26 ;;; compute-class-precedence-list
27 ;;;
28 ;;; Knuth section 2.2.3 has some interesting notes on this.
29 ;;;
30 ;;; What appears here is basically the algorithm presented there.
31 ;;;
32 ;;; The key idea is that we use class-precedence-description (CPD) structures
33 ;;; to store the precedence information as we proceed. The CPD structure for
34 ;;; a class stores two critical pieces of information:
35 ;;;
36 ;;;  - a count of the number of "reasons" why the class can't go
37 ;;;    into the class precedence list yet.
38 ;;;
39 ;;;  - a list of the "reasons" this class prevents others from
40 ;;;    going in until after it
41 ;;
42 ;;; A "reason" is essentially a single local precedence constraint. If a
43 ;;; constraint between two classes arises more than once it generates more
44 ;;; than one reason. This makes things simpler, linear, and isn't a problem
45 ;;; as long as we make sure to keep track of each instance of a "reason".
46 ;;;
47 ;;; This code is divided into three phases.
48 ;;;
49 ;;;  - the first phase simply generates the CPD's for each of the class
50 ;;;    and its superclasses. The remainder of the code will manipulate
51 ;;;    these CPDs rather than the class objects themselves. At the end
52 ;;;    of this pass, the CPD-SUPERS field of a CPD is a list of the CPDs
53 ;;;    of the direct superclasses of the class.
54 ;;;
55 ;;;  - the second phase folds all the local constraints into the CPD
56 ;;;    structure. The CPD-COUNT of each CPD is built up, and the
57 ;;;    CPD-AFTER fields are augmented to include precedence constraints
58 ;;;    from the CPD-SUPERS field and from the order of classes in other
59 ;;;    CPD-SUPERS fields.
60 ;;;
61 ;;;    After this phase, the CPD-AFTER field of a class includes all the
62 ;;;    direct superclasses of the class plus any class that immediately
63 ;;;    follows the class in the direct superclasses of another. There
64 ;;;    can be duplicates in this list. The CPD-COUNT field is equal to
65 ;;;    the number of times this class appears in the CPD-AFTER field of
66 ;;;    all the other CPDs.
67 ;;;
68 ;;;  - In the third phase, classes are put into the precedence list one
69 ;;;    at a time, with only those classes with a CPD-COUNT of 0 being
70 ;;;    candidates for insertion. When a class is inserted , every CPD
71 ;;;    in its CPD-AFTER field has its count decremented.
72 ;;;
73 ;;;    In the usual case, there is only one candidate for insertion at
74 ;;;    any point. If there is more than one, the specified tiebreaker
75 ;;;    rule is used to choose among them.
76
77 (defmethod compute-class-precedence-list ((root slot-class))
78   (compute-std-cpl root (class-direct-superclasses root)))
79
80 (defstruct (class-precedence-description
81              (:conc-name nil)
82              (:print-object (lambda (obj str)
83                               (print-unreadable-object (obj str :type t)
84                                 (format str "~D" (cpd-count obj)))))
85              (:constructor make-cpd ()))
86   (cpd-class  nil)
87   (cpd-supers ())
88   (cpd-after  ())
89   (cpd-count  0))
90
91 (defun compute-std-cpl (class supers)
92   (cond ((null supers)                          ;First two branches of COND
93          (list class))                          ;are implementing the single
94         ((null (cdr supers))                    ;inheritance optimization.
95          (cons class
96                (compute-std-cpl (car supers)
97                                 (class-direct-superclasses (car supers)))))
98         (t
99          (multiple-value-bind (all-cpds nclasses)
100              (compute-std-cpl-phase-1 class supers)
101            (compute-std-cpl-phase-2 all-cpds)
102            (compute-std-cpl-phase-3 class all-cpds nclasses)))))
103
104 (defvar *compute-std-cpl-class->entry-table-size* 60)
105
106 (defun compute-std-cpl-phase-1 (class supers)
107   (let ((nclasses 0)
108         (all-cpds ())
109         (table (make-hash-table :size *compute-std-cpl-class->entry-table-size*
110                                 :test #'eq)))
111     (declare (fixnum nclasses))
112     (labels ((get-cpd (c)
113                (or (gethash c table)
114                    (setf (gethash c table) (make-cpd))))
115              (walk (c supers)
116                (if (forward-referenced-class-p c)
117                    (cpl-forward-referenced-class-error class c)
118                    (let ((cpd (get-cpd c)))
119                      (unless (cpd-class cpd)    ;If we have already done this
120                                                 ;class before, we can quit.
121                        (setf (cpd-class cpd) c)
122                        (incf nclasses)
123                        (push cpd all-cpds)
124                        (setf (cpd-supers cpd) (mapcar #'get-cpd supers))
125                        (dolist (super supers)
126                          (walk super (class-direct-superclasses super))))))))
127       (walk class supers)
128       (values all-cpds nclasses))))
129
130 (defun compute-std-cpl-phase-2 (all-cpds)
131   (dolist (cpd all-cpds)
132     (let ((supers (cpd-supers cpd)))
133       (when supers
134         (setf (cpd-after cpd) (nconc (cpd-after cpd) supers))
135         (incf (cpd-count (car supers)) 1)
136         (do* ((t1 supers t2)
137               (t2 (cdr t1) (cdr t1)))
138              ((null t2))
139           (incf (cpd-count (car t2)) 2)
140           (push (car t2) (cpd-after (car t1))))))))
141
142 (defun compute-std-cpl-phase-3 (class all-cpds nclasses)
143   (let ((candidates ())
144         (next-cpd nil)
145         (rcpl ()))
146
147     ;; We have to bootstrap the collection of those CPD's that
148     ;; have a zero count. Once we get going, we will maintain
149     ;; this list incrementally.
150     (dolist (cpd all-cpds)
151       (when (zerop (cpd-count cpd)) (push cpd candidates)))
152
153     (loop
154       (when (null candidates)
155
156         ;; If there are no candidates, and enough classes have been put
157         ;; into the precedence list, then we are all done. Otherwise
158         ;; it means there is a consistency problem.
159         (if (zerop nclasses)
160             (return (reverse rcpl))
161             (cpl-inconsistent-error class all-cpds)))
162
163       ;; Try to find the next class to put in from among the candidates.
164       ;; If there is only one, its easy, otherwise we have to use the
165       ;; famous RPG tiebreaker rule. There is some hair here to avoid
166       ;; having to call DELETE on the list of candidates. I dunno if
167       ;; its worth it but what the hell.
168       (setq next-cpd
169             (if (null (cdr candidates))
170                 (prog1 (car candidates)
171                        (setq candidates ()))
172                 (block tie-breaker
173                   (dolist (c rcpl)
174                     (let ((supers (class-direct-superclasses c)))
175                       (if (memq (cpd-class (car candidates)) supers)
176                           (return-from tie-breaker (pop candidates))
177                           (do ((loc candidates (cdr loc)))
178                               ((null (cdr loc)))
179                             (let ((cpd (cadr loc)))
180                               (when (memq (cpd-class cpd) supers)
181                                 (setf (cdr loc) (cddr loc))
182                                 (return-from tie-breaker cpd))))))))))
183       (decf nclasses)
184       (push (cpd-class next-cpd) rcpl)
185       (dolist (after (cpd-after next-cpd))
186         (when (zerop (decf (cpd-count after)))
187           (push after candidates))))))
188 \f
189 ;;;; support code for signalling nice error messages
190
191 (defun cpl-error (class format-string &rest format-args)
192   (error "While computing the class precedence list of the class ~A.~%~A"
193           (if (class-name class)
194               (format nil "named ~S" (class-name class))
195               class)
196           (apply #'format nil format-string format-args)))
197
198 (defun cpl-forward-referenced-class-error (class forward-class)
199   (flet ((class-or-name (class)
200            (if (class-name class)
201                (format nil "named ~S" (class-name class))
202                class)))
203     (let ((names (mapcar #'class-or-name
204                          (cdr (find-superclass-chain class forward-class)))))
205       (cpl-error class
206                  "The class ~A is a forward referenced class.~@
207                   The class ~A is ~A."
208                  (class-or-name forward-class)
209                  (class-or-name forward-class)
210                  (if (null (cdr names))
211                      (format nil
212                              "a direct superclass of the class ~A"
213                              (class-or-name class))
214                      (format nil
215                              "reached from the class ~A by following~@
216                               the direct superclass chain through: ~A~
217                               ~%  ending at the class ~A"
218                              (class-or-name class)
219                              (format nil
220                                      "~{~%  the class ~A,~}"
221                                      (butlast names))
222                              (car (last names))))))))
223
224 (defun find-superclass-chain (bottom top)
225   (labels ((walk (c chain)
226              (if (eq c top)
227                  (return-from find-superclass-chain (nreverse chain))
228                  (dolist (super (class-direct-superclasses c))
229                    (walk super (cons super chain))))))
230     (walk bottom (list bottom))))
231
232 (defun cpl-inconsistent-error (class all-cpds)
233   (let ((reasons (find-cycle-reasons all-cpds)))
234     (cpl-error class
235       "It is not possible to compute the class precedence list because~@
236        there ~A in the local precedence relations.~@
237        ~A because:~{~%  ~A~}."
238       (if (cdr reasons) "are circularities" "is a circularity")
239       (if (cdr reasons) "These arise" "This arises")
240       (format-cycle-reasons (apply #'append reasons)))))
241
242 (defun format-cycle-reasons (reasons)
243   (flet ((class-or-name (cpd)
244            (let ((class (cpd-class cpd)))
245              (if (class-name class)
246                  (format nil "named ~S" (class-name class))
247                  class))))
248     (mapcar
249       #'(lambda (reason)
250           (ecase (caddr reason)
251             (:super
252               (format
253                 nil
254                 "The class ~A appears in the supers of the class ~A."
255                 (class-or-name (cadr reason))
256                 (class-or-name (car reason))))
257             (:in-supers
258               (format
259                 nil
260                 "The class ~A follows the class ~A in the supers of the class ~A."
261                 (class-or-name (cadr reason))
262                 (class-or-name (car reason))
263                 (class-or-name (cadddr reason))))))
264       reasons)))
265
266 (defun find-cycle-reasons (all-cpds)
267   (let ((been-here ())     ; list of classes we have visited
268         (cycle-reasons ()))
269
270     (labels ((chase (path)
271                (if (memq (car path) (cdr path))
272                    (record-cycle (memq (car path) (nreverse path)))
273                    (unless (memq (car path) been-here)
274                      (push (car path) been-here)
275                      (dolist (after (cpd-after (car path)))
276                        (chase (cons after path))))))
277              (record-cycle (cycle)
278                (let ((reasons ()))
279                  (do* ((t1 cycle t2)
280                        (t2 (cdr t1) (cdr t1)))
281                       ((null t2))
282                    (let ((c1 (car t1))
283                          (c2 (car t2)))
284                      (if (memq c2 (cpd-supers c1))
285                          (push (list c1 c2 :super) reasons)
286                          (dolist (cpd all-cpds)
287                            (when (memq c2 (memq c1 (cpd-supers cpd)))
288                              (return
289                                (push (list c1 c2 :in-supers cpd) reasons)))))))
290                  (push (nreverse reasons) cycle-reasons))))
291
292       (dolist (cpd all-cpds)
293         (unless (zerop (cpd-count cpd))
294           (chase (list cpd))))
295
296       cycle-reasons)))
297