534554410b6d61cb5795425f6120c2210f9bed20
[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 (if (symbolp thing)
237                     (find-classoid thing)
238                     thing))
239          (class (typecase thing
240                   (condition-classoid thing)
241                   (classoid
242                    (error 'simple-type-error
243                           :datum thing
244                           :expected-type 'condition-class
245                           :format-control "~S is not a condition class."
246                           :format-arguments (list thing)))
247                   (t
248                    (error 'simple-type-error
249                           :datum thing
250                           :expected-type 'condition-class
251                           :format-control "bad thing for class argument:~%  ~S"
252                           :format-arguments (list thing)))))
253          (res (make-condition-object args)))
254     (setf (%instance-layout res) (classoid-layout class))
255     ;; Set any class slots with initargs present in this call.
256     (dolist (cslot (condition-classoid-class-slots class))
257       (dolist (initarg (condition-slot-initargs cslot))
258         (let ((val (getf args initarg *empty-condition-slot*)))
259           (unless (eq val *empty-condition-slot*)
260             (setf (car (condition-slot-cell cslot)) val)))))
261     ;; Default any slots with non-constant defaults now.
262     (dolist (hslot (condition-classoid-hairy-slots class))
263       (when (dolist (initarg (condition-slot-initargs hslot) t)
264               (unless (eq (getf args initarg *empty-condition-slot*)
265                           *empty-condition-slot*)
266                 (return nil)))
267         (setf (getf (condition-assigned-slots res) (condition-slot-name hslot))
268               (find-slot-default class hslot))))
269
270     res))
271 \f
272 ;;;; DEFINE-CONDITION
273
274 (eval-when (:compile-toplevel :load-toplevel :execute)
275 (defun %compiler-define-condition (name direct-supers layout
276                                    all-readers all-writers)
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   (%compiler-define-condition name parent-types layout all-readers all-writers)
373   (let ((class (find-classoid name)))
374     (setf (condition-classoid-slots class) slots)
375     (setf (condition-classoid-report class) report)
376     (setf (condition-classoid-default-initargs class) default-initargs)
377     (setf (fdocumentation name 'type) documentation)
378
379     (dolist (slot slots)
380
381       ;; Set up reader and writer functions.
382       (let ((slot-name (condition-slot-name slot)))
383         (dolist (reader (condition-slot-readers slot))
384           (install-condition-slot-reader reader name slot-name))
385         (dolist (writer (condition-slot-writers slot))
386           (install-condition-slot-writer writer name slot-name))))
387
388     ;; Compute effective slots and set up the class and hairy slots
389     ;; (subsets of the effective slots.)
390     (let ((eslots (compute-effective-slots class))
391           (e-def-initargs
392            (reduce #'append
393                    (mapcar #'condition-classoid-default-initargs
394                            (condition-classoid-cpl class)))))
395       (dolist (slot eslots)
396         (ecase (condition-slot-allocation slot)
397           (:class
398            (unless (condition-slot-cell slot)
399              (setf (condition-slot-cell slot)
400                    (list (if (condition-slot-initform-p slot)
401                              (let ((initform (condition-slot-initform slot)))
402                                (if (functionp initform)
403                                    (funcall initform)
404                                    initform))
405                              *empty-condition-slot*))))
406            (push slot (condition-classoid-class-slots class)))
407           ((:instance nil)
408            (setf (condition-slot-allocation slot) :instance)
409            (when (or (functionp (condition-slot-initform slot))
410                      (dolist (initarg (condition-slot-initargs slot) nil)
411                        (when (functionp (getf e-def-initargs initarg))
412                          (return t))))
413              (push slot (condition-classoid-hairy-slots class))))))))
414   name)
415
416 (defmacro define-condition (name (&rest parent-types) (&rest slot-specs)
417                                  &body options)
418   #!+sb-doc
419   "DEFINE-CONDITION Name (Parent-Type*) (Slot-Spec*) Option*
420    Define NAME as a condition type. This new type inherits slots and its
421    report function from the specified PARENT-TYPEs. A slot spec is a list of:
422      (slot-name :reader <rname> :initarg <iname> {Option Value}*
423
424    The DEFINE-CLASS slot options :ALLOCATION, :INITFORM, [slot] :DOCUMENTATION
425    and :TYPE and the overall options :DEFAULT-INITARGS and
426    [type] :DOCUMENTATION are also allowed.
427
428    The :REPORT option is peculiar to DEFINE-CONDITION. Its argument is either
429    a string or a two-argument lambda or function name. If a function, the
430    function is called with the condition and stream to report the condition.
431    If a string, the string is printed.
432
433    Condition types are classes, but (as allowed by ANSI and not as described in
434    CLtL2) are neither STANDARD-OBJECTs nor STRUCTURE-OBJECTs. WITH-SLOTS and
435    SLOT-VALUE may not be used on condition objects."
436   (let* ((parent-types (or parent-types '(condition)))
437          (layout (find-condition-layout name parent-types))
438          (documentation nil)
439          (report nil)
440          (default-initargs ()))
441     (collect ((slots)
442               (all-readers nil append)
443               (all-writers nil append))
444       (dolist (spec slot-specs)
445         (when (keywordp spec)
446           (warn "Keyword slot name indicates probable syntax error:~%  ~S"
447                 spec))
448         (let* ((spec (if (consp spec) spec (list spec)))
449                (slot-name (first spec))
450                (allocation :instance)
451                (initform-p nil)
452                documentation
453                initform)
454           (collect ((initargs)
455                     (readers)
456                     (writers))
457             (do ((options (rest spec) (cddr options)))
458                 ((null options))
459               (unless (and (consp options) (consp (cdr options)))
460                 (error "malformed condition slot spec:~%  ~S." spec))
461               (let ((arg (second options)))
462                 (case (first options)
463                   (:reader (readers arg))
464                   (:writer (writers arg))
465                   (:accessor
466                    (readers arg)
467                    (writers `(setf ,arg)))
468                   (:initform
469                    (when initform-p
470                      (error "more than one :INITFORM in ~S" spec))
471                    (setq initform-p t)
472                    (setq initform arg))
473                   (:initarg (initargs arg))
474                   (:allocation
475                    (setq allocation arg))
476                   (:documentation
477                    (when documentation
478                      (error "more than one :DOCUMENTATION in ~S" spec))
479                    (unless (stringp arg)
480                      (error "slot :DOCUMENTATION argument is not a string: ~S"
481                             arg))
482                    (setq documentation arg))
483                   (:type)
484                   (t
485                    (error "unknown slot option:~%  ~S" (first options))))))
486
487             (all-readers (readers))
488             (all-writers (writers))
489             (slots `(make-condition-slot
490                      :name ',slot-name
491                      :initargs ',(initargs)
492                      :readers ',(readers)
493                      :writers ',(writers)
494                      :initform-p ',initform-p
495                      :documentation ',documentation
496                      :initform
497                      ,(if (constantp initform)
498                           `',(eval initform)
499                           `#'(lambda () ,initform)))))))
500
501       (dolist (option options)
502         (unless (consp option)
503           (error "bad option:~%  ~S" option))
504         (case (first option)
505           (:documentation (setq documentation (second option)))
506           (:report
507            (let ((arg (second option)))
508              (setq report
509                    (if (stringp arg)
510                        `#'(lambda (condition stream)
511                           (declare (ignore condition))
512                           (write-string ,arg stream))
513                        `#'(lambda (condition stream)
514                           (funcall #',arg condition stream))))))
515           (:default-initargs
516            (do ((initargs (rest option) (cddr initargs)))
517                ((endp initargs))
518              (let ((val (second initargs)))
519                (setq default-initargs
520                      (list* `',(first initargs)
521                             (if (constantp val)
522                                 `',(eval val)
523                                 `#'(lambda () ,val))
524                             default-initargs)))))
525           (t
526            (error "unknown option: ~S" (first option)))))
527
528       `(progn
529          (eval-when (:compile-toplevel)
530            (%compiler-define-condition ',name ',parent-types ',layout
531                                        ',(all-readers) ',(all-writers)))
532          (eval-when (:load-toplevel :execute)
533            (%define-condition ',name
534                               ',parent-types
535                               ',layout
536                               (list ,@(slots))
537                               ,documentation
538                               ,report
539                               (list ,@default-initargs)
540                               ',(all-readers)
541                               ',(all-writers)))))))
542 \f
543 ;;;; DESCRIBE on CONDITIONs
544
545 ;;; a function to be used as the guts of DESCRIBE-OBJECT (CONDITION T)
546 ;;; eventually (once we get CLOS up and running so that we can define
547 ;;; methods)
548 (defun describe-condition (condition stream)
549   (format stream
550           "~&~@<~S ~_is a ~S. ~_Its slot values are ~_~S.~:>~%"
551           condition
552           (type-of condition)
553           (concatenate 'list
554                        (condition-actual-initargs condition)
555                        (condition-assigned-slots condition))))
556 \f
557 ;;;; various CONDITIONs specified by ANSI
558
559 (define-condition serious-condition (condition) ())
560
561 (define-condition error (serious-condition) ())
562
563 (define-condition warning (condition) ())
564 (define-condition style-warning (warning) ())
565
566 (defun simple-condition-printer (condition stream)
567   (apply #'format
568          stream
569          (simple-condition-format-control condition)
570          (simple-condition-format-arguments condition)))
571
572 (define-condition simple-condition ()
573   ((format-control :reader simple-condition-format-control
574                    :initarg :format-control
575                    :type format-control)
576    (format-arguments :reader simple-condition-format-arguments
577                      :initarg :format-arguments
578                      :initform '()
579                      :type list))
580   (:report simple-condition-printer))
581
582 (define-condition simple-warning (simple-condition warning) ())
583
584 (define-condition simple-error (simple-condition error) ())
585
586 ;;; not specified by ANSI, but too useful not to have around.
587 (define-condition simple-style-warning (simple-condition style-warning) ())
588
589 (define-condition storage-condition (serious-condition) ())
590
591 (define-condition type-error (error)
592   ((datum :reader type-error-datum :initarg :datum)
593    (expected-type :reader type-error-expected-type :initarg :expected-type))
594   (:report
595    (lambda (condition stream)
596      (format stream
597              "~@<The value ~2I~:_~S ~I~_is not of type ~2I~_~S.~:>"
598              (type-error-datum condition)
599              (type-error-expected-type condition)))))
600
601 (define-condition simple-type-error (simple-condition type-error) ())
602
603 (define-condition program-error (error) ())
604 (define-condition parse-error   (error) ())
605 (define-condition control-error (error) ())
606 (define-condition stream-error  (error)
607   ((stream :reader stream-error-stream :initarg :stream)))
608
609 (define-condition end-of-file (stream-error) ()
610   (:report
611    (lambda (condition stream)
612      (format stream
613              "end of file on ~S"
614              (stream-error-stream condition)))))
615
616 (define-condition file-error (error)
617   ((pathname :reader file-error-pathname :initarg :pathname))
618   (:report
619    (lambda (condition stream)
620      (format stream "error on file ~S" (file-error-pathname condition)))))
621
622 (define-condition package-error (error)
623   ((package :reader package-error-package :initarg :package)))
624
625 (define-condition cell-error (error)
626   ((name :reader cell-error-name :initarg :name)))
627
628 (define-condition unbound-variable (cell-error) ()
629   (:report
630    (lambda (condition stream)
631      (format stream
632              "The variable ~S is unbound."
633              (cell-error-name condition)))))
634
635 (define-condition undefined-function (cell-error) ()
636   (:report
637    (lambda (condition stream)
638      (format stream
639              "The function ~S is undefined."
640              (cell-error-name condition)))))
641
642 (define-condition special-form-function (undefined-function) ()
643   (:report
644    (lambda (condition stream)
645      (format stream
646              "Cannot FUNCALL the SYMBOL-FUNCTION of special operator ~S."
647              (cell-error-name condition)))))
648
649 (define-condition arithmetic-error (error)
650   ((operation :reader arithmetic-error-operation
651               :initarg :operation
652               :initform nil)
653    (operands :reader arithmetic-error-operands
654              :initarg :operands))
655   (:report (lambda (condition stream)
656              (format stream
657                      "arithmetic error ~S signalled"
658                      (type-of condition))
659              (when (arithmetic-error-operation condition)
660                (format stream
661                        "~%Operation was ~S, operands ~S."
662                        (arithmetic-error-operation condition)
663                        (arithmetic-error-operands condition))))))
664
665 (define-condition division-by-zero         (arithmetic-error) ())
666 (define-condition floating-point-overflow  (arithmetic-error) ())
667 (define-condition floating-point-underflow (arithmetic-error) ())
668 (define-condition floating-point-inexact   (arithmetic-error) ())
669 (define-condition floating-point-invalid-operation (arithmetic-error) ())
670
671 (define-condition print-not-readable (error)
672   ((object :reader print-not-readable-object :initarg :object))
673   (:report
674    (lambda (condition stream)
675      (let ((obj (print-not-readable-object condition))
676            (*print-array* nil))
677        (format stream "~S cannot be printed readably." obj)))))
678
679 (define-condition reader-error (parse-error stream-error)
680   ((format-control
681     :reader reader-error-format-control
682     :initarg :format-control)
683    (format-arguments
684     :reader reader-error-format-arguments
685     :initarg :format-arguments
686     :initform '()))
687   (:report
688    (lambda (condition stream)
689      (let* ((error-stream (stream-error-stream condition))
690             (pos (file-position error-stream)))
691        (let (lineno colno)
692          (when (and pos
693                     (< pos sb!xc:array-dimension-limit)
694                     ;; KLUDGE: lseek() (which is what FILE-POSITION
695                     ;; reduces to on file-streams) is undefined on
696                     ;; "some devices", which in practice means that it
697                     ;; can claim to succeed on /dev/stdin on Darwin
698                     ;; and Solaris.  This is obviously bad news,
699                     ;; because the READ-SEQUENCE below will then
700                     ;; block, not complete, and the report will never
701                     ;; be printed.  As a workaround, we exclude
702                     ;; interactive streams from this attempt to report
703                     ;; positions.  -- CSR, 2003-08-21
704                     (not (interactive-stream-p error-stream))
705                     (file-position error-stream :start))
706            (let ((string
707                   (make-string pos
708                                :element-type (stream-element-type error-stream))))
709              (when (= pos (read-sequence string error-stream))
710                (setq lineno (1+ (count #\Newline string))
711                      colno (- pos
712                               (or (position #\Newline string :from-end t) -1)
713                               1))))
714            (file-position error-stream pos))
715          (format stream
716                  "READER-ERROR ~@[at ~W ~]~
717                   ~@[(line ~W~]~@[, column ~W) ~]~
718                   on ~S:~%~?"
719                  pos lineno colno error-stream
720                  (reader-error-format-control condition)
721                  (reader-error-format-arguments condition)))))))
722 \f
723 ;;;; special SBCL extension conditions
724
725 ;;; an error apparently caused by a bug in SBCL itself
726 ;;;
727 ;;; Note that we don't make any serious effort to use this condition
728 ;;; for *all* errors in SBCL itself. E.g. type errors and array
729 ;;; indexing errors can occur in functions called from SBCL code, and
730 ;;; will just end up as ordinary TYPE-ERROR or invalid index error,
731 ;;; because the signalling code has no good way to know that the
732 ;;; underlying problem is a bug in SBCL. But in the fairly common case
733 ;;; that the signalling code does know that it's found a bug in SBCL,
734 ;;; this condition is appropriate, reusing boilerplate and helping
735 ;;; users to recognize it as an SBCL bug.
736 (define-condition bug (simple-error)
737   ()
738   (:report
739    (lambda (condition stream)
740      (format stream
741              "~@<  ~? ~:@_~?~:>"
742              (simple-condition-format-control condition)
743              (simple-condition-format-arguments condition)
744              "~@<This is probably a bug in SBCL itself. (Alternatively, ~
745               SBCL might have been corrupted by bad user code, e.g. by an ~
746               undefined Lisp operation like ~S, or by stray pointers from ~
747               alien code or from unsafe Lisp code; or there might be a bug ~
748               in the OS or hardware that SBCL is running on.) If it seems to ~
749               be a bug in SBCL itself, the maintainers would like to know ~
750               about it. Bug reports are welcome on the SBCL ~
751               mailing lists, which you can find at ~
752               <http://sbcl.sourceforge.net/>.~:@>"
753              '((fmakunbound 'compile))))))
754
755 ;;; a condition for use in stubs for operations which aren't supported
756 ;;; on some platforms
757 ;;;
758 ;;; E.g. in sbcl-0.7.0.5, it might be appropriate to do something like
759 ;;;   #-(or freebsd linux)
760 ;;;   (defun load-foreign (&rest rest)
761 ;;;     (error 'unsupported-operator :name 'load-foreign))
762 ;;;   #+(or freebsd linux)
763 ;;;   (defun load-foreign ... actual definition ...)
764 ;;; By signalling a standard condition in this case, we make it
765 ;;; possible for test code to distinguish between (1) intentionally
766 ;;; unimplemented and (2) unintentionally just screwed up somehow.
767 ;;; (Before this condition was defined, test code tried to deal with 
768 ;;; this by checking for FBOUNDP, but that didn't work reliably. In
769 ;;; sbcl-0.7.0, a a package screwup left the definition of
770 ;;; LOAD-FOREIGN in the wrong package, so it was unFBOUNDP even on
771 ;;; architectures where it was supposed to be supported, and the
772 ;;; regression tests cheerfully passed because they assumed that
773 ;;; unFBOUNDPness meant they were running on an system which didn't
774 ;;; support the extension.)
775 (define-condition unsupported-operator (cell-error) ()
776   (:report
777    (lambda (condition stream)
778      (format stream
779              "unsupported on this platform (OS, CPU, whatever): ~S"
780              (cell-error-name condition)))))
781 \f
782 ;;; (:ansi-cl :function remove)
783 ;;; (:ansi-cl :section (a b c))
784 ;;; (:ansi-cl :glossary "similar")
785 ;;;
786 ;;; (:sbcl :node "...")
787 ;;; (:sbcl :variable *ed-functions*)
788 ;;;
789 ;;; FIXME: this is not the right place for this.
790 (defun print-reference (reference stream)
791   (ecase (car reference)
792     (:ansi-cl
793      (format stream "The ANSI Standard")
794      (format stream ", ")
795      (destructuring-bind (type data) (cdr reference)
796        (ecase type
797          (:function (format stream "Function ~S" data))
798          (:special-operator (format stream "Special Operator ~S" data))
799          (:macro (format stream "Macro ~S" data))
800          (:section (format stream "Section ~{~D~^.~}" data))
801          (:glossary (format stream "Glossary entry for ~S" data))
802          (:issue (format stream "writeup for Issue ~A" data)))))
803     (:sbcl
804      (format stream "The SBCL Manual")
805      (format stream ", ")
806      (destructuring-bind (type data) (cdr reference)
807        (ecase type
808          (:node (format stream "Node ~S" data))
809          (:variable (format stream "Variable ~S" data)))))
810     ;; FIXME: other documents (e.g. AMOP, Franz documentation :-)
811     ))
812 (define-condition reference-condition ()
813   ((references :initarg :references :reader reference-condition-references)))
814 (defvar *print-condition-references* t)
815 (def!method print-object :around ((o reference-condition) s)
816   (call-next-method)
817   (unless (or *print-escape* *print-readably*)
818     (when *print-condition-references*
819       (format s "~&See also:~%")
820       (pprint-logical-block (s nil :per-line-prefix "  ")
821         (do* ((rs (reference-condition-references o) (cdr rs))
822               (r (car rs) (car rs)))
823              ((null rs))
824           (print-reference r s)
825           (unless (null (cdr rs))
826             (terpri s)))))))
827     
828 (define-condition duplicate-definition (reference-condition warning)
829   ((name :initarg :name :reader duplicate-definition-name))
830   (:report (lambda (c s)
831              (format s "~@<Duplicate definition for ~S found in ~
832                         one file.~@:>"
833                      (duplicate-definition-name c))))
834   (:default-initargs :references (list '(:ansi-cl :section (3 2 2 3)))))
835
836 (define-condition package-at-variance (reference-condition simple-warning) 
837   ()
838   (:default-initargs :references (list '(:ansi-cl :macro defpackage))))
839
840 (define-condition defconstant-uneql (reference-condition error)
841   ((name :initarg :name :reader defconstant-uneql-name)
842    (old-value :initarg :old-value :reader defconstant-uneql-old-value)
843    (new-value :initarg :new-value :reader defconstant-uneql-new-value))
844   (:report
845    (lambda (condition stream)
846      (format stream
847              "~@<The constant ~S is being redefined (from ~S to ~S)~@:>"
848              (defconstant-uneql-name condition)
849              (defconstant-uneql-old-value condition)
850              (defconstant-uneql-new-value condition))))
851   (:default-initargs :references (list '(:ansi-cl :macro defconstant)
852                                        '(:sbcl :node "Idiosyncrasies"))))
853
854 (define-condition array-initial-element-mismatch 
855     (reference-condition simple-warning)
856   ()
857   (:default-initargs 
858       :references (list 
859                    '(:ansi-cl :function make-array) 
860                    '(:ansi-cl :function sb!xc:upgraded-array-element-type))))
861
862 (define-condition displaced-to-array-too-small-error
863     (reference-condition simple-error)
864   ()
865   (:default-initargs
866       :references (list '(:ansi-cl :function adjust-array))))
867
868 (define-condition type-warning (reference-condition simple-warning)
869   ()
870   (:default-initargs :references (list '(:sbcl :node "Handling of Types"))))
871
872 (define-condition local-argument-mismatch (reference-condition simple-warning)
873   ()
874   (:default-initargs :references (list '(:ansi-cl :section (3 2 2 3)))))
875
876 (define-condition format-args-mismatch (reference-condition)
877   ()
878   (:default-initargs :references (list '(:ansi-cl :section (22 3 10 2)))))
879
880 (define-condition format-too-few-args-warning 
881     (format-args-mismatch simple-warning)
882   ())
883 (define-condition format-too-many-args-warning
884     (format-args-mismatch simple-style-warning)
885   ())
886
887 (define-condition extension-failure (reference-condition simple-error)
888   ())
889 \f
890 ;;;; various other (not specified by ANSI) CONDITIONs
891 ;;;;
892 ;;;; These might logically belong in other files; they're here, after
893 ;;;; setup of CONDITION machinery, only because that makes it easier to
894 ;;;; get cold init to work.
895
896 (define-condition values-type-error (type-error)
897   ()
898   (:report
899    (lambda (condition stream)
900      (format stream
901              "~@<The values set ~2I~:_[~{~S~^ ~}] ~I~_is not of type ~2I~_~S.~:>"
902              (type-error-datum condition)
903              (type-error-expected-type condition)))))
904
905 ;;; KLUDGE: a condition for floating point errors when we can't or
906 ;;; won't figure out what type they are. (In FreeBSD and OpenBSD we
907 ;;; don't know how, at least as of sbcl-0.6.7; in Linux we probably
908 ;;; know how but the old code was broken by the conversion to POSIX
909 ;;; signal handling and hasn't been fixed as of sbcl-0.6.7.)
910 ;;;
911 ;;; FIXME: Perhaps this should also be a base class for all
912 ;;; floating point exceptions?
913 (define-condition floating-point-exception (arithmetic-error)
914   ((flags :initarg :traps
915           :initform nil
916           :reader floating-point-exception-traps))
917   (:report (lambda (condition stream)
918              (format stream
919                      "An arithmetic error ~S was signalled.~%"
920                      (type-of condition))
921              (let ((traps (floating-point-exception-traps condition)))
922                (if traps
923                    (format stream
924                            "Trapping conditions are: ~%~{ ~S~^~}~%"
925                            traps)
926                    (write-line
927                     "No traps are enabled? How can this be?"
928                     stream))))))
929
930 (define-condition index-too-large-error (type-error)
931   ()
932   (:report
933    (lambda (condition stream)
934      (format stream
935              "The index ~S is too large."
936              (type-error-datum condition)))))
937
938 (define-condition bounding-indices-bad-error (reference-condition type-error)
939   ((object :reader bounding-indices-bad-object :initarg :object))
940   (:report
941    (lambda (condition stream)
942      (let* ((datum (type-error-datum condition))
943             (start (car datum))
944             (end (cdr datum))
945             (object (bounding-indices-bad-object condition)))
946        (etypecase object
947          (sequence
948           (format stream
949                   "The bounding indices ~S and ~S are bad ~
950                    for a sequence of length ~S."
951                   start end (length object)))
952          (array
953           ;; from WITH-ARRAY-DATA
954           (format stream
955                   "The START and END parameters ~S and ~S are ~
956                    bad for an array of total size ~S."
957                   start end (array-total-size object)))))))
958   (:default-initargs 
959       :references 
960       (list '(:ansi-cl :glossary "bounding index designator")
961             '(:ansi-cl :issue "SUBSEQ-OUT-OF-BOUNDS:IS-AN-ERROR"))))
962
963 (define-condition nil-array-accessed-error (reference-condition type-error)
964   ()
965   (:report (lambda (condition stream)
966              (declare (ignore condition))
967              (format stream
968                      "An attempt to access an array of element-type ~
969                       NIL was made.  Congratulations!")))
970   (:default-initargs
971       :references (list '(:ansi-cl :function sb!xc:upgraded-array-element-type)
972                         '(:ansi-cl :section (15 1 2 1))
973                         '(:ansi-cl :section (15 1 2 2)))))
974
975 (define-condition io-timeout (stream-error)
976   ((direction :reader io-timeout-direction :initarg :direction))
977   (:report
978    (lambda (condition stream)
979      (declare (type stream stream))
980      (format stream
981              "I/O timeout ~(~A~)ing ~S"
982              (io-timeout-direction condition)
983              (stream-error-stream condition)))))
984
985 (define-condition namestring-parse-error (parse-error)
986   ((complaint :reader namestring-parse-error-complaint :initarg :complaint)
987    (args :reader namestring-parse-error-args :initarg :args :initform nil)
988    (namestring :reader namestring-parse-error-namestring :initarg :namestring)
989    (offset :reader namestring-parse-error-offset :initarg :offset))
990   (:report
991    (lambda (condition stream)
992      (format stream
993              "parse error in namestring: ~?~%  ~A~%  ~V@T^"
994              (namestring-parse-error-complaint condition)
995              (namestring-parse-error-args condition)
996              (namestring-parse-error-namestring condition)
997              (namestring-parse-error-offset condition)))))
998
999 (define-condition simple-package-error (simple-condition package-error) ())
1000
1001 (define-condition reader-package-error (reader-error) ())
1002
1003 (define-condition reader-eof-error (end-of-file)
1004   ((context :reader reader-eof-error-context :initarg :context))
1005   (:report
1006    (lambda (condition stream)
1007      (format stream
1008              "unexpected end of file on ~S ~A"
1009              (stream-error-stream condition)
1010              (reader-eof-error-context condition)))))
1011
1012 (define-condition reader-impossible-number-error (reader-error)
1013   ((error :reader reader-impossible-number-error-error :initarg :error))
1014   (:report
1015    (lambda (condition stream)
1016      (let ((error-stream (stream-error-stream condition)))
1017        (format stream "READER-ERROR ~@[at ~W ~]on ~S:~%~?~%Original error: ~A"
1018                (file-position error-stream) error-stream
1019                (reader-error-format-control condition)
1020                (reader-error-format-arguments condition)
1021                (reader-impossible-number-error-error condition))))))
1022
1023 (define-condition timeout (serious-condition) ())
1024 \f
1025 ;;;; restart definitions
1026
1027 (define-condition abort-failure (control-error) ()
1028   (:report
1029    "An ABORT restart was found that failed to transfer control dynamically."))
1030
1031 (defun abort (&optional condition)
1032   #!+sb-doc
1033   "Transfer control to a restart named ABORT, signalling a CONTROL-ERROR if
1034    none exists."
1035   (invoke-restart (find-restart-or-control-error 'abort condition))
1036   ;; ABORT signals an error in case there was a restart named ABORT
1037   ;; that did not transfer control dynamically. This could happen with
1038   ;; RESTART-BIND.
1039   (error 'abort-failure))
1040
1041 (defun muffle-warning (&optional condition)
1042   #!+sb-doc
1043   "Transfer control to a restart named MUFFLE-WARNING, signalling a
1044    CONTROL-ERROR if none exists."
1045   (invoke-restart (find-restart-or-control-error 'muffle-warning condition)))
1046
1047 (macrolet ((define-nil-returning-restart (name args doc)
1048              #!-sb-doc (declare (ignore doc))
1049              `(defun ,name (,@args &optional condition)
1050                 #!+sb-doc ,doc
1051                 ;; FIXME: Perhaps this shared logic should be pulled out into
1052                 ;; FLET MAYBE-INVOKE-RESTART? See whether it shrinks code..
1053                 (let ((restart (find-restart ',name condition)))
1054                   (when restart
1055                     (invoke-restart restart ,@args))))))
1056   (define-nil-returning-restart continue ()
1057     "Transfer control to a restart named CONTINUE, or return NIL if none exists.")
1058   (define-nil-returning-restart store-value (value)
1059     "Transfer control and VALUE to a restart named STORE-VALUE, or return NIL if
1060    none exists.")
1061   (define-nil-returning-restart use-value (value)
1062     "Transfer control and VALUE to a restart named USE-VALUE, or return NIL if
1063    none exists."))
1064
1065 (/show0 "condition.lisp end of file")
1066