0.8.16.5: deoopsification
[sbcl.git] / src / code / condition.lisp
1 ;;;; stuff originally from CMU CL's error.lisp which can or should
2 ;;;; come late (mostly related to the CONDITION class itself)
3 ;;;;
4
5 ;;;; This software is part of the SBCL system. See the README file for
6 ;;;; more information.
7 ;;;;
8 ;;;; This software is derived from the CMU CL system, which was
9 ;;;; written at Carnegie Mellon University and released into the
10 ;;;; public domain. The software is in the public domain and is
11 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
12 ;;;; files for more information.
13
14 (in-package "SB!KERNEL")
15 \f
16 ;;;; the CONDITION class
17
18 (/show0 "condition.lisp 20")
19
20 (eval-when (:compile-toplevel :load-toplevel :execute)
21
22 (/show0 "condition.lisp 24")
23
24 (def!struct (condition-classoid (:include slot-classoid)
25                                 (:constructor make-condition-classoid))
26   ;; list of CONDITION-SLOT structures for the direct slots of this
27   ;; class
28   (slots nil :type list)
29   ;; list of CONDITION-SLOT structures for all of the effective class
30   ;; slots of this class
31   (class-slots nil :type list)
32   ;; report function or NIL
33   (report nil :type (or function null))
34   ;; list of alternating initargs and initforms
35   (default-initargs () :type list)
36   ;; class precedence list as a list of CLASS objects, with all
37   ;; non-CONDITION classes removed
38   (cpl () :type list)
39   ;; a list of all the effective instance allocation slots of this
40   ;; class that have a non-constant initform or default-initarg.
41   ;; Values for these slots must be computed in the dynamic
42   ;; environment of MAKE-CONDITION.
43   (hairy-slots nil :type list))
44
45 (/show0 "condition.lisp 49")
46
47 ) ; EVAL-WHEN
48
49 (!defstruct-with-alternate-metaclass condition
50   :slot-names (actual-initargs assigned-slots)
51   :boa-constructor %make-condition-object
52   :superclass-name instance
53   :metaclass-name condition-classoid
54   :metaclass-constructor make-condition-classoid
55   :dd-type structure)
56
57 (defun make-condition-object (actual-initargs)
58   (%make-condition-object actual-initargs nil))
59
60 (defstruct (condition-slot (:copier nil))
61   (name (missing-arg) :type symbol)
62   ;; list of all applicable initargs
63   (initargs (missing-arg) :type list)
64   ;; names of reader and writer functions
65   (readers (missing-arg) :type list)
66   (writers (missing-arg) :type list)
67   ;; true if :INITFORM was specified
68   (initform-p (missing-arg) :type (member t nil))
69   ;; If this is a function, call it with no args. Otherwise, it's the
70   ;; actual value.
71   (initform (missing-arg) :type t)
72   ;; allocation of this slot, or NIL until defaulted
73   (allocation nil :type (member :instance :class nil))
74   ;; If ALLOCATION is :CLASS, this is a cons whose car holds the value.
75   (cell nil :type (or cons null))
76   ;; slot documentation
77   (documentation nil :type (or string null)))
78
79 ;;; KLUDGE: It's not clear to me why CONDITION-CLASS has itself listed
80 ;;; in its CPL, while other classes derived from CONDITION-CLASS don't
81 ;;; have themselves listed in their CPLs. This behavior is inherited
82 ;;; from CMU CL, and didn't seem to be explained there, and I haven't
83 ;;; figured out whether it's right. -- WHN 19990612
84 (eval-when (:compile-toplevel :load-toplevel :execute)
85   (/show0 "condition.lisp 103")
86   (let ((condition-class (locally
87                            ;; KLUDGE: There's a DEFTRANSFORM
88                            ;; FIND-CLASSOID for constant class names
89                            ;; which creates fast but
90                            ;; non-cold-loadable, non-compact code. In
91                            ;; this context, we'd rather have compact,
92                            ;; cold-loadable code. -- WHN 19990928
93                            (declare (notinline find-classoid))
94                            (find-classoid 'condition))))
95     (setf (condition-classoid-cpl condition-class)
96           (list condition-class)))
97   (/show0 "condition.lisp 103"))
98
99 (setf (condition-classoid-report (locally
100                                    ;; KLUDGE: There's a DEFTRANSFORM
101                                    ;; FIND-CLASSOID for constant class
102                                    ;; names which creates fast but
103                                    ;; non-cold-loadable, non-compact
104                                    ;; code. In this context, we'd
105                                    ;; rather have compact,
106                                    ;; cold-loadable code. -- WHN
107                                    ;; 19990928
108                                    (declare (notinline find-classoid))
109                                    (find-classoid 'condition)))
110       (lambda (cond stream)
111         (format stream "Condition ~S was signalled." (type-of cond))))
112
113 (eval-when (:compile-toplevel :load-toplevel :execute)
114
115 (defun find-condition-layout (name parent-types)
116   (let* ((cpl (remove-duplicates
117                (reverse
118                 (reduce #'append
119                         (mapcar (lambda (x)
120                                   (condition-classoid-cpl
121                                    (find-classoid x)))
122                                 parent-types)))))
123          (cond-layout (info :type :compiler-layout 'condition))
124          (olayout (info :type :compiler-layout name))
125          ;; FIXME: Does this do the right thing in case of multiple
126          ;; inheritance? A quick look at DEFINE-CONDITION didn't make
127          ;; it obvious what ANSI intends to be done in the case of
128          ;; multiple inheritance, so it's not actually clear what the
129          ;; right thing is..
130          (new-inherits
131           (order-layout-inherits (concatenate 'simple-vector
132                                               (layout-inherits cond-layout)
133                                               (mapcar #'classoid-layout cpl)))))
134     (if (and olayout
135              (not (mismatch (layout-inherits olayout) new-inherits)))
136         olayout
137         (make-layout :classoid (make-undefined-classoid name)
138                      :inherits new-inherits
139                      :depthoid -1
140                      :length (layout-length cond-layout)))))
141
142 ) ; EVAL-WHEN
143
144 ;;; FIXME: ANSI's definition of DEFINE-CONDITION says
145 ;;;   Condition reporting is mediated through the PRINT-OBJECT method
146 ;;;   for the condition type in question, with *PRINT-ESCAPE* always
147 ;;;   being nil. Specifying (:REPORT REPORT-NAME) in the definition of
148 ;;;   a condition type C is equivalent to:
149 ;;;     (defmethod print-object ((x c) stream)
150 ;;;       (if *print-escape* (call-next-method) (report-name x stream)))
151 ;;; The current code doesn't seem to quite match that.
152 (def!method print-object ((x condition) stream)
153   (if *print-escape*
154       (print-unreadable-object (x stream :type t :identity t))
155       ;; KLUDGE: A comment from CMU CL here said
156       ;;   7/13/98 BUG? CPL is not sorted and results here depend on order of
157       ;;   superclasses in define-condition call!
158       (dolist (class (condition-classoid-cpl (classoid-of x))
159                      (error "no REPORT? shouldn't happen!"))
160         (let ((report (condition-classoid-report class)))
161           (when report
162             (return (funcall report x stream)))))))
163 \f
164 ;;;; slots of CONDITION objects
165
166 (defvar *empty-condition-slot* '(empty))
167
168 (defun find-slot-default (class slot)
169   (let ((initargs (condition-slot-initargs slot))
170         (cpl (condition-classoid-cpl class)))
171     (dolist (class cpl)
172       (let ((default-initargs (condition-classoid-default-initargs class)))
173         (dolist (initarg initargs)
174           (let ((val (getf default-initargs initarg *empty-condition-slot*)))
175             (unless (eq val *empty-condition-slot*)
176               (return-from find-slot-default
177                            (if (functionp val)
178                                (funcall val)
179                                val)))))))
180
181     (if (condition-slot-initform-p slot)
182         (let ((initform (condition-slot-initform slot)))
183           (if (functionp initform)
184               (funcall initform)
185               initform))
186         (error "unbound condition slot: ~S" (condition-slot-name slot)))))
187
188 (defun find-condition-class-slot (condition-class slot-name)
189   (dolist (sclass
190            (condition-classoid-cpl condition-class)
191            (error "There is no slot named ~S in ~S."
192                   slot-name condition-class))
193     (dolist (slot (condition-classoid-slots sclass))
194       (when (eq (condition-slot-name slot) slot-name)
195         (return-from find-condition-class-slot slot)))))
196
197 (defun condition-writer-function (condition new-value name)
198   (dolist (cslot (condition-classoid-class-slots
199                   (layout-classoid (%instance-layout condition)))
200                  (setf (getf (condition-assigned-slots condition) name)
201                        new-value))
202     (when (eq (condition-slot-name cslot) name)
203       (return (setf (car (condition-slot-cell cslot)) new-value)))))
204
205 (defun condition-reader-function (condition name)
206   (let ((class (layout-classoid (%instance-layout condition))))
207     (dolist (cslot (condition-classoid-class-slots class))
208       (when (eq (condition-slot-name cslot) name)
209         (return-from condition-reader-function
210                      (car (condition-slot-cell cslot)))))
211     (let ((val (getf (condition-assigned-slots condition) name
212                      *empty-condition-slot*)))
213       (if (eq val *empty-condition-slot*)
214           (let ((actual-initargs (condition-actual-initargs condition))
215                 (slot (find-condition-class-slot class name)))
216             (unless slot
217               (error "missing slot ~S of ~S" name condition))
218             (do ((initargs actual-initargs (cddr initargs)))
219                 ((endp initargs)
220                  (setf (getf (condition-assigned-slots condition) name)
221                        (find-slot-default class slot)))
222               (when (member (car initargs) (condition-slot-initargs slot))
223                 (return-from condition-reader-function
224                   (setf (getf (condition-assigned-slots condition)
225                               name)
226                         (cadr initargs))))))
227           val))))
228 \f
229 ;;;; MAKE-CONDITION
230
231 (defun make-condition (thing &rest args)
232   #!+sb-doc
233   "Make an instance of a condition object using the specified initargs."
234   ;; Note: ANSI specifies no exceptional situations in this function.
235   ;; signalling simple-type-error would not be wrong.
236   (let* ((thing (or (and (symbolp thing) (find-classoid thing nil))
237                     thing))
238          (class (typecase thing
239                   (condition-classoid thing)
240                   (classoid
241                    (error 'simple-type-error
242                           :datum thing
243                           :expected-type 'condition-class
244                           :format-control "~S is not a condition class."
245                           :format-arguments (list thing)))
246                   (t
247                    (error 'simple-type-error
248                           :datum thing
249                           :expected-type 'condition-class
250                           :format-control "bad thing for class argument:~%  ~S"
251                           :format-arguments (list thing)))))
252          (res (make-condition-object args)))
253     (setf (%instance-layout res) (classoid-layout class))
254     ;; Set any class slots with initargs present in this call.
255     (dolist (cslot (condition-classoid-class-slots class))
256       (dolist (initarg (condition-slot-initargs cslot))
257         (let ((val (getf args initarg *empty-condition-slot*)))
258           (unless (eq val *empty-condition-slot*)
259             (setf (car (condition-slot-cell cslot)) val)))))
260     ;; Default any slots with non-constant defaults now.
261     (dolist (hslot (condition-classoid-hairy-slots class))
262       (when (dolist (initarg (condition-slot-initargs hslot) t)
263               (unless (eq (getf args initarg *empty-condition-slot*)
264                           *empty-condition-slot*)
265                 (return nil)))
266         (setf (getf (condition-assigned-slots res) (condition-slot-name hslot))
267               (find-slot-default class hslot))))
268     res))
269 \f
270 ;;;; DEFINE-CONDITION
271
272 (eval-when (:compile-toplevel :load-toplevel :execute)
273 (defun %compiler-define-condition (name direct-supers layout
274                                    all-readers all-writers)
275   (with-single-package-locked-error 
276       (:symbol name "defining ~A as a condition")
277     (sb!xc:proclaim `(ftype (function (t) t) ,@all-readers))
278     (sb!xc:proclaim `(ftype (function (t t) t) ,@all-writers))
279     (multiple-value-bind (class old-layout)
280         (insured-find-classoid name
281                                #'condition-classoid-p
282                                #'make-condition-classoid)
283       (setf (layout-classoid layout) class)
284       (setf (classoid-direct-superclasses class)
285             (mapcar #'find-classoid direct-supers))
286       (cond ((not old-layout)
287              (register-layout layout))
288             ((not *type-system-initialized*)
289              (setf (layout-classoid old-layout) class)
290              (setq layout old-layout)
291              (unless (eq (classoid-layout class) layout)
292                (register-layout layout)))
293             ((redefine-layout-warning "current"
294                                       old-layout
295                                       "new"
296                                       (layout-length layout)
297                                       (layout-inherits layout)
298                                       (layout-depthoid layout))
299              (register-layout layout :invalidate t))
300             ((not (classoid-layout class))
301              (register-layout layout)))
302       
303       (setf (layout-info layout)
304             (locally
305                 ;; KLUDGE: There's a FIND-CLASS DEFTRANSFORM for constant class
306                 ;; names which creates fast but non-cold-loadable, non-compact
307                 ;; code. In this context, we'd rather have compact, cold-loadable
308                 ;; code. -- WHN 19990928
309                 (declare (notinline find-classoid))
310               (layout-info (classoid-layout (find-classoid 'condition)))))
311       
312       (setf (find-classoid name) class)
313       
314       ;; Initialize CPL slot.
315       (setf (condition-classoid-cpl class)
316             (remove-if-not #'condition-classoid-p 
317                            (std-compute-class-precedence-list class)))))
318   (values))
319 ) ; EVAL-WHEN
320
321 ;;; Compute the effective slots of CLASS, copying inherited slots and
322 ;;; destructively modifying direct slots.
323 ;;;
324 ;;; FIXME: It'd be nice to explain why it's OK to destructively modify
325 ;;; direct slots. Presumably it follows from the semantics of
326 ;;; inheritance and redefinition of conditions, but finding the cite
327 ;;; and documenting it here would be good. (Or, if this is not in fact
328 ;;; ANSI-compliant, fixing it would also be good.:-)
329 (defun compute-effective-slots (class)
330   (collect ((res (copy-list (condition-classoid-slots class))))
331     (dolist (sclass (cdr (condition-classoid-cpl class)))
332       (dolist (sslot (condition-classoid-slots sclass))
333         (let ((found (find (condition-slot-name sslot) (res)
334                            :key #'condition-slot-name)))
335           (cond (found
336                  (setf (condition-slot-initargs found)
337                        (union (condition-slot-initargs found)
338                               (condition-slot-initargs sslot)))
339                  (unless (condition-slot-initform-p found)
340                    (setf (condition-slot-initform-p found)
341                          (condition-slot-initform-p sslot))
342                    (setf (condition-slot-initform found)
343                          (condition-slot-initform sslot)))
344                  (unless (condition-slot-allocation found)
345                    (setf (condition-slot-allocation found)
346                          (condition-slot-allocation sslot))))
347                 (t
348                  (res (copy-structure sslot)))))))
349     (res)))
350
351 ;;; Early definitions of slot accessor creators.
352 ;;;
353 ;;; Slot accessors must be generic functions, but ANSI does not seem
354 ;;; to specify any of them, and we cannot support it before end of
355 ;;; warm init. So we use ordinary functions inside SBCL, and switch to
356 ;;; GFs only at the end of building.
357 (declaim (notinline install-condition-slot-reader
358                     install-condition-slot-writer))
359 (defun install-condition-slot-reader (name condition slot-name)
360   (declare (ignore condition))
361   (setf (fdefinition name)
362         (lambda (condition)
363           (condition-reader-function condition slot-name))))
364 (defun install-condition-slot-writer (name condition slot-name)
365   (declare (ignore condition))
366   (setf (fdefinition name)
367         (lambda (new-value condition)
368           (condition-writer-function condition new-value slot-name))))
369
370 (defun %define-condition (name parent-types layout slots documentation
371                           report default-initargs all-readers all-writers)
372   (with-single-package-locked-error 
373       (:symbol name "defining ~A as a condition")
374     (%compiler-define-condition name parent-types layout all-readers all-writers)
375     (let ((class (find-classoid name)))
376       (setf (condition-classoid-slots class) slots)
377       (setf (condition-classoid-report class) report)
378       (setf (condition-classoid-default-initargs class) default-initargs)
379       (setf (fdocumentation name 'type) documentation)
380       
381       (dolist (slot slots)
382         
383         ;; Set up reader and writer functions.
384         (let ((slot-name (condition-slot-name slot)))
385           (dolist (reader (condition-slot-readers slot))
386             (install-condition-slot-reader reader name slot-name))
387           (dolist (writer (condition-slot-writers slot))
388             (install-condition-slot-writer writer name slot-name))))
389       
390       ;; Compute effective slots and set up the class and hairy slots
391       ;; (subsets of the effective slots.)
392       (let ((eslots (compute-effective-slots class))
393             (e-def-initargs
394              (reduce #'append
395                      (mapcar #'condition-classoid-default-initargs
396                            (condition-classoid-cpl class)))))
397         (dolist (slot eslots)
398           (ecase (condition-slot-allocation slot)
399             (:class
400              (unless (condition-slot-cell slot)
401                (setf (condition-slot-cell slot)
402                      (list (if (condition-slot-initform-p slot)
403                                (let ((initform (condition-slot-initform slot)))
404                                  (if (functionp initform)
405                                      (funcall initform)
406                                      initform))
407                                *empty-condition-slot*))))
408              (push slot (condition-classoid-class-slots class)))
409             ((:instance nil)
410              (setf (condition-slot-allocation slot) :instance)
411              (when (or (functionp (condition-slot-initform slot))
412                        (dolist (initarg (condition-slot-initargs slot) nil)
413                          (when (functionp (getf e-def-initargs initarg))
414                            (return t))))
415                (push slot (condition-classoid-hairy-slots class))))))))
416     name))
417
418 (defmacro define-condition (name (&rest parent-types) (&rest slot-specs)
419                                  &body options)
420   #!+sb-doc
421   "DEFINE-CONDITION Name (Parent-Type*) (Slot-Spec*) Option*
422    Define NAME as a condition type. This new type inherits slots and its
423    report function from the specified PARENT-TYPEs. A slot spec is a list of:
424      (slot-name :reader <rname> :initarg <iname> {Option Value}*
425
426    The DEFINE-CLASS slot options :ALLOCATION, :INITFORM, [slot] :DOCUMENTATION
427    and :TYPE and the overall options :DEFAULT-INITARGS and
428    [type] :DOCUMENTATION are also allowed.
429
430    The :REPORT option is peculiar to DEFINE-CONDITION. Its argument is either
431    a string or a two-argument lambda or function name. If a function, the
432    function is called with the condition and stream to report the condition.
433    If a string, the string is printed.
434
435    Condition types are classes, but (as allowed by ANSI and not as described in
436    CLtL2) are neither STANDARD-OBJECTs nor STRUCTURE-OBJECTs. WITH-SLOTS and
437    SLOT-VALUE may not be used on condition objects."
438   (let* ((parent-types (or parent-types '(condition)))
439          (layout (find-condition-layout name parent-types))
440          (documentation nil)
441          (report nil)
442          (default-initargs ()))
443     (collect ((slots)
444               (all-readers nil append)
445               (all-writers nil append))
446       (dolist (spec slot-specs)
447         (when (keywordp spec)
448           (warn "Keyword slot name indicates probable syntax error:~%  ~S"
449                 spec))
450         (let* ((spec (if (consp spec) spec (list spec)))
451                (slot-name (first spec))
452                (allocation :instance)
453                (initform-p nil)
454                documentation
455                initform)
456           (collect ((initargs)
457                     (readers)
458                     (writers))
459             (do ((options (rest spec) (cddr options)))
460                 ((null options))
461               (unless (and (consp options) (consp (cdr options)))
462                 (error "malformed condition slot spec:~%  ~S." spec))
463               (let ((arg (second options)))
464                 (case (first options)
465                   (:reader (readers arg))
466                   (:writer (writers arg))
467                   (:accessor
468                    (readers arg)
469                    (writers `(setf ,arg)))
470                   (:initform
471                    (when initform-p
472                      (error "more than one :INITFORM in ~S" spec))
473                    (setq initform-p t)
474                    (setq initform arg))
475                   (:initarg (initargs arg))
476                   (:allocation
477                    (setq allocation arg))
478                   (:documentation
479                    (when documentation
480                      (error "more than one :DOCUMENTATION in ~S" spec))
481                    (unless (stringp arg)
482                      (error "slot :DOCUMENTATION argument is not a string: ~S"
483                             arg))
484                    (setq documentation arg))
485                   (:type)
486                   (t
487                    (error "unknown slot option:~%  ~S" (first options))))))
488
489             (all-readers (readers))
490             (all-writers (writers))
491             (slots `(make-condition-slot
492                      :name ',slot-name
493                      :initargs ',(initargs)
494                      :readers ',(readers)
495                      :writers ',(writers)
496                      :initform-p ',initform-p
497                      :documentation ',documentation
498                      :initform
499                      ,(if (constantp initform)
500                           `',(eval initform)
501                           `#'(lambda () ,initform)))))))
502
503       (dolist (option options)
504         (unless (consp option)
505           (error "bad option:~%  ~S" option))
506         (case (first option)
507           (:documentation (setq documentation (second option)))
508           (:report
509            (let ((arg (second option)))
510              (setq report
511                    (if (stringp arg)
512                        `#'(lambda (condition stream)
513                           (declare (ignore condition))
514                           (write-string ,arg stream))
515                        `#'(lambda (condition stream)
516                           (funcall #',arg condition stream))))))
517           (:default-initargs
518            (do ((initargs (rest option) (cddr initargs)))
519                ((endp initargs))
520              (let ((val (second initargs)))
521                (setq default-initargs
522                      (list* `',(first initargs)
523                             (if (constantp val)
524                                 `',(eval val)
525                                 `#'(lambda () ,val))
526                             default-initargs)))))
527           (t
528            (error "unknown option: ~S" (first option)))))
529
530       `(progn
531          (eval-when (:compile-toplevel)
532            (%compiler-define-condition ',name ',parent-types ',layout
533                                        ',(all-readers) ',(all-writers)))
534          (eval-when (:load-toplevel :execute)
535            (%define-condition ',name
536                               ',parent-types
537                               ',layout
538                               (list ,@(slots))
539                               ,documentation
540                               ,report
541                               (list ,@default-initargs)
542                               ',(all-readers)
543                               ',(all-writers)))))))
544 \f
545 ;;;; DESCRIBE on CONDITIONs
546
547 ;;; a function to be used as the guts of DESCRIBE-OBJECT (CONDITION T)
548 ;;; eventually (once we get CLOS up and running so that we can define
549 ;;; methods)
550 (defun describe-condition (condition stream)
551   (format stream
552           "~&~@<~S ~_is a ~S. ~_Its slot values are ~_~S.~:>~%"
553           condition
554           (type-of condition)
555           (concatenate 'list
556                        (condition-actual-initargs condition)
557                        (condition-assigned-slots condition))))
558 \f
559 ;;;; various CONDITIONs specified by ANSI
560
561 (define-condition serious-condition (condition) ())
562
563 (define-condition error (serious-condition) ())
564
565 (define-condition warning (condition) ())
566 (define-condition style-warning (warning) ())
567
568 (defun simple-condition-printer (condition stream)
569   (apply #'format
570          stream
571          (simple-condition-format-control condition)
572          (simple-condition-format-arguments condition)))
573
574 (define-condition simple-condition ()
575   ((format-control :reader simple-condition-format-control
576                    :initarg :format-control
577                    :type format-control)
578    (format-arguments :reader simple-condition-format-arguments
579                      :initarg :format-arguments
580                      :initform '()
581                      :type list))
582   (:report simple-condition-printer))
583
584 (define-condition simple-warning (simple-condition warning) ())
585
586 (define-condition simple-error (simple-condition error) ())
587
588 ;;; not specified by ANSI, but too useful not to have around.
589 (define-condition simple-style-warning (simple-condition style-warning) ())
590
591 (define-condition storage-condition (serious-condition) ())
592
593 (define-condition type-error (error)
594   ((datum :reader type-error-datum :initarg :datum)
595    (expected-type :reader type-error-expected-type :initarg :expected-type))
596   (:report
597    (lambda (condition stream)
598      (format stream
599              "~@<The value ~2I~:_~S ~I~_is not of type ~2I~_~S.~:>"
600              (type-error-datum condition)
601              (type-error-expected-type condition)))))
602
603 (define-condition simple-type-error (simple-condition type-error) ())
604
605 (define-condition program-error (error) ())
606 (define-condition parse-error   (error) ())
607 (define-condition control-error (error) ())
608 (define-condition stream-error  (error)
609   ((stream :reader stream-error-stream :initarg :stream)))
610
611 (define-condition end-of-file (stream-error) ()
612   (:report
613    (lambda (condition stream)
614      (format stream
615              "end of file on ~S"
616              (stream-error-stream condition)))))
617
618 (define-condition file-error (error)
619   ((pathname :reader file-error-pathname :initarg :pathname))
620   (:report
621    (lambda (condition stream)
622      (format stream "error on file ~S" (file-error-pathname condition)))))
623
624 (define-condition package-error (error)
625   ((package :reader package-error-package :initarg :package)))
626
627 (define-condition cell-error (error)
628   ((name :reader cell-error-name :initarg :name)))
629
630 (define-condition unbound-variable (cell-error) ()
631   (:report
632    (lambda (condition stream)
633      (format stream
634              "The variable ~S is unbound."
635              (cell-error-name condition)))))
636
637 (define-condition undefined-function (cell-error) ()
638   (:report
639    (lambda (condition stream)
640      (format stream
641              "The function ~S is undefined."
642              (cell-error-name condition)))))
643
644 (define-condition special-form-function (undefined-function) ()
645   (:report
646    (lambda (condition stream)
647      (format stream
648              "Cannot FUNCALL the SYMBOL-FUNCTION of special operator ~S."
649              (cell-error-name condition)))))
650
651 (define-condition arithmetic-error (error)
652   ((operation :reader arithmetic-error-operation
653               :initarg :operation
654               :initform nil)
655    (operands :reader arithmetic-error-operands
656              :initarg :operands))
657   (:report (lambda (condition stream)
658              (format stream
659                      "arithmetic error ~S signalled"
660                      (type-of condition))
661              (when (arithmetic-error-operation condition)
662                (format stream
663                        "~%Operation was ~S, operands ~S."
664                        (arithmetic-error-operation condition)
665                        (arithmetic-error-operands condition))))))
666
667 (define-condition division-by-zero         (arithmetic-error) ())
668 (define-condition floating-point-overflow  (arithmetic-error) ())
669 (define-condition floating-point-underflow (arithmetic-error) ())
670 (define-condition floating-point-inexact   (arithmetic-error) ())
671 (define-condition floating-point-invalid-operation (arithmetic-error) ())
672
673 (define-condition print-not-readable (error)
674   ((object :reader print-not-readable-object :initarg :object))
675   (:report
676    (lambda (condition stream)
677      (let ((obj (print-not-readable-object condition))
678            (*print-array* nil))
679        (format stream "~S cannot be printed readably." obj)))))
680
681 (define-condition reader-error (parse-error stream-error)
682   ((format-control
683     :reader reader-error-format-control
684     :initarg :format-control)
685    (format-arguments
686     :reader reader-error-format-arguments
687     :initarg :format-arguments
688     :initform '()))
689   (:report
690    (lambda (condition stream)
691      (let* ((error-stream (stream-error-stream condition))
692             (pos (file-position error-stream)))
693        (let (lineno colno)
694          (when (and pos
695                     (< pos sb!xc:array-dimension-limit)
696                     ;; KLUDGE: lseek() (which is what FILE-POSITION
697                     ;; reduces to on file-streams) is undefined on
698                     ;; "some devices", which in practice means that it
699                     ;; can claim to succeed on /dev/stdin on Darwin
700                     ;; and Solaris.  This is obviously bad news,
701                     ;; because the READ-SEQUENCE below will then
702                     ;; block, not complete, and the report will never
703                     ;; be printed.  As a workaround, we exclude
704                     ;; interactive streams from this attempt to report
705                     ;; positions.  -- CSR, 2003-08-21
706                     (not (interactive-stream-p error-stream))
707                     (file-position error-stream :start))
708            (let ((string
709                   (make-string pos
710                                :element-type (stream-element-type error-stream))))
711              (when (= pos (read-sequence string error-stream))
712                (setq lineno (1+ (count #\Newline string))
713                      colno (- pos
714                               (or (position #\Newline string :from-end t) -1)
715                               1))))
716            (file-position error-stream pos))
717          (format stream
718                  "READER-ERROR ~@[at ~W ~]~
719                   ~@[(line ~W~]~@[, column ~W) ~]~
720                   on ~S:~%~?"
721                  pos lineno colno error-stream
722                  (reader-error-format-control condition)
723                  (reader-error-format-arguments condition)))))))
724 \f
725 ;;;; special SBCL extension conditions
726
727 ;;; an error apparently caused by a bug in SBCL itself
728 ;;;
729 ;;; Note that we don't make any serious effort to use this condition
730 ;;; for *all* errors in SBCL itself. E.g. type errors and array
731 ;;; indexing errors can occur in functions called from SBCL code, and
732 ;;; will just end up as ordinary TYPE-ERROR or invalid index error,
733 ;;; because the signalling code has no good way to know that the
734 ;;; underlying problem is a bug in SBCL. But in the fairly common case
735 ;;; that the signalling code does know that it's found a bug in SBCL,
736 ;;; this condition is appropriate, reusing boilerplate and helping
737 ;;; users to recognize it as an SBCL bug.
738 (define-condition bug (simple-error)
739   ()
740   (:report
741    (lambda (condition stream)
742      (format stream
743              "~@<  ~? ~:@_~?~:>"
744              (simple-condition-format-control condition)
745              (simple-condition-format-arguments condition)
746              "~@<This is probably a bug in SBCL itself. (Alternatively, ~
747               SBCL might have been corrupted by bad user code, e.g. by an ~
748               undefined Lisp operation like ~S, or by stray pointers from ~
749               alien code or from unsafe Lisp code; or there might be a bug ~
750               in the OS or hardware that SBCL is running on.) If it seems to ~
751               be a bug in SBCL itself, the maintainers would like to know ~
752               about it. Bug reports are welcome on the SBCL ~
753               mailing lists, which you can find at ~
754               <http://sbcl.sourceforge.net/>.~:@>"
755              '((fmakunbound 'compile))))))
756
757 ;;; a condition for use in stubs for operations which aren't supported
758 ;;; on some platforms
759 ;;;
760 ;;; E.g. in sbcl-0.7.0.5, it might be appropriate to do something like
761 ;;;   #-(or freebsd linux)
762 ;;;   (defun load-foreign (&rest rest)
763 ;;;     (error 'unsupported-operator :name 'load-foreign))
764 ;;;   #+(or freebsd linux)
765 ;;;   (defun load-foreign ... actual definition ...)
766 ;;; By signalling a standard condition in this case, we make it
767 ;;; possible for test code to distinguish between (1) intentionally
768 ;;; unimplemented and (2) unintentionally just screwed up somehow.
769 ;;; (Before this condition was defined, test code tried to deal with 
770 ;;; this by checking for FBOUNDP, but that didn't work reliably. In
771 ;;; sbcl-0.7.0, a a package screwup left the definition of
772 ;;; LOAD-FOREIGN in the wrong package, so it was unFBOUNDP even on
773 ;;; architectures where it was supposed to be supported, and the
774 ;;; regression tests cheerfully passed because they assumed that
775 ;;; unFBOUNDPness meant they were running on an system which didn't
776 ;;; support the extension.)
777 (define-condition unsupported-operator (simple-error) ())
778
779 \f
780 ;;; (:ansi-cl :function remove)
781 ;;; (:ansi-cl :section (a b c))
782 ;;; (:ansi-cl :glossary "similar")
783 ;;;
784 ;;; (:sbcl :node "...")
785 ;;; (:sbcl :variable *ed-functions*)
786 ;;;
787 ;;; FIXME: this is not the right place for this.
788 (defun print-reference (reference stream)
789   (ecase (car reference)
790     (:amop
791      (format stream "AMOP")
792      (format stream ", ")
793      (destructuring-bind (type data) (cdr reference)
794        (ecase type
795          (:generic-function (format stream "Generic Function ~S" data))
796          (:section (format stream "Section ~{~D~^.~}" data)))))
797     (:ansi-cl
798      (format stream "The ANSI Standard")
799      (format stream ", ")
800      (destructuring-bind (type data) (cdr reference)
801        (ecase type
802          (:function (format stream "Function ~S" data))
803          (:special-operator (format stream "Special Operator ~S" data))
804          (:macro (format stream "Macro ~S" data))
805          (:section (format stream "Section ~{~D~^.~}" data))
806          (:glossary (format stream "Glossary entry for ~S" data))
807          (:issue (format stream "writeup for Issue ~A" data)))))
808     (:sbcl
809      (format stream "The SBCL Manual")
810      (format stream ", ")
811      (destructuring-bind (type data) (cdr reference)
812        (ecase type
813          (:node (format stream "Node ~S" data))
814          (:variable (format stream "Variable ~S" data))
815          (:function (format stream "Function ~S" data)))))
816     ;; FIXME: other documents (e.g. CLIM, Franz documentation :-)
817     ))
818 (define-condition reference-condition ()
819   ((references :initarg :references :reader reference-condition-references)))
820 (defvar *print-condition-references* t)
821 (def!method print-object :around ((o reference-condition) s)
822   (call-next-method)
823   (unless (or *print-escape* *print-readably*)
824     (when (and *print-condition-references*
825                (reference-condition-references o))
826       (format s "~&See also:~%")
827       (pprint-logical-block (s nil :per-line-prefix "  ")
828         (do* ((rs (reference-condition-references o) (cdr rs))
829               (r (car rs) (car rs)))
830              ((null rs))
831           (print-reference r s)
832           (unless (null (cdr rs))
833             (terpri s)))))))
834
835 (define-condition duplicate-definition (reference-condition warning)
836   ((name :initarg :name :reader duplicate-definition-name))
837   (:report (lambda (c s)
838              (format s "~@<Duplicate definition for ~S found in ~
839                         one file.~@:>"
840                      (duplicate-definition-name c))))
841   (:default-initargs :references (list '(:ansi-cl :section (3 2 2 3)))))
842
843 (define-condition package-at-variance (reference-condition simple-warning) 
844   ()
845   (:default-initargs :references (list '(:ansi-cl :macro defpackage))))
846
847 (define-condition defconstant-uneql (reference-condition error)
848   ((name :initarg :name :reader defconstant-uneql-name)
849    (old-value :initarg :old-value :reader defconstant-uneql-old-value)
850    (new-value :initarg :new-value :reader defconstant-uneql-new-value))
851   (:report
852    (lambda (condition stream)
853      (format stream
854              "~@<The constant ~S is being redefined (from ~S to ~S)~@:>"
855              (defconstant-uneql-name condition)
856              (defconstant-uneql-old-value condition)
857              (defconstant-uneql-new-value condition))))
858   (:default-initargs :references (list '(:ansi-cl :macro defconstant)
859                                        '(:sbcl :node "Idiosyncrasies"))))
860
861 (define-condition array-initial-element-mismatch 
862     (reference-condition simple-warning)
863   ()
864   (:default-initargs 
865       :references (list 
866                    '(:ansi-cl :function make-array) 
867                    '(:ansi-cl :function sb!xc:upgraded-array-element-type))))
868
869 (define-condition displaced-to-array-too-small-error
870     (reference-condition simple-error)
871   ()
872   (:default-initargs
873       :references (list '(:ansi-cl :function adjust-array))))
874
875 (define-condition type-warning (reference-condition simple-warning)
876   ()
877   (:default-initargs :references (list '(:sbcl :node "Handling of Types"))))
878
879 (define-condition local-argument-mismatch (reference-condition simple-warning)
880   ()
881   (:default-initargs :references (list '(:ansi-cl :section (3 2 2 3)))))
882
883 (define-condition format-args-mismatch (reference-condition)
884   ()
885   (:default-initargs :references (list '(:ansi-cl :section (22 3 10 2)))))
886
887 (define-condition format-too-few-args-warning 
888     (format-args-mismatch simple-warning)
889   ())
890 (define-condition format-too-many-args-warning
891     (format-args-mismatch simple-style-warning)
892   ())
893
894 (define-condition extension-failure (reference-condition simple-error)
895   ())
896
897 #!+sb-package-locks
898 (progn
899
900 (define-condition package-lock-violation (reference-condition package-error)
901   ((format-control :initform nil :initarg :format-control 
902                    :reader package-error-format-control)
903    (format-arguments :initform nil :initarg :format-arguments
904                      :reader package-error-format-arguments))
905   (:report 
906    (lambda (condition stream)
907      (let ((control (package-error-format-control condition)))
908        (if control
909            (apply #'format stream
910                   (format nil "~~@<Lock on package ~A violated when ~A.~~:@>"
911                           (package-name (package-error-package condition))
912                           control)
913                   (package-error-format-arguments condition))
914            (format stream "~@<Lock on package ~A violated.~:@>"
915                    (package-name (package-error-package condition)))))))
916   ;; no :default-initargs -- reference-stuff provided by the
917   ;; signalling form in target-package.lisp
918   #!+sb-doc
919   (:documentation
920    "Subtype of CL:PACKAGE-ERROR. A subtype of this error is signalled
921 when a package-lock is violated."))
922
923 (define-condition package-locked-error (package-lock-violation) ()
924   #!+sb-doc
925   (:documentation
926    "Subtype of SB-EXT:PACKAGE-LOCK-VIOLATION. An error of this type is
927 signalled when an operation on a package violates a package lock."))
928
929 (define-condition symbol-package-locked-error (package-lock-violation)
930   ((symbol :initarg :symbol :reader package-locked-error-symbol))
931   #!+sb-doc
932   (:documentation
933    "Subtype of SB-EXT:PACKAGE-LOCK-VIOLATION. An error of this type is
934 signalled when an operation on a symbol violates a package lock. The
935 symbol that caused the violation is accessed by the function
936 SB-EXT:PACKAGE-LOCKED-ERROR-SYMBOL."))
937
938 ) ; progn
939 \f
940 ;;;; various other (not specified by ANSI) CONDITIONs
941 ;;;;
942 ;;;; These might logically belong in other files; they're here, after
943 ;;;; setup of CONDITION machinery, only because that makes it easier to
944 ;;;; get cold init to work.
945
946 ;;; OAOOM warning: see cross-condition.lisp
947 (define-condition encapsulated-condition (condition)
948   ((condition :initarg :condition :reader encapsulated-condition)))
949
950 (define-condition values-type-error (type-error)
951   ()
952   (:report
953    (lambda (condition stream)
954      (format stream
955              "~@<The values set ~2I~:_[~{~S~^ ~}] ~I~_is not of type ~2I~_~S.~:>"
956              (type-error-datum condition)
957              (type-error-expected-type condition)))))
958
959 ;;; KLUDGE: a condition for floating point errors when we can't or
960 ;;; won't figure out what type they are. (In FreeBSD and OpenBSD we
961 ;;; don't know how, at least as of sbcl-0.6.7; in Linux we probably
962 ;;; know how but the old code was broken by the conversion to POSIX
963 ;;; signal handling and hasn't been fixed as of sbcl-0.6.7.)
964 ;;;
965 ;;; FIXME: Perhaps this should also be a base class for all
966 ;;; floating point exceptions?
967 (define-condition floating-point-exception (arithmetic-error)
968   ((flags :initarg :traps
969           :initform nil
970           :reader floating-point-exception-traps))
971   (:report (lambda (condition stream)
972              (format stream
973                      "An arithmetic error ~S was signalled.~%"
974                      (type-of condition))
975              (let ((traps (floating-point-exception-traps condition)))
976                (if traps
977                    (format stream
978                            "Trapping conditions are: ~%~{ ~S~^~}~%"
979                            traps)
980                    (write-line
981                     "No traps are enabled? How can this be?"
982                     stream))))))
983
984 (define-condition index-too-large-error (type-error)
985   ()
986   (:report
987    (lambda (condition stream)
988      (format stream
989              "The index ~S is too large."
990              (type-error-datum condition)))))
991
992 (define-condition bounding-indices-bad-error (reference-condition type-error)
993   ((object :reader bounding-indices-bad-object :initarg :object))
994   (:report
995    (lambda (condition stream)
996      (let* ((datum (type-error-datum condition))
997             (start (car datum))
998             (end (cdr datum))
999             (object (bounding-indices-bad-object condition)))
1000        (etypecase object
1001          (sequence
1002           (format stream
1003                   "The bounding indices ~S and ~S are bad ~
1004                    for a sequence of length ~S."
1005                   start end (length object)))
1006          (array
1007           ;; from WITH-ARRAY-DATA
1008           (format stream
1009                   "The START and END parameters ~S and ~S are ~
1010                    bad for an array of total size ~S."
1011                   start end (array-total-size object)))))))
1012   (:default-initargs 
1013       :references 
1014       (list '(:ansi-cl :glossary "bounding index designator")
1015             '(:ansi-cl :issue "SUBSEQ-OUT-OF-BOUNDS:IS-AN-ERROR"))))
1016
1017 (define-condition nil-array-accessed-error (reference-condition type-error)
1018   ()
1019   (:report (lambda (condition stream)
1020              (declare (ignore condition))
1021              (format stream
1022                      "An attempt to access an array of element-type ~
1023                       NIL was made.  Congratulations!")))
1024   (:default-initargs
1025       :references (list '(:ansi-cl :function sb!xc:upgraded-array-element-type)
1026                         '(:ansi-cl :section (15 1 2 1))
1027                         '(:ansi-cl :section (15 1 2 2)))))
1028
1029 (define-condition io-timeout (stream-error)
1030   ((direction :reader io-timeout-direction :initarg :direction))
1031   (:report
1032    (lambda (condition stream)
1033      (declare (type stream stream))
1034      (format stream
1035              "I/O timeout ~(~A~)ing ~S"
1036              (io-timeout-direction condition)
1037              (stream-error-stream condition)))))
1038
1039 (define-condition namestring-parse-error (parse-error)
1040   ((complaint :reader namestring-parse-error-complaint :initarg :complaint)
1041    (args :reader namestring-parse-error-args :initarg :args :initform nil)
1042    (namestring :reader namestring-parse-error-namestring :initarg :namestring)
1043    (offset :reader namestring-parse-error-offset :initarg :offset))
1044   (:report
1045    (lambda (condition stream)
1046      (format stream
1047              "parse error in namestring: ~?~%  ~A~%  ~V@T^"
1048              (namestring-parse-error-complaint condition)
1049              (namestring-parse-error-args condition)
1050              (namestring-parse-error-namestring condition)
1051              (namestring-parse-error-offset condition)))))
1052
1053 (define-condition simple-package-error (simple-condition package-error) ())
1054
1055 (define-condition reader-package-error (reader-error) ())
1056
1057 (define-condition reader-eof-error (end-of-file)
1058   ((context :reader reader-eof-error-context :initarg :context))
1059   (:report
1060    (lambda (condition stream)
1061      (format stream
1062              "unexpected end of file on ~S ~A"
1063              (stream-error-stream condition)
1064              (reader-eof-error-context condition)))))
1065
1066 (define-condition reader-impossible-number-error (reader-error)
1067   ((error :reader reader-impossible-number-error-error :initarg :error))
1068   (:report
1069    (lambda (condition stream)
1070      (let ((error-stream (stream-error-stream condition)))
1071        (format stream "READER-ERROR ~@[at ~W ~]on ~S:~%~?~%Original error: ~A"
1072                (file-position error-stream) error-stream
1073                (reader-error-format-control condition)
1074                (reader-error-format-arguments condition)
1075                (reader-impossible-number-error-error condition))))))
1076
1077 (define-condition timeout (serious-condition) ())
1078
1079 ;;; Single stepping conditions
1080
1081 (define-condition step-condition ()
1082   ((form :initarg :form :reader step-condition-form))
1083   #!+sb-doc
1084   (:documentation "Common base class of single-stepping conditions.
1085 STEP-CONDITION-FORM holds a string representation of the form being
1086 stepped."))
1087
1088 #!+sb-doc
1089 (setf (fdocumentation 'step-condition-form 'function)
1090       "Form associated with the STEP-CONDITION.")
1091
1092 (define-condition step-form-condition (step-condition)
1093   ((source-path :initarg :source-path :reader step-condition-source-path)
1094    (pathname :initarg :pathname :reader step-condition-pathname))
1095   #!+sb-doc
1096   (:documentation "Condition signalled by code compiled with
1097 single-stepping information when about to execute a form.
1098 STEP-CONDITION-FORM holds the form, STEP-CONDITION-PATHNAME holds the
1099 pathname of the original file or NIL, and STEP-CONDITION-SOURCE-PATH
1100 holds the source-path to the original form within that file or NIL.
1101 Associated with this condition are always the restarts STEP-INTO,
1102 STEP-NEXT, and STEP-CONTINUE."))
1103
1104 #!+sb-doc
1105 (setf (fdocumentation 'step-condition-source-path 'function)
1106       "Source-path of the original form associated with the
1107 STEP-FORM-CONDITION or NIL."
1108       (fdocumentation 'step-condition-pathname 'function)
1109       "Pathname of the original source-file associated with the
1110 STEP-FORM-CONDITION or NIL.")
1111
1112 (define-condition step-result-condition (step-condition)
1113   ((result :initarg :result :reader step-condition-result)))
1114
1115 #!+sb-doc
1116 (setf (fdocumentation 'step-condition-result 'function)
1117       "Return values associated with STEP-VALUES-CONDITION as a list,
1118 or the variable value associated with STEP-VARIABLE-CONDITION.")
1119
1120 (define-condition step-values-condition (step-result-condition)
1121   ()
1122   #!+sb-doc
1123   (:documentation "Condition signalled by code compiled with
1124 single-stepping information after executing a form.
1125 STEP-CONDITION-FORM holds the form, and STEP-CONDITION-RESULT holds
1126 the values returned by the form as a list. No associated restarts."))
1127
1128 (define-condition step-variable-condition (step-result-condition)
1129   ()
1130   #!+sb-doc
1131   (:documentation "Condition signalled by code compiled with
1132 single-stepping information when referencing a variable.
1133 STEP-CONDITION-FORM hold the symbol, and STEP-CONDITION-RESULT holds
1134 the value of the variable. No associated restarts."))
1135
1136 \f
1137 ;;;; restart definitions
1138
1139 (define-condition abort-failure (control-error) ()
1140   (:report
1141    "An ABORT restart was found that failed to transfer control dynamically."))
1142
1143 (defun abort (&optional condition)
1144   #!+sb-doc
1145   "Transfer control to a restart named ABORT, signalling a CONTROL-ERROR if
1146    none exists."
1147   (invoke-restart (find-restart-or-control-error 'abort condition))
1148   ;; ABORT signals an error in case there was a restart named ABORT
1149   ;; that did not transfer control dynamically. This could happen with
1150   ;; RESTART-BIND.
1151   (error 'abort-failure))
1152
1153 (defun muffle-warning (&optional condition)
1154   #!+sb-doc
1155   "Transfer control to a restart named MUFFLE-WARNING, signalling a
1156    CONTROL-ERROR if none exists."
1157   (invoke-restart (find-restart-or-control-error 'muffle-warning condition)))
1158
1159 (macrolet ((define-nil-returning-restart (name args doc)
1160              #!-sb-doc (declare (ignore doc))
1161              `(defun ,name (,@args &optional condition)
1162                 #!+sb-doc ,doc
1163                 ;; FIXME: Perhaps this shared logic should be pulled out into
1164                 ;; FLET MAYBE-INVOKE-RESTART? See whether it shrinks code..
1165                 (let ((restart (find-restart ',name condition)))
1166                   (when restart
1167                     (invoke-restart restart ,@args))))))
1168   (define-nil-returning-restart continue ()
1169     "Transfer control to a restart named CONTINUE, or return NIL if none exists.")
1170   (define-nil-returning-restart store-value (value)
1171     "Transfer control and VALUE to a restart named STORE-VALUE, or return NIL if
1172    none exists.")
1173   (define-nil-returning-restart use-value (value)
1174     "Transfer control and VALUE to a restart named USE-VALUE, or return NIL if
1175    none exists."))
1176
1177 ;;; single-stepping restarts
1178
1179 (macrolet ((def (name doc)
1180                #!-sb-doc (declare (ignore doc))
1181                `(defun ,name (condition)
1182                  #!+sb-doc ,doc
1183                  (invoke-restart (find-restart-or-control-error ',name condition)))))
1184   (def step-continue
1185       "Transfers control to the STEP-CONTINUE restart associated with
1186 the condition, continuing execution without stepping. Signals a
1187 CONTROL-ERROR if the restart does not exist.")
1188   (def step-next
1189       "Transfers control to the STEP-NEXT restart associated with the
1190 condition, executing the current form without stepping and continuing
1191 stepping with the next form. Signals CONTROL-ERROR is the restart does
1192 not exists.")
1193   (def step-into
1194       "Transfers control to the STEP-INTO restart associated with the
1195 condition, stepping into the current form. Signals a CONTROL-ERROR is
1196 the restart does not exist."))
1197
1198 (/show0 "condition.lisp end of file")
1199