1.0.41.47: (EXPT 0.0 0.0) and (EXPT 0 0.0) to signal an error
[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 ;;;; miscellaneous support utilities
17
18 ;;; Signalling an error when trying to print an error condition is
19 ;;; generally a PITA, so whatever the failure encountered when
20 ;;; wondering about FILE-POSITION within a condition printer, 'tis
21 ;;; better silently to give up than to try to complain.
22 (defun file-position-or-nil-for-error (stream &optional (pos nil posp))
23   ;; Arguably FILE-POSITION shouldn't be signalling errors at all; but
24   ;; "NIL if this cannot be determined" in the ANSI spec doesn't seem
25   ;; absolutely unambiguously to prohibit errors when, e.g., STREAM
26   ;; has been closed so that FILE-POSITION is a nonsense question. So
27   ;; my (WHN) impression is that the conservative approach is to
28   ;; IGNORE-ERRORS. (I encountered this failure from within a homebrew
29   ;; defsystemish operation where the ERROR-STREAM had been CL:CLOSEd,
30   ;; I think by nonlocally exiting through a WITH-OPEN-FILE, by the
31   ;; time an error was reported.)
32   (if posp
33       (ignore-errors (file-position stream pos))
34       (ignore-errors (file-position stream))))
35 \f
36 ;;;; the CONDITION class
37
38 (/show0 "condition.lisp 20")
39
40 (eval-when (:compile-toplevel :load-toplevel :execute)
41
42 (/show0 "condition.lisp 24")
43
44 (def!struct (condition-classoid (:include classoid)
45                                 (:constructor make-condition-classoid))
46   ;; list of CONDITION-SLOT structures for the direct slots of this
47   ;; class
48   (slots nil :type list)
49   ;; list of CONDITION-SLOT structures for all of the effective class
50   ;; slots of this class
51   (class-slots nil :type list)
52   ;; report function or NIL
53   (report nil :type (or function null))
54   ;; list of alternating initargs and initforms
55   (default-initargs () :type list)
56   ;; class precedence list as a list of CLASS objects, with all
57   ;; non-CONDITION classes removed
58   (cpl () :type list)
59   ;; a list of all the effective instance allocation slots of this
60   ;; class that have a non-constant initform or default-initarg.
61   ;; Values for these slots must be computed in the dynamic
62   ;; environment of MAKE-CONDITION.
63   (hairy-slots nil :type list))
64
65 (/show0 "condition.lisp 49")
66
67 ) ; EVAL-WHEN
68
69 (!defstruct-with-alternate-metaclass condition
70   :slot-names (actual-initargs assigned-slots)
71   :boa-constructor %make-condition-object
72   :superclass-name t
73   :metaclass-name condition-classoid
74   :metaclass-constructor make-condition-classoid
75   :dd-type structure)
76
77 (defun make-condition-object (actual-initargs)
78   (%make-condition-object actual-initargs nil))
79
80 (defstruct (condition-slot (:copier nil))
81   (name (missing-arg) :type symbol)
82   ;; list of all applicable initargs
83   (initargs (missing-arg) :type list)
84   ;; names of reader and writer functions
85   (readers (missing-arg) :type list)
86   (writers (missing-arg) :type list)
87   ;; true if :INITFORM was specified
88   (initform-p (missing-arg) :type (member t nil))
89   ;; If this is a function, call it with no args. Otherwise, it's the
90   ;; actual value.
91   (initform (missing-arg) :type t)
92   ;; allocation of this slot, or NIL until defaulted
93   (allocation nil :type (member :instance :class nil))
94   ;; If ALLOCATION is :CLASS, this is a cons whose car holds the value.
95   (cell nil :type (or cons null))
96   ;; slot documentation
97   (documentation nil :type (or string null)))
98
99 ;;; KLUDGE: It's not clear to me why CONDITION-CLASS has itself listed
100 ;;; in its CPL, while other classes derived from CONDITION-CLASS don't
101 ;;; have themselves listed in their CPLs. This behavior is inherited
102 ;;; from CMU CL, and didn't seem to be explained there, and I haven't
103 ;;; figured out whether it's right. -- WHN 19990612
104 (eval-when (:compile-toplevel :load-toplevel :execute)
105   (/show0 "condition.lisp 103")
106   (let ((condition-class (locally
107                            ;; KLUDGE: There's a DEFTRANSFORM
108                            ;; FIND-CLASSOID for constant class names
109                            ;; which creates fast but
110                            ;; non-cold-loadable, non-compact code. In
111                            ;; this context, we'd rather have compact,
112                            ;; cold-loadable code. -- WHN 19990928
113                            (declare (notinline find-classoid))
114                            (find-classoid 'condition))))
115     (setf (condition-classoid-cpl condition-class)
116           (list condition-class)))
117   (/show0 "condition.lisp 103"))
118
119 (setf (condition-classoid-report (locally
120                                    ;; KLUDGE: There's a DEFTRANSFORM
121                                    ;; FIND-CLASSOID for constant class
122                                    ;; names which creates fast but
123                                    ;; non-cold-loadable, non-compact
124                                    ;; code. In this context, we'd
125                                    ;; rather have compact,
126                                    ;; cold-loadable code. -- WHN
127                                    ;; 19990928
128                                    (declare (notinline find-classoid))
129                                    (find-classoid 'condition)))
130       (lambda (cond stream)
131         (format stream "Condition ~S was signalled." (type-of cond))))
132
133 (eval-when (:compile-toplevel :load-toplevel :execute)
134
135 (defun find-condition-layout (name parent-types)
136   (let* ((cpl (remove-duplicates
137                (reverse
138                 (reduce #'append
139                         (mapcar (lambda (x)
140                                   (condition-classoid-cpl
141                                    (find-classoid x)))
142                                 parent-types)))))
143          (cond-layout (info :type :compiler-layout 'condition))
144          (olayout (info :type :compiler-layout name))
145          ;; FIXME: Does this do the right thing in case of multiple
146          ;; inheritance? A quick look at DEFINE-CONDITION didn't make
147          ;; it obvious what ANSI intends to be done in the case of
148          ;; multiple inheritance, so it's not actually clear what the
149          ;; right thing is..
150          (new-inherits
151           (order-layout-inherits (concatenate 'simple-vector
152                                               (layout-inherits cond-layout)
153                                               (mapcar #'classoid-layout cpl)))))
154     (if (and olayout
155              (not (mismatch (layout-inherits olayout) new-inherits)))
156         olayout
157         (make-layout :classoid (make-undefined-classoid name)
158                      :inherits new-inherits
159                      :depthoid -1
160                      :length (layout-length cond-layout)))))
161
162 ) ; EVAL-WHEN
163
164 ;;; FIXME: ANSI's definition of DEFINE-CONDITION says
165 ;;;   Condition reporting is mediated through the PRINT-OBJECT method
166 ;;;   for the condition type in question, with *PRINT-ESCAPE* always
167 ;;;   being nil. Specifying (:REPORT REPORT-NAME) in the definition of
168 ;;;   a condition type C is equivalent to:
169 ;;;     (defmethod print-object ((x c) stream)
170 ;;;       (if *print-escape* (call-next-method) (report-name x stream)))
171 ;;; The current code doesn't seem to quite match that.
172 (def!method print-object ((x condition) stream)
173   (if *print-escape*
174       (if (and (typep x 'simple-condition) (slot-boundp x 'format-control))
175           (print-unreadable-object (x stream :type t :identity t)
176             (format stream "~S" (simple-condition-format-control x)))
177           (print-unreadable-object (x stream :type t :identity t)))
178       ;; KLUDGE: A comment from CMU CL here said
179       ;;   7/13/98 BUG? CPL is not sorted and results here depend on order of
180       ;;   superclasses in define-condition call!
181       (dolist (class (condition-classoid-cpl (classoid-of x))
182                      (error "no REPORT? shouldn't happen!"))
183         (let ((report (condition-classoid-report class)))
184           (when report
185             (return (funcall report x stream)))))))
186 \f
187 ;;;; slots of CONDITION objects
188
189 (defvar *empty-condition-slot* '(empty))
190
191 (defun find-slot-default (class slot)
192   (let ((initargs (condition-slot-initargs slot))
193         (cpl (condition-classoid-cpl class)))
194     (dolist (class cpl)
195       (let ((default-initargs (condition-classoid-default-initargs class)))
196         (dolist (initarg initargs)
197           (let ((val (getf default-initargs initarg *empty-condition-slot*)))
198             (unless (eq val *empty-condition-slot*)
199               (return-from find-slot-default
200                            (if (functionp val)
201                                (funcall val)
202                                val)))))))
203
204     (if (condition-slot-initform-p slot)
205         (let ((initform (condition-slot-initform slot)))
206           (if (functionp initform)
207               (funcall initform)
208               initform))
209         (error "unbound condition slot: ~S" (condition-slot-name slot)))))
210
211 (defun find-condition-class-slot (condition-class slot-name)
212   (dolist (sclass
213            (condition-classoid-cpl condition-class)
214            (error "There is no slot named ~S in ~S."
215                   slot-name condition-class))
216     (dolist (slot (condition-classoid-slots sclass))
217       (when (eq (condition-slot-name slot) slot-name)
218         (return-from find-condition-class-slot slot)))))
219
220 (defun condition-writer-function (condition new-value name)
221   (dolist (cslot (condition-classoid-class-slots
222                   (layout-classoid (%instance-layout condition)))
223                  (setf (getf (condition-assigned-slots condition) name)
224                        new-value))
225     (when (eq (condition-slot-name cslot) name)
226       (return (setf (car (condition-slot-cell cslot)) new-value)))))
227
228 (defun condition-reader-function (condition name)
229   (let ((class (layout-classoid (%instance-layout condition))))
230     (dolist (cslot (condition-classoid-class-slots class))
231       (when (eq (condition-slot-name cslot) name)
232         (return-from condition-reader-function
233                      (car (condition-slot-cell cslot)))))
234     (let ((val (getf (condition-assigned-slots condition) name
235                      *empty-condition-slot*)))
236       (if (eq val *empty-condition-slot*)
237           (let ((actual-initargs (condition-actual-initargs condition))
238                 (slot (find-condition-class-slot class name)))
239             (unless slot
240               (error "missing slot ~S of ~S" name condition))
241             (do ((initargs actual-initargs (cddr initargs)))
242                 ((endp initargs)
243                  (setf (getf (condition-assigned-slots condition) name)
244                        (find-slot-default class slot)))
245               (when (member (car initargs) (condition-slot-initargs slot))
246                 (return-from condition-reader-function
247                   (setf (getf (condition-assigned-slots condition)
248                               name)
249                         (cadr initargs))))))
250           val))))
251 \f
252 ;;;; MAKE-CONDITION
253
254 (defun make-condition (type &rest args)
255   #!+sb-doc
256   "Make an instance of a condition object using the specified initargs."
257   ;; Note: ANSI specifies no exceptional situations in this function.
258   ;; signalling simple-type-error would not be wrong.
259   (let* ((type (or (and (symbolp type) (find-classoid type nil))
260                     type))
261          (class (typecase type
262                   (condition-classoid type)
263                   (class
264                    ;; Punt to CLOS.
265                    (return-from make-condition (apply #'make-instance type args)))
266                   (classoid
267                    (error 'simple-type-error
268                           :datum type
269                           :expected-type 'condition-class
270                           :format-control "~S is not a condition class."
271                           :format-arguments (list type)))
272                   (t
273                    (error 'simple-type-error
274                           :datum type
275                           :expected-type 'condition-class
276                           :format-control "Bad type argument:~%  ~S"
277                           :format-arguments (list type)))))
278          (res (make-condition-object args)))
279     (setf (%instance-layout res) (classoid-layout class))
280     ;; Set any class slots with initargs present in this call.
281     (dolist (cslot (condition-classoid-class-slots class))
282       (dolist (initarg (condition-slot-initargs cslot))
283         (let ((val (getf args initarg *empty-condition-slot*)))
284           (unless (eq val *empty-condition-slot*)
285             (setf (car (condition-slot-cell cslot)) val)))))
286     ;; Default any slots with non-constant defaults now.
287     (dolist (hslot (condition-classoid-hairy-slots class))
288       (when (dolist (initarg (condition-slot-initargs hslot) t)
289               (unless (eq (getf args initarg *empty-condition-slot*)
290                           *empty-condition-slot*)
291                 (return nil)))
292         (setf (getf (condition-assigned-slots res) (condition-slot-name hslot))
293               (find-slot-default class hslot))))
294     res))
295 \f
296 ;;;; DEFINE-CONDITION
297
298 (eval-when (:compile-toplevel :load-toplevel :execute)
299 (defun %compiler-define-condition (name direct-supers layout
300                                    all-readers all-writers)
301   (with-single-package-locked-error
302       (:symbol name "defining ~A as a condition")
303     (sb!xc:proclaim `(ftype (function (t) t) ,@all-readers))
304     (sb!xc:proclaim `(ftype (function (t t) t) ,@all-writers))
305     (multiple-value-bind (class old-layout)
306         (insured-find-classoid name
307                                #'condition-classoid-p
308                                #'make-condition-classoid)
309       (setf (layout-classoid layout) class)
310       (setf (classoid-direct-superclasses class)
311             (mapcar #'find-classoid direct-supers))
312       (cond ((not old-layout)
313              (register-layout layout))
314             ((not *type-system-initialized*)
315              (setf (layout-classoid old-layout) class)
316              (setq layout old-layout)
317              (unless (eq (classoid-layout class) layout)
318                (register-layout layout)))
319             ((redefine-layout-warning "current"
320                                       old-layout
321                                       "new"
322                                       (layout-length layout)
323                                       (layout-inherits layout)
324                                       (layout-depthoid layout)
325                                       (layout-n-untagged-slots layout))
326              (register-layout layout :invalidate t))
327             ((not (classoid-layout class))
328              (register-layout layout)))
329
330       (setf (layout-info layout)
331             (locally
332                 ;; KLUDGE: There's a FIND-CLASS DEFTRANSFORM for constant class
333                 ;; names which creates fast but non-cold-loadable, non-compact
334                 ;; code. In this context, we'd rather have compact, cold-loadable
335                 ;; code. -- WHN 19990928
336                 (declare (notinline find-classoid))
337               (layout-info (classoid-layout (find-classoid 'condition)))))
338
339       (setf (find-classoid name) class)
340
341       ;; Initialize CPL slot.
342       (setf (condition-classoid-cpl class)
343             (remove-if-not #'condition-classoid-p
344                            (std-compute-class-precedence-list class)))))
345   (values))
346 ) ; EVAL-WHEN
347
348 ;;; Compute the effective slots of CLASS, copying inherited slots and
349 ;;; destructively modifying direct slots.
350 ;;;
351 ;;; FIXME: It'd be nice to explain why it's OK to destructively modify
352 ;;; direct slots. Presumably it follows from the semantics of
353 ;;; inheritance and redefinition of conditions, but finding the cite
354 ;;; and documenting it here would be good. (Or, if this is not in fact
355 ;;; ANSI-compliant, fixing it would also be good.:-)
356 (defun compute-effective-slots (class)
357   (collect ((res (copy-list (condition-classoid-slots class))))
358     (dolist (sclass (cdr (condition-classoid-cpl class)))
359       (dolist (sslot (condition-classoid-slots sclass))
360         (let ((found (find (condition-slot-name sslot) (res)
361                            :key #'condition-slot-name)))
362           (cond (found
363                  (setf (condition-slot-initargs found)
364                        (union (condition-slot-initargs found)
365                               (condition-slot-initargs sslot)))
366                  (unless (condition-slot-initform-p found)
367                    (setf (condition-slot-initform-p found)
368                          (condition-slot-initform-p sslot))
369                    (setf (condition-slot-initform found)
370                          (condition-slot-initform sslot)))
371                  (unless (condition-slot-allocation found)
372                    (setf (condition-slot-allocation found)
373                          (condition-slot-allocation sslot))))
374                 (t
375                  (res (copy-structure sslot)))))))
376     (res)))
377
378 ;;; Early definitions of slot accessor creators.
379 ;;;
380 ;;; Slot accessors must be generic functions, but ANSI does not seem
381 ;;; to specify any of them, and we cannot support it before end of
382 ;;; warm init. So we use ordinary functions inside SBCL, and switch to
383 ;;; GFs only at the end of building.
384 (declaim (notinline install-condition-slot-reader
385                     install-condition-slot-writer))
386 (defun install-condition-slot-reader (name condition slot-name)
387   (declare (ignore condition))
388   (setf (fdefinition name)
389         (lambda (condition)
390           (condition-reader-function condition slot-name))))
391 (defun install-condition-slot-writer (name condition slot-name)
392   (declare (ignore condition))
393   (setf (fdefinition name)
394         (lambda (new-value condition)
395           (condition-writer-function condition new-value slot-name))))
396
397 (defvar *define-condition-hooks* nil)
398
399 (defun %define-condition (name parent-types layout slots documentation
400                           report default-initargs all-readers all-writers
401                           source-location)
402   (with-single-package-locked-error
403       (:symbol name "defining ~A as a condition")
404     (%compiler-define-condition name parent-types layout all-readers all-writers)
405     (sb!c:with-source-location (source-location)
406       (setf (layout-source-location layout)
407             source-location))
408     (let ((class (find-classoid name)))
409       (setf (condition-classoid-slots class) slots)
410       (setf (condition-classoid-report class) report)
411       (setf (condition-classoid-default-initargs class) default-initargs)
412       (setf (fdocumentation name 'type) documentation)
413
414       (dolist (slot slots)
415
416         ;; Set up reader and writer functions.
417         (let ((slot-name (condition-slot-name slot)))
418           (dolist (reader (condition-slot-readers slot))
419             (install-condition-slot-reader reader name slot-name))
420           (dolist (writer (condition-slot-writers slot))
421             (install-condition-slot-writer writer name slot-name))))
422
423       ;; Compute effective slots and set up the class and hairy slots
424       ;; (subsets of the effective slots.)
425       (let ((eslots (compute-effective-slots class))
426             (e-def-initargs
427              (reduce #'append
428                      (mapcar #'condition-classoid-default-initargs
429                            (condition-classoid-cpl class)))))
430         (dolist (slot eslots)
431           (ecase (condition-slot-allocation slot)
432             (:class
433              (unless (condition-slot-cell slot)
434                (setf (condition-slot-cell slot)
435                      (list (if (condition-slot-initform-p slot)
436                                (let ((initform (condition-slot-initform slot)))
437                                  (if (functionp initform)
438                                      (funcall initform)
439                                      initform))
440                                *empty-condition-slot*))))
441              (push slot (condition-classoid-class-slots class)))
442             ((:instance nil)
443              (setf (condition-slot-allocation slot) :instance)
444              (when (or (functionp (condition-slot-initform slot))
445                        (dolist (initarg (condition-slot-initargs slot) nil)
446                          (when (functionp (getf e-def-initargs initarg))
447                            (return t))))
448                (push slot (condition-classoid-hairy-slots class)))))))
449       (when (boundp '*define-condition-hooks*)
450         (dolist (fun *define-condition-hooks*)
451           (funcall fun class))))
452     name))
453
454 (defmacro define-condition (name (&rest parent-types) (&rest slot-specs)
455                                  &body options)
456   #!+sb-doc
457   "DEFINE-CONDITION Name (Parent-Type*) (Slot-Spec*) Option*
458    Define NAME as a condition type. This new type inherits slots and its
459    report function from the specified PARENT-TYPEs. A slot spec is a list of:
460      (slot-name :reader <rname> :initarg <iname> {Option Value}*
461
462    The DEFINE-CLASS slot options :ALLOCATION, :INITFORM, [slot] :DOCUMENTATION
463    and :TYPE and the overall options :DEFAULT-INITARGS and
464    [type] :DOCUMENTATION are also allowed.
465
466    The :REPORT option is peculiar to DEFINE-CONDITION. Its argument is either
467    a string or a two-argument lambda or function name. If a function, the
468    function is called with the condition and stream to report the condition.
469    If a string, the string is printed.
470
471    Condition types are classes, but (as allowed by ANSI and not as described in
472    CLtL2) are neither STANDARD-OBJECTs nor STRUCTURE-OBJECTs. WITH-SLOTS and
473    SLOT-VALUE may not be used on condition objects."
474   (let* ((parent-types (or parent-types '(condition)))
475          (layout (find-condition-layout name parent-types))
476          (documentation nil)
477          (report nil)
478          (default-initargs ()))
479     (collect ((slots)
480               (all-readers nil append)
481               (all-writers nil append))
482       (dolist (spec slot-specs)
483         (when (keywordp spec)
484           (warn "Keyword slot name indicates probable syntax error:~%  ~S"
485                 spec))
486         (let* ((spec (if (consp spec) spec (list spec)))
487                (slot-name (first spec))
488                (allocation :instance)
489                (initform-p nil)
490                documentation
491                initform)
492           (collect ((initargs)
493                     (readers)
494                     (writers))
495             (do ((options (rest spec) (cddr options)))
496                 ((null options))
497               (unless (and (consp options) (consp (cdr options)))
498                 (error "malformed condition slot spec:~%  ~S." spec))
499               (let ((arg (second options)))
500                 (case (first options)
501                   (:reader (readers arg))
502                   (:writer (writers arg))
503                   (:accessor
504                    (readers arg)
505                    (writers `(setf ,arg)))
506                   (:initform
507                    (when initform-p
508                      (error "more than one :INITFORM in ~S" spec))
509                    (setq initform-p t)
510                    (setq initform arg))
511                   (:initarg (initargs arg))
512                   (:allocation
513                    (setq allocation arg))
514                   (:documentation
515                    (when documentation
516                      (error "more than one :DOCUMENTATION in ~S" spec))
517                    (unless (stringp arg)
518                      (error "slot :DOCUMENTATION argument is not a string: ~S"
519                             arg))
520                    (setq documentation arg))
521                   (:type)
522                   (t
523                    (error "unknown slot option:~%  ~S" (first options))))))
524
525             (all-readers (readers))
526             (all-writers (writers))
527             (slots `(make-condition-slot
528                      :name ',slot-name
529                      :initargs ',(initargs)
530                      :readers ',(readers)
531                      :writers ',(writers)
532                      :initform-p ',initform-p
533                      :documentation ',documentation
534                      :initform
535                      ,(if (sb!xc:constantp initform)
536                           `',(constant-form-value initform)
537                           `#'(lambda () ,initform)))))))
538
539       (dolist (option options)
540         (unless (consp option)
541           (error "bad option:~%  ~S" option))
542         (case (first option)
543           (:documentation (setq documentation (second option)))
544           (:report
545            (let ((arg (second option)))
546              (setq report
547                    (if (stringp arg)
548                        `#'(lambda (condition stream)
549                           (declare (ignore condition))
550                           (write-string ,arg stream))
551                        `#'(lambda (condition stream)
552                           (funcall #',arg condition stream))))))
553           (:default-initargs
554            (do ((initargs (rest option) (cddr initargs)))
555                ((endp initargs))
556              (let ((val (second initargs)))
557                (setq default-initargs
558                      (list* `',(first initargs)
559                             (if (sb!xc:constantp val)
560                                 `',(constant-form-value val)
561                                 `#'(lambda () ,val))
562                             default-initargs)))))
563           (t
564            (error "unknown option: ~S" (first option)))))
565
566       `(progn
567          (eval-when (:compile-toplevel)
568            (%compiler-define-condition ',name ',parent-types ',layout
569                                        ',(all-readers) ',(all-writers)))
570          (eval-when (:load-toplevel :execute)
571            (%define-condition ',name
572                               ',parent-types
573                               ',layout
574                               (list ,@(slots))
575                               ,documentation
576                               ,report
577                               (list ,@default-initargs)
578                               ',(all-readers)
579                               ',(all-writers)
580                               (sb!c:source-location)))))))
581 \f
582 ;;;; various CONDITIONs specified by ANSI
583
584 (define-condition serious-condition (condition) ())
585
586 (define-condition error (serious-condition) ())
587
588 (define-condition warning (condition) ())
589 (define-condition style-warning (warning) ())
590
591 (defun simple-condition-printer (condition stream)
592   (apply #'format
593          stream
594          (simple-condition-format-control condition)
595          (simple-condition-format-arguments condition)))
596
597 (define-condition simple-condition ()
598   ((format-control :reader simple-condition-format-control
599                    :initarg :format-control
600                    :type format-control)
601    (format-arguments :reader simple-condition-format-arguments
602                      :initarg :format-arguments
603                      :initform '()
604                      :type list))
605   (:report simple-condition-printer))
606
607 (define-condition simple-warning (simple-condition warning) ())
608
609 (define-condition simple-error (simple-condition error) ())
610
611 (define-condition storage-condition (serious-condition) ())
612
613 (define-condition type-error (error)
614   ((datum :reader type-error-datum :initarg :datum)
615    (expected-type :reader type-error-expected-type :initarg :expected-type))
616   (:report
617    (lambda (condition stream)
618      (format stream
619              "~@<The value ~2I~:_~S ~I~_is not of type ~2I~_~S.~:>"
620              (type-error-datum condition)
621              (type-error-expected-type condition)))))
622
623 ;;; not specified by ANSI, but too useful not to have around.
624 (define-condition simple-style-warning (simple-condition style-warning) ())
625 (define-condition simple-type-error (simple-condition type-error) ())
626
627 (define-condition program-error (error) ())
628 (define-condition parse-error   (error) ())
629 (define-condition control-error (error) ())
630 (define-condition stream-error  (error)
631   ((stream :reader stream-error-stream :initarg :stream)))
632
633 (define-condition end-of-file (stream-error) ()
634   (:report
635    (lambda (condition stream)
636      (format stream
637              "end of file on ~S"
638              (stream-error-stream condition)))))
639
640 (define-condition closed-stream-error (stream-error) ()
641   (:report
642    (lambda (condition stream)
643      (format stream "~S is closed" (stream-error-stream condition)))))
644
645 (define-condition file-error (error)
646   ((pathname :reader file-error-pathname :initarg :pathname))
647   (:report
648    (lambda (condition stream)
649      (format stream "error on file ~S" (file-error-pathname condition)))))
650
651 (define-condition package-error (error)
652   ((package :reader package-error-package :initarg :package)))
653
654 (define-condition cell-error (error)
655   ((name :reader cell-error-name :initarg :name)))
656
657 (def!method print-object ((condition cell-error) stream)
658   (if (and *print-escape* (slot-boundp condition 'name))
659       (print-unreadable-object (condition stream :type t :identity t)
660         (princ (cell-error-name condition) stream))
661       (call-next-method)))
662
663 (define-condition unbound-variable (cell-error) ()
664   (:report
665    (lambda (condition stream)
666      (format stream
667              "The variable ~S is unbound."
668              (cell-error-name condition)))))
669
670 (define-condition undefined-function (cell-error) ()
671   (:report
672    (lambda (condition stream)
673      (format stream
674              "The function ~S is undefined."
675              (cell-error-name condition)))))
676
677 (define-condition special-form-function (undefined-function) ()
678   (:report
679    (lambda (condition stream)
680      (format stream
681              "Cannot FUNCALL the SYMBOL-FUNCTION of special operator ~S."
682              (cell-error-name condition)))))
683
684 (define-condition arithmetic-error (error)
685   ((operation :reader arithmetic-error-operation
686               :initarg :operation
687               :initform nil)
688    (operands :reader arithmetic-error-operands
689              :initarg :operands))
690   (:report (lambda (condition stream)
691              (format stream
692                      "arithmetic error ~S signalled"
693                      (type-of condition))
694              (when (arithmetic-error-operation condition)
695                (format stream
696                        "~%Operation was ~S, operands ~S."
697                        (arithmetic-error-operation condition)
698                        (arithmetic-error-operands condition))))))
699
700 (define-condition division-by-zero         (arithmetic-error) ())
701 (define-condition floating-point-overflow  (arithmetic-error) ())
702 (define-condition floating-point-underflow (arithmetic-error) ())
703 (define-condition floating-point-inexact   (arithmetic-error) ())
704 (define-condition floating-point-invalid-operation (arithmetic-error) ())
705
706 (define-condition print-not-readable (error)
707   ((object :reader print-not-readable-object :initarg :object))
708   (:report
709    (lambda (condition stream)
710      (let ((obj (print-not-readable-object condition))
711            (*print-array* nil))
712        (format stream "~S cannot be printed readably." obj)))))
713
714 (define-condition reader-error (parse-error stream-error) ()
715   (:report (lambda (condition stream)
716              (%report-reader-error condition stream))))
717
718 ;;; a READER-ERROR whose REPORTing is controlled by FORMAT-CONTROL and
719 ;;; FORMAT-ARGS (the usual case for READER-ERRORs signalled from
720 ;;; within SBCL itself)
721 ;;;
722 ;;; (Inheriting CL:SIMPLE-CONDITION here isn't quite consistent with
723 ;;; the letter of the ANSI spec: this is not a condition signalled by
724 ;;; SIGNAL when a format-control is supplied by the function's first
725 ;;; argument. It seems to me (WHN) to be basically in the spirit of
726 ;;; the spec, but if not, it'd be straightforward to do our own
727 ;;; DEFINE-CONDITION SB-INT:SIMPLISTIC-CONDITION with
728 ;;; FORMAT-CONTROL and FORMAT-ARGS slots, and use that condition in
729 ;;; place of CL:SIMPLE-CONDITION here.)
730 (define-condition simple-reader-error (reader-error simple-condition)
731   ()
732   (:report (lambda (condition stream)
733              (%report-reader-error condition stream :simple t))))
734
735 ;;; base REPORTing of a READER-ERROR
736 ;;;
737 ;;; When SIMPLE, we expect and use SIMPLE-CONDITION-ish FORMAT-CONTROL
738 ;;; and FORMAT-ARGS slots.
739 (defun %report-reader-error (condition stream &key simple)
740   (let* ((error-stream (stream-error-stream condition))
741          (pos (file-position-or-nil-for-error error-stream)))
742     (let (lineno colno)
743       (when (and pos
744                  (< pos sb!xc:array-dimension-limit)
745                  ;; KLUDGE: lseek() (which is what FILE-POSITION
746                  ;; reduces to on file-streams) is undefined on
747                  ;; "some devices", which in practice means that it
748                  ;; can claim to succeed on /dev/stdin on Darwin
749                  ;; and Solaris.  This is obviously bad news,
750                  ;; because the READ-SEQUENCE below will then
751                  ;; block, not complete, and the report will never
752                  ;; be printed.  As a workaround, we exclude
753                  ;; interactive streams from this attempt to report
754                  ;; positions.  -- CSR, 2003-08-21
755                  (not (interactive-stream-p error-stream))
756                  (file-position error-stream :start))
757         (let ((string
758                (make-string pos
759                             :element-type (stream-element-type
760                                            error-stream))))
761           (when (= pos (read-sequence string error-stream))
762             (setq lineno (1+ (count #\Newline string))
763                   colno (- pos
764                            (or (position #\Newline string :from-end t) -1)
765                            1))))
766         (file-position-or-nil-for-error error-stream pos))
767       (pprint-logical-block (stream nil)
768         (format stream
769                 "~S ~@[at ~W ~]~
770                     ~@[(line ~W~]~@[, column ~W) ~]~
771                     on ~S"
772                 (class-name (class-of condition))
773                 pos lineno colno error-stream)
774         (when simple
775           (format stream ":~2I~_~?"
776                   (simple-condition-format-control condition)
777                   (simple-condition-format-arguments condition)))))))
778 \f
779 ;;;; special SBCL extension conditions
780
781 ;;; an error apparently caused by a bug in SBCL itself
782 ;;;
783 ;;; Note that we don't make any serious effort to use this condition
784 ;;; for *all* errors in SBCL itself. E.g. type errors and array
785 ;;; indexing errors can occur in functions called from SBCL code, and
786 ;;; will just end up as ordinary TYPE-ERROR or invalid index error,
787 ;;; because the signalling code has no good way to know that the
788 ;;; underlying problem is a bug in SBCL. But in the fairly common case
789 ;;; that the signalling code does know that it's found a bug in SBCL,
790 ;;; this condition is appropriate, reusing boilerplate and helping
791 ;;; users to recognize it as an SBCL bug.
792 (define-condition bug (simple-error)
793   ()
794   (:report
795    (lambda (condition stream)
796      (format stream
797              "~@<  ~? ~:@_~?~:>"
798              (simple-condition-format-control condition)
799              (simple-condition-format-arguments condition)
800              "~@<This is probably a bug in SBCL itself. (Alternatively, ~
801               SBCL might have been corrupted by bad user code, e.g. by an ~
802               undefined Lisp operation like ~S, or by stray pointers from ~
803               alien code or from unsafe Lisp code; or there might be a bug ~
804               in the OS or hardware that SBCL is running on.) If it seems to ~
805               be a bug in SBCL itself, the maintainers would like to know ~
806               about it. Bug reports are welcome on the SBCL ~
807               mailing lists, which you can find at ~
808               <http://sbcl.sourceforge.net/>.~:@>"
809              '((fmakunbound 'compile))))))
810
811 (define-condition simple-storage-condition (storage-condition simple-condition)
812   ())
813
814 ;;; a condition for use in stubs for operations which aren't supported
815 ;;; on some platforms
816 ;;;
817 ;;; E.g. in sbcl-0.7.0.5, it might be appropriate to do something like
818 ;;;   #-(or freebsd linux)
819 ;;;   (defun load-foreign (&rest rest)
820 ;;;     (error 'unsupported-operator :name 'load-foreign))
821 ;;;   #+(or freebsd linux)
822 ;;;   (defun load-foreign ... actual definition ...)
823 ;;; By signalling a standard condition in this case, we make it
824 ;;; possible for test code to distinguish between (1) intentionally
825 ;;; unimplemented and (2) unintentionally just screwed up somehow.
826 ;;; (Before this condition was defined, test code tried to deal with
827 ;;; this by checking for FBOUNDP, but that didn't work reliably. In
828 ;;; sbcl-0.7.0, a package screwup left the definition of
829 ;;; LOAD-FOREIGN in the wrong package, so it was unFBOUNDP even on
830 ;;; architectures where it was supposed to be supported, and the
831 ;;; regression tests cheerfully passed because they assumed that
832 ;;; unFBOUNDPness meant they were running on an system which didn't
833 ;;; support the extension.)
834 (define-condition unsupported-operator (simple-error) ())
835 \f
836 ;;; (:ansi-cl :function remove)
837 ;;; (:ansi-cl :section (a b c))
838 ;;; (:ansi-cl :glossary "similar")
839 ;;;
840 ;;; (:sbcl :node "...")
841 ;;; (:sbcl :variable *ed-functions*)
842 ;;;
843 ;;; FIXME: this is not the right place for this.
844 (defun print-reference (reference stream)
845   (ecase (car reference)
846     (:amop
847      (format stream "AMOP")
848      (format stream ", ")
849      (destructuring-bind (type data) (cdr reference)
850        (ecase type
851          (:readers "Readers for ~:(~A~) Metaobjects"
852                    (substitute #\  #\- (symbol-name data)))
853          (:initialization
854           (format stream "Initialization of ~:(~A~) Metaobjects"
855                   (substitute #\  #\- (symbol-name data))))
856          (:generic-function (format stream "Generic Function ~S" data))
857          (:function (format stream "Function ~S" data))
858          (:section (format stream "Section ~{~D~^.~}" data)))))
859     (:ansi-cl
860      (format stream "The ANSI Standard")
861      (format stream ", ")
862      (destructuring-bind (type data) (cdr reference)
863        (ecase type
864          (:function (format stream "Function ~S" data))
865          (:special-operator (format stream "Special Operator ~S" data))
866          (:macro (format stream "Macro ~S" data))
867          (:section (format stream "Section ~{~D~^.~}" data))
868          (:glossary (format stream "Glossary entry for ~S" data))
869          (:issue (format stream "writeup for Issue ~A" data)))))
870     (:sbcl
871      (format stream "The SBCL Manual")
872      (format stream ", ")
873      (destructuring-bind (type data) (cdr reference)
874        (ecase type
875          (:node (format stream "Node ~S" data))
876          (:variable (format stream "Variable ~S" data))
877          (:function (format stream "Function ~S" data)))))
878     ;; FIXME: other documents (e.g. CLIM, Franz documentation :-)
879     ))
880 (define-condition reference-condition ()
881   ((references :initarg :references :reader reference-condition-references)))
882 (defvar *print-condition-references* t)
883 (def!method print-object :around ((o reference-condition) s)
884   (call-next-method)
885   (unless (or *print-escape* *print-readably*)
886     (when (and *print-condition-references*
887                (reference-condition-references o))
888       (format s "~&See also:~%")
889       (pprint-logical-block (s nil :per-line-prefix "  ")
890         (do* ((rs (reference-condition-references o) (cdr rs))
891               (r (car rs) (car rs)))
892              ((null rs))
893           (print-reference r s)
894           (unless (null (cdr rs))
895             (terpri s)))))))
896
897 (define-condition simple-reference-error (reference-condition simple-error)
898   ())
899
900 (define-condition simple-reference-warning (reference-condition simple-warning)
901   ())
902
903 (define-condition arguments-out-of-domain-error
904     (arithmetic-error reference-condition)
905   ())
906
907 (define-condition duplicate-definition (reference-condition warning)
908   ((name :initarg :name :reader duplicate-definition-name))
909   (:report (lambda (c s)
910              (format s "~@<Duplicate definition for ~S found in ~
911                         one file.~@:>"
912                      (duplicate-definition-name c))))
913   (:default-initargs :references (list '(:ansi-cl :section (3 2 2 3)))))
914
915 (define-condition constant-modified (reference-condition warning)
916   ((fun-name :initarg :fun-name :reader constant-modified-fun-name))
917   (:report (lambda (c s)
918              (format s "~@<Destructive function ~S called on ~
919                         constant data.~@:>"
920                      (constant-modified-fun-name c))))
921   (:default-initargs :references (list '(:ansi-cl :special-operator quote)
922                                        '(:ansi-cl :section (3 2 2 3)))))
923
924 (define-condition package-at-variance (reference-condition simple-warning)
925   ()
926   (:default-initargs :references (list '(:ansi-cl :macro defpackage))))
927
928 (define-condition defconstant-uneql (reference-condition error)
929   ((name :initarg :name :reader defconstant-uneql-name)
930    (old-value :initarg :old-value :reader defconstant-uneql-old-value)
931    (new-value :initarg :new-value :reader defconstant-uneql-new-value))
932   (:report
933    (lambda (condition stream)
934      (format stream
935              "~@<The constant ~S is being redefined (from ~S to ~S)~@:>"
936              (defconstant-uneql-name condition)
937              (defconstant-uneql-old-value condition)
938              (defconstant-uneql-new-value condition))))
939   (:default-initargs :references (list '(:ansi-cl :macro defconstant)
940                                        '(:sbcl :node "Idiosyncrasies"))))
941
942 (define-condition array-initial-element-mismatch
943     (reference-condition simple-warning)
944   ()
945   (:default-initargs
946       :references (list
947                    '(:ansi-cl :function make-array)
948                    '(:ansi-cl :function sb!xc:upgraded-array-element-type))))
949
950 (define-condition type-warning (reference-condition simple-warning)
951   ()
952   (:default-initargs :references (list '(:sbcl :node "Handling of Types"))))
953 (define-condition type-style-warning (reference-condition simple-style-warning)
954   ()
955   (:default-initargs :references (list '(:sbcl :node "Handling of Types"))))
956
957 (define-condition local-argument-mismatch (reference-condition simple-warning)
958   ()
959   (:default-initargs :references (list '(:ansi-cl :section (3 2 2 3)))))
960
961 (define-condition format-args-mismatch (reference-condition)
962   ()
963   (:default-initargs :references (list '(:ansi-cl :section (22 3 10 2)))))
964
965 (define-condition format-too-few-args-warning
966     (format-args-mismatch simple-warning)
967   ())
968 (define-condition format-too-many-args-warning
969     (format-args-mismatch simple-style-warning)
970   ())
971
972 (define-condition implicit-generic-function-warning (style-warning)
973   ((name :initarg :name :reader implicit-generic-function-name))
974   (:report
975    (lambda (condition stream)
976      (format stream "~@<Implicitly creating new generic function ~S.~:@>"
977              (implicit-generic-function-name condition)))))
978
979 (define-condition extension-failure (reference-condition simple-error)
980   ())
981
982 (define-condition structure-initarg-not-keyword
983     (reference-condition simple-style-warning)
984   ()
985   (:default-initargs :references (list '(:ansi-cl :section (2 4 8 13)))))
986
987 #!+sb-package-locks
988 (progn
989
990 (define-condition package-lock-violation (reference-condition package-error)
991   ((format-control :initform nil :initarg :format-control
992                    :reader package-error-format-control)
993    (format-arguments :initform nil :initarg :format-arguments
994                      :reader package-error-format-arguments))
995   (:report
996    (lambda (condition stream)
997      (let ((control (package-error-format-control condition)))
998        (if control
999            (apply #'format stream
1000                   (format nil "~~@<Lock on package ~A violated when ~A.~~:@>"
1001                           (package-name (package-error-package condition))
1002                           control)
1003                   (package-error-format-arguments condition))
1004            (format stream "~@<Lock on package ~A violated.~:@>"
1005                    (package-name (package-error-package condition)))))))
1006   ;; no :default-initargs -- reference-stuff provided by the
1007   ;; signalling form in target-package.lisp
1008   #!+sb-doc
1009   (:documentation
1010    "Subtype of CL:PACKAGE-ERROR. A subtype of this error is signalled
1011 when a package-lock is violated."))
1012
1013 (define-condition package-locked-error (package-lock-violation) ()
1014   #!+sb-doc
1015   (:documentation
1016    "Subtype of SB-EXT:PACKAGE-LOCK-VIOLATION. An error of this type is
1017 signalled when an operation on a package violates a package lock."))
1018
1019 (define-condition symbol-package-locked-error (package-lock-violation)
1020   ((symbol :initarg :symbol :reader package-locked-error-symbol))
1021   #!+sb-doc
1022   (:documentation
1023    "Subtype of SB-EXT:PACKAGE-LOCK-VIOLATION. An error of this type is
1024 signalled when an operation on a symbol violates a package lock. The
1025 symbol that caused the violation is accessed by the function
1026 SB-EXT:PACKAGE-LOCKED-ERROR-SYMBOL."))
1027
1028 ) ; progn
1029
1030 (define-condition undefined-alien-error (cell-error) ()
1031   (:report
1032    (lambda (condition stream)
1033      (if (slot-boundp condition 'name)
1034          (format stream "Undefined alien: ~S" (cell-error-name condition))
1035          (format stream "Undefined alien symbol.")))))
1036
1037 (define-condition undefined-alien-variable-error (undefined-alien-error) ()
1038   (:report
1039    (lambda (condition stream)
1040      (declare (ignore condition))
1041      (format stream "Attempt to access an undefined alien variable."))))
1042
1043 (define-condition undefined-alien-function-error (undefined-alien-error) ()
1044   (:report
1045    (lambda (condition stream)
1046      (declare (ignore condition))
1047      (format stream "Attempt to call an undefined alien function."))))
1048
1049 \f
1050 ;;;; various other (not specified by ANSI) CONDITIONs
1051 ;;;;
1052 ;;;; These might logically belong in other files; they're here, after
1053 ;;;; setup of CONDITION machinery, only because that makes it easier to
1054 ;;;; get cold init to work.
1055
1056 ;;; OAOOM warning: see cross-condition.lisp
1057 (define-condition encapsulated-condition (condition)
1058   ((condition :initarg :condition :reader encapsulated-condition)))
1059
1060 (define-condition values-type-error (type-error)
1061   ()
1062   (:report
1063    (lambda (condition stream)
1064      (format stream
1065              "~@<The values set ~2I~:_[~{~S~^ ~}] ~I~_is not of type ~2I~_~S.~:>"
1066              (type-error-datum condition)
1067              (type-error-expected-type condition)))))
1068
1069 ;;; KLUDGE: a condition for floating point errors when we can't or
1070 ;;; won't figure out what type they are. (In FreeBSD and OpenBSD we
1071 ;;; don't know how, at least as of sbcl-0.6.7; in Linux we probably
1072 ;;; know how but the old code was broken by the conversion to POSIX
1073 ;;; signal handling and hasn't been fixed as of sbcl-0.6.7.)
1074 ;;;
1075 ;;; FIXME: Perhaps this should also be a base class for all
1076 ;;; floating point exceptions?
1077 (define-condition floating-point-exception (arithmetic-error)
1078   ((flags :initarg :traps
1079           :initform nil
1080           :reader floating-point-exception-traps))
1081   (:report (lambda (condition stream)
1082              (format stream
1083                      "An arithmetic error ~S was signalled.~%"
1084                      (type-of condition))
1085              (let ((traps (floating-point-exception-traps condition)))
1086                (if traps
1087                    (format stream
1088                            "Trapping conditions are: ~%~{ ~S~^~}~%"
1089                            traps)
1090                    (write-line
1091                     "No traps are enabled? How can this be?"
1092                     stream))))))
1093
1094 (define-condition invalid-array-index-error (type-error)
1095   ((array :initarg :array :reader invalid-array-index-error-array)
1096    (axis :initarg :axis :reader invalid-array-index-error-axis))
1097   (:report
1098    (lambda (condition stream)
1099      (let ((array (invalid-array-index-error-array condition)))
1100        (format stream "Index ~W out of bounds for ~@[axis ~W of ~]~S, ~
1101                        should be nonnegative and <~W."
1102                (type-error-datum condition)
1103                (when (> (array-rank array) 1)
1104                  (invalid-array-index-error-axis condition))
1105                (type-of array)
1106                ;; Extract the bound from (INTEGER 0 (BOUND))
1107                (caaddr (type-error-expected-type condition)))))))
1108
1109 (define-condition invalid-array-error (reference-condition type-error) ()
1110   (:report
1111    (lambda (condition stream)
1112      (let ((*print-array* nil))
1113        (format stream
1114                "~@<Displaced array originally of type ~S has been invalidated ~
1115                 due its displaced-to array ~S having become too small to hold ~
1116                 it: the displaced array's dimensions have all been set to zero ~
1117                 to trap accesses to it.~:@>"
1118                (type-error-expected-type condition)
1119                (array-displacement (type-error-datum condition))))))
1120   (:default-initargs
1121       :references
1122       (list '(:ansi-cl :function adjust-array))))
1123
1124 (define-condition index-too-large-error (type-error)
1125   ()
1126   (:report
1127    (lambda (condition stream)
1128      (format stream
1129              "The index ~S is too large."
1130              (type-error-datum condition)))))
1131
1132 (define-condition bounding-indices-bad-error (reference-condition type-error)
1133   ((object :reader bounding-indices-bad-object :initarg :object))
1134   (:report
1135    (lambda (condition stream)
1136      (let* ((datum (type-error-datum condition))
1137             (start (car datum))
1138             (end (cdr datum))
1139             (object (bounding-indices-bad-object condition)))
1140        (etypecase object
1141          (sequence
1142           (format stream
1143                   "The bounding indices ~S and ~S are bad ~
1144                    for a sequence of length ~S."
1145                   start end (length object)))
1146          (array
1147           ;; from WITH-ARRAY-DATA
1148           (format stream
1149                   "The START and END parameters ~S and ~S are ~
1150                    bad for an array of total size ~S."
1151                   start end (array-total-size object)))))))
1152   (:default-initargs
1153       :references
1154       (list '(:ansi-cl :glossary "bounding index designator")
1155             '(:ansi-cl :issue "SUBSEQ-OUT-OF-BOUNDS:IS-AN-ERROR"))))
1156
1157 (define-condition nil-array-accessed-error (reference-condition type-error)
1158   ()
1159   (:report (lambda (condition stream)
1160              (declare (ignore condition))
1161              (format stream
1162                      "An attempt to access an array of element-type ~
1163                       NIL was made.  Congratulations!")))
1164   (:default-initargs
1165       :references (list '(:ansi-cl :function sb!xc:upgraded-array-element-type)
1166                         '(:ansi-cl :section (15 1 2 1))
1167                         '(:ansi-cl :section (15 1 2 2)))))
1168
1169 (define-condition namestring-parse-error (parse-error)
1170   ((complaint :reader namestring-parse-error-complaint :initarg :complaint)
1171    (args :reader namestring-parse-error-args :initarg :args :initform nil)
1172    (namestring :reader namestring-parse-error-namestring :initarg :namestring)
1173    (offset :reader namestring-parse-error-offset :initarg :offset))
1174   (:report
1175    (lambda (condition stream)
1176      (format stream
1177              "parse error in namestring: ~?~%  ~A~%  ~V@T^"
1178              (namestring-parse-error-complaint condition)
1179              (namestring-parse-error-args condition)
1180              (namestring-parse-error-namestring condition)
1181              (namestring-parse-error-offset condition)))))
1182
1183 (define-condition simple-package-error (simple-condition package-error) ())
1184
1185 (define-condition simple-reader-package-error (simple-reader-error) ())
1186
1187 (define-condition reader-eof-error (end-of-file)
1188   ((context :reader reader-eof-error-context :initarg :context))
1189   (:report
1190    (lambda (condition stream)
1191      (format stream
1192              "unexpected end of file on ~S ~A"
1193              (stream-error-stream condition)
1194              (reader-eof-error-context condition)))))
1195
1196 (define-condition reader-impossible-number-error (simple-reader-error)
1197   ((error :reader reader-impossible-number-error-error :initarg :error))
1198   (:report
1199    (lambda (condition stream)
1200      (let ((error-stream (stream-error-stream condition)))
1201        (format stream
1202                "READER-ERROR ~@[at ~W ~]on ~S:~%~?~%Original error: ~A"
1203                (file-position-or-nil-for-error error-stream) error-stream
1204                (simple-condition-format-control condition)
1205                (simple-condition-format-arguments condition)
1206                (reader-impossible-number-error-error condition))))))
1207
1208 (define-condition standard-readtable-modified-error (reference-condition error)
1209   ((operation :initarg :operation :reader standard-readtable-modified-operation))
1210   (:report (lambda (condition stream)
1211              (format stream "~S would modify the standard readtable."
1212                      (standard-readtable-modified-operation condition))))
1213   (:default-initargs :references `((:ansi-cl :section (2 1 1 2))
1214                                    (:ansi-cl :glossary "standard readtable"))))
1215
1216 (define-condition standard-pprint-dispatch-table-modified-error
1217     (reference-condition error)
1218   ((operation :initarg :operation
1219               :reader standard-pprint-dispatch-table-modified-operation))
1220   (:report (lambda (condition stream)
1221              (format stream "~S would modify the standard pprint dispatch table."
1222                      (standard-pprint-dispatch-table-modified-operation
1223                       condition))))
1224   (:default-initargs
1225       :references `((:ansi-cl :glossary "standard pprint dispatch table"))))
1226
1227 (define-condition timeout (serious-condition)
1228   ((seconds :initarg :seconds :initform nil :reader timeout-seconds))
1229   (:report (lambda (condition stream)
1230              (format stream "Timeout occurred~@[ after ~A seconds~]."
1231                      (timeout-seconds condition)))))
1232
1233 (define-condition io-timeout (stream-error timeout)
1234   ((direction :reader io-timeout-direction :initarg :direction))
1235   (:report
1236    (lambda (condition stream)
1237      (declare (type stream stream))
1238      (format stream
1239              "I/O timeout ~(~A~)ing ~S."
1240              (io-timeout-direction condition)
1241              (stream-error-stream condition)))))
1242
1243 (define-condition deadline-timeout (timeout) ()
1244   (:report (lambda (condition stream)
1245              (format stream "A deadline was reached after ~A seconds."
1246                      (timeout-seconds condition)))))
1247
1248 (define-condition declaration-type-conflict-error (reference-condition
1249                                                    simple-error)
1250   ()
1251   (:default-initargs
1252       :format-control "symbol ~S cannot be both the name of a type and the name of a declaration"
1253     :references (list '(:ansi-cl :section (3 8 21)))))
1254
1255 ;;; Single stepping conditions
1256
1257 (define-condition step-condition ()
1258   ((form :initarg :form :reader step-condition-form))
1259
1260   #!+sb-doc
1261   (:documentation "Common base class of single-stepping conditions.
1262 STEP-CONDITION-FORM holds a string representation of the form being
1263 stepped."))
1264
1265 #!+sb-doc
1266 (setf (fdocumentation 'step-condition-form 'function)
1267       "Form associated with the STEP-CONDITION.")
1268
1269 (define-condition step-form-condition (step-condition)
1270   ((args :initarg :args :reader step-condition-args))
1271   (:report
1272    (lambda (condition stream)
1273      (let ((*print-circle* t)
1274            (*print-pretty* t)
1275            (*print-readably* nil))
1276        (format stream
1277                  "Evaluating call:~%~<  ~@;~A~:>~%~
1278                   ~:[With arguments:~%~{  ~S~%~}~;With unknown arguments~]~%"
1279                (list (step-condition-form condition))
1280                (eq (step-condition-args condition) :unknown)
1281                (step-condition-args condition)))))
1282   #!+sb-doc
1283   (:documentation "Condition signalled by code compiled with
1284 single-stepping information when about to execute a form.
1285 STEP-CONDITION-FORM holds the form, STEP-CONDITION-PATHNAME holds the
1286 pathname of the original file or NIL, and STEP-CONDITION-SOURCE-PATH
1287 holds the source-path to the original form within that file or NIL.
1288 Associated with this condition are always the restarts STEP-INTO,
1289 STEP-NEXT, and STEP-CONTINUE."))
1290
1291 (define-condition step-result-condition (step-condition)
1292   ((result :initarg :result :reader step-condition-result)))
1293
1294 #!+sb-doc
1295 (setf (fdocumentation 'step-condition-result 'function)
1296       "Return values associated with STEP-VALUES-CONDITION as a list,
1297 or the variable value associated with STEP-VARIABLE-CONDITION.")
1298
1299 (define-condition step-values-condition (step-result-condition)
1300   ()
1301   #!+sb-doc
1302   (:documentation "Condition signalled by code compiled with
1303 single-stepping information after executing a form.
1304 STEP-CONDITION-FORM holds the form, and STEP-CONDITION-RESULT holds
1305 the values returned by the form as a list. No associated restarts."))
1306
1307 (define-condition step-finished-condition (step-condition)
1308   ()
1309   (:report
1310    (lambda (condition stream)
1311      (declare (ignore condition))
1312      (format stream "Returning from STEP")))
1313   #!+sb-doc
1314   (:documentation "Condition signaled when STEP returns."))
1315 \f
1316 ;;; A knob for muffling warnings, mostly for use while loading files.
1317 (defvar *muffled-warnings* 'uninteresting-redefinition
1318   "A type that ought to specify a subtype of WARNING.  Whenever a
1319 warning is signaled, if the warning if of this type and is not
1320 handled by any other handler, it will be muffled.")
1321 \f
1322 ;;; Various STYLE-WARNING signaled in the system.
1323 ;; For the moment, we're only getting into the details for function
1324 ;; redefinitions, but other redefinitions could be done later
1325 ;; (e.g. methods).
1326 (define-condition redefinition-warning (style-warning)
1327   ())
1328
1329 (define-condition function-redefinition-warning (redefinition-warning)
1330   ((name :initarg :name :reader function-redefinition-warning-name)
1331    (old :initarg :old :reader function-redefinition-warning-old-fdefinition)
1332    ;; For DEFGENERIC and perhaps others, the redefinition
1333    ;; destructively modifies the original, rather than storing a new
1334    ;; object, so there's no NEW here, but only in subclasses.
1335    ))
1336
1337 (define-condition redefinition-with-defun (function-redefinition-warning)
1338   ((new :initarg :new :reader redefinition-with-defun-new-fdefinition)
1339    ;; KLUDGE: it would be nice to fix the unreasonably late
1340    ;; back-patching of DEBUG-SOURCEs in the DEBUG-INFO during
1341    ;; fasloading and just use the new fdefinition, but for the moment
1342    ;; we'll compare the SOURCE-LOCATION created during DEFUN with the
1343    ;; previous DEBUG-SOURCE.
1344    (new-location :initarg :new-location
1345               :reader redefinition-with-defun-new-location))
1346   (:report (lambda (warning stream)
1347              (format stream "redefining ~S in DEFUN"
1348                      (function-redefinition-warning-name warning)))))
1349
1350 (define-condition redefinition-with-defgeneric (function-redefinition-warning)
1351   ((new-location :initarg :new-location
1352                  :reader redefinition-with-defgeneric-new-location))
1353   (:report (lambda (warning stream)
1354              (format stream "redefining ~S in DEFGENERIC"
1355                      (function-redefinition-warning-name warning)))))
1356
1357 (define-condition redefinition-with-defmethod (redefinition-warning)
1358   ((gf :initarg :generic-function
1359        :reader redefinition-with-defmethod-generic-function)
1360    (qualifiers :initarg :qualifiers
1361                :reader redefinition-with-defmethod-qualifiers)
1362    (specializers :initarg :specializers
1363                  :reader redefinition-with-defmethod-specializers)
1364    (new-location :initarg :new-location
1365                  :reader redefinition-with-defmethod-new-location)
1366    (old-method :initarg :old-method
1367                :reader redefinition-with-defmethod-old-method))
1368   (:report (lambda (warning stream)
1369              (format stream "redefining ~S~{ ~S~} ~S in DEFMETHOD"
1370                      (redefinition-with-defmethod-generic-function warning)
1371                      (redefinition-with-defmethod-qualifiers warning)
1372                      (redefinition-with-defmethod-specializers warning)))))
1373
1374 ;; FIXME: see the FIXMEs in defmacro.lisp, then maybe instantiate this.
1375 (define-condition redefinition-with-defmacro (function-redefinition-warning)
1376   ())
1377
1378 ;; Here are a few predicates for what people might find interesting
1379 ;; about redefinitions.
1380
1381 ;; DEFUN can replace a generic function with an ordinary function.
1382 ;; (Attempting to replace an ordinary function with a generic one
1383 ;; causes an error, though.)
1384 (defun redefinition-replaces-generic-function-p (warning)
1385   (and (typep warning 'redefinition-with-defun)
1386        (typep (function-redefinition-warning-old-fdefinition warning)
1387               'generic-function)))
1388
1389 (defun redefinition-replaces-compiled-function-with-interpreted-p (warning)
1390   (and (typep warning 'redefinition-with-defun)
1391        (compiled-function-p
1392         (function-redefinition-warning-old-fdefinition warning))
1393        (not (compiled-function-p
1394              (redefinition-with-defun-new-fdefinition warning)))))
1395
1396 ;; Most people seem to agree that re-running a DEFUN in a file is
1397 ;; completely uninteresting.
1398 (defun uninteresting-ordinary-function-redefinition-p (warning)
1399   ;; OAOO violation: this duplicates code in SB-INTROSPECT.
1400   ;; Additionally, there are some functions that aren't
1401   ;; funcallable-instances for which finding the source location is
1402   ;; complicated (e.g. DEFSTRUCT-defined predicates and accessors),
1403   ;; but I don't think they're defined with %DEFUN, so the warning
1404   ;; isn't raised.
1405   (flet ((fdefinition-file-namestring (fdefn)
1406            #!+sb-eval
1407            (when (typep fdefn 'sb!eval:interpreted-function)
1408              (return-from fdefinition-file-namestring
1409                (sb!c:definition-source-location-namestring
1410                    (sb!eval:interpreted-function-source-location fdefn))))
1411            ;; All the following accesses are guarded with conditionals
1412            ;; because it's not clear whether any of the slots we're
1413            ;; chasing down are guaranteed to be filled in.
1414            (let* ((fdefn
1415                    ;; KLUDGE: although this looks like it only works
1416                    ;; for %SIMPLE-FUNs, in fact there's a pun such
1417                    ;; that %SIMPLE-FUN-SELF returns the simple-fun
1418                    ;; object for closures and
1419                    ;; funcallable-instances. -- CSR, circa 2005
1420                    (sb!kernel:%simple-fun-self fdefn))
1421                   (code (if fdefn (sb!kernel:fun-code-header fdefn)))
1422                   (debug-info (if code (sb!kernel:%code-debug-info code)))
1423                   (debug-source (if debug-info
1424                                     (sb!c::debug-info-source debug-info)))
1425                   (namestring (if debug-source
1426                                   (sb!c::debug-source-namestring debug-source))))
1427              namestring)))
1428     (and
1429      ;; There's garbage in various places when the first DEFUN runs in
1430      ;; cold-init.
1431      sb!kernel::*cold-init-complete-p*
1432      (typep warning 'redefinition-with-defun)
1433      (let ((old-fdefn
1434             (function-redefinition-warning-old-fdefinition warning))
1435            (new-fdefn
1436             (redefinition-with-defun-new-fdefinition warning)))
1437        ;; Replacing a compiled function with a compiled function is
1438        ;; clearly uninteresting, and we'll say arbitrarily that
1439        ;; replacing an interpreted function with an interpreted
1440        ;; function is uninteresting, too, but leave out the
1441        ;; compiled-to-interpreted case.
1442        (when (or (typep
1443                   old-fdefn
1444                   '(or #!+sb-eval sb!eval:interpreted-function))
1445                  (and (typep old-fdefn
1446                              '(and compiled-function
1447                                (not funcallable-instance)))
1448                       ;; Since this is a REDEFINITION-WITH-DEFUN,
1449                       ;; NEW-FDEFN can't be a FUNCALLABLE-INSTANCE.
1450                       (typep new-fdefn 'compiled-function)))
1451          (let* ((old-namestring (fdefinition-file-namestring old-fdefn))
1452                 (new-namestring
1453                  (or (fdefinition-file-namestring new-fdefn)
1454                      (let ((srcloc
1455                             (redefinition-with-defun-new-location warning)))
1456                        (if srcloc
1457                             (sb!c::definition-source-location-namestring
1458                                 srcloc))))))
1459            (and old-namestring
1460                 new-namestring
1461                 (equal old-namestring new-namestring))))))))
1462
1463 (defun uninteresting-generic-function-redefinition-p (warning)
1464   (and (typep warning 'redefinition-with-defgeneric)
1465        (let* ((old-fdefn
1466                (function-redefinition-warning-old-fdefinition warning))
1467               (old-location
1468                (if (typep old-fdefn 'generic-function)
1469                    (sb!pcl::definition-source old-fdefn)))
1470               (old-namestring
1471                (if old-location
1472                    (sb!c:definition-source-location-namestring old-location)))
1473               (new-location
1474                (redefinition-with-defgeneric-new-location warning))
1475               (new-namestring
1476                (if new-location
1477                    (sb!c:definition-source-location-namestring new-location))))
1478          (and old-namestring
1479               new-namestring
1480               (equal old-namestring new-namestring)))))
1481
1482 (defun uninteresting-method-redefinition-p (warning)
1483   (and (typep warning 'redefinition-with-defmethod)
1484        (let* ((old-method (redefinition-with-defmethod-old-method warning))
1485               (old-location (sb!pcl::definition-source old-method))
1486               (old-namestring (if old-location
1487                                   (sb!c:definition-source-location-namestring
1488                                       old-location)))
1489               (new-location (redefinition-with-defmethod-new-location warning))
1490               (new-namestring (if new-location
1491                                   (sb!c:definition-source-location-namestring
1492                                       new-location))))
1493          (and new-namestring
1494               old-namestring
1495               (equal new-namestring old-namestring)))))
1496
1497 (deftype uninteresting-redefinition ()
1498   '(or (satisfies uninteresting-ordinary-function-redefinition-p)
1499        (satisfies uninteresting-generic-function-redefinition-p)
1500        (satisfies uninteresting-method-redefinition-p)))
1501
1502 (define-condition redefinition-with-deftransform (redefinition-warning)
1503   ((transform :initarg :transform
1504               :reader redefinition-with-deftransform-transform))
1505   (:report (lambda (warning stream)
1506              (format stream "Overwriting ~S"
1507                      (redefinition-with-deftransform-transform warning)))))
1508 \f
1509 ;;; Various other STYLE-WARNINGS
1510 (define-condition dubious-asterisks-around-variable-name
1511     (style-warning simple-condition)
1512   ()
1513   (:report (lambda (warning stream)
1514              (format stream "~@?, even though the name follows~@
1515 the usual naming convention (names like *FOO*) for special variables"
1516                      (simple-condition-format-control warning)
1517                      (simple-condition-format-arguments warning)))))
1518
1519 (define-condition asterisks-around-lexical-variable-name
1520     (dubious-asterisks-around-variable-name)
1521   ())
1522
1523 (define-condition asterisks-around-constant-variable-name
1524     (dubious-asterisks-around-variable-name)
1525   ())
1526
1527 ;; We call this UNDEFINED-ALIEN-STYLE-WARNING because there are some
1528 ;; subclasses of ERROR above having to do with undefined aliens.
1529 (define-condition undefined-alien-style-warning (style-warning)
1530   ((symbol :initarg :symbol :reader undefined-alien-symbol))
1531   (:report (lambda (warning stream)
1532              (format stream "Undefined alien: ~S"
1533                      (undefined-alien-symbol warning)))))
1534
1535 #!+sb-eval
1536 (define-condition lexical-environment-too-complex (style-warning)
1537   ((form :initarg :form :reader lexical-environment-too-complex-form)
1538    (lexenv :initarg :lexenv :reader lexical-environment-too-complex-lexenv))
1539   (:report (lambda (warning stream)
1540              (format stream
1541                      "~@<Native lexical environment too complex for ~
1542                          SB-EVAL to evaluate ~S, falling back to ~
1543                          SIMPLE-EVAL-IN-LEXENV.  Lexenv: ~S~:@>"
1544                      (lexical-environment-too-complex-form warning)
1545                      (lexical-environment-too-complex-lexenv warning)))))
1546
1547 ;; Although this has -ERROR- in the name, it's just a STYLE-WARNING.
1548 (define-condition character-decoding-error-in-comment (style-warning)
1549   ((stream :initarg :stream :reader decoding-error-in-comment-stream)
1550    (position :initarg :position :reader decoding-error-in-comment-position))
1551   (:report (lambda (warning stream)
1552              (format stream
1553                       "Character decoding error in a ~A-comment at ~
1554                       position ~A reading source stream ~A, ~
1555                       resyncing."
1556                       (decoding-error-in-comment-macro warning)
1557                       (decoding-error-in-comment-position warning)
1558                       (decoding-error-in-comment-stream warning)))))
1559
1560 (define-condition character-decoding-error-in-macro-char-comment
1561     (character-decoding-error-in-comment)
1562   ((char :initform #\; :initarg :char
1563          :reader character-decoding-error-in-macro-char-comment-char)))
1564
1565 (define-condition character-decoding-error-in-dispatch-macro-char-comment
1566     (character-decoding-error-in-comment)
1567   ;; ANSI doesn't give a way for a reader function invoked by a
1568   ;; dispatch macro character to determine which dispatch character
1569   ;; was used, so if a user wants to signal one of these from a custom
1570   ;; comment reader, he'll have to supply the :DISP-CHAR himself.
1571   ((disp-char :initform #\# :initarg :disp-char
1572               :reader character-decoding-error-in-macro-char-comment-disp-char)
1573    (sub-char :initarg :sub-char
1574              :reader character-decoding-error-in-macro-char-comment-sub-char)))
1575
1576 (defun decoding-error-in-comment-macro (warning)
1577   (etypecase warning
1578     (character-decoding-error-in-macro-char-comment
1579      (character-decoding-error-in-macro-char-comment-char warning))
1580     (character-decoding-error-in-dispatch-macro-char-comment
1581      (format
1582       nil "~C~C"
1583       (character-decoding-error-in-macro-char-comment-disp-char warning)
1584       (character-decoding-error-in-macro-char-comment-sub-char warning)))))
1585
1586 (define-condition deprecated-eval-when-situations (style-warning)
1587   ((situations :initarg :situations
1588                :reader deprecated-eval-when-situations-situations))
1589   (:report (lambda (warning stream)
1590              (format stream "using deprecated EVAL-WHEN situation names~{ ~S~}"
1591                      (deprecated-eval-when-situations-situations warning)))))
1592
1593 (define-condition proclamation-mismatch (style-warning)
1594   ((name :initarg :name :reader proclamation-mismatch-name)
1595    (old :initarg :old :reader proclamation-mismatch-old)
1596    (new :initarg :new :reader proclamation-mismatch-new)))
1597
1598 (define-condition type-proclamation-mismatch (proclamation-mismatch)
1599   ()
1600   (:report (lambda (warning stream)
1601              (format stream
1602                      "The new TYPE proclamation~% ~S for ~S does not ~
1603                      match the old TYPE proclamation ~S"
1604                      (proclamation-mismatch-new warning)
1605                      (proclamation-mismatch-name warning)
1606                      (proclamation-mismatch-old warning)))))
1607
1608 (define-condition ftype-proclamation-mismatch (proclamation-mismatch)
1609   ()
1610   (:report (lambda (warning stream)
1611              (format stream
1612                      "The new FTYPE proclamation~% ~S for ~S does not ~
1613                      match the old FTYPE proclamation ~S"
1614                      (proclamation-mismatch-new warning)
1615                      (proclamation-mismatch-name warning)
1616                      (proclamation-mismatch-old warning)))))
1617 \f
1618 ;;;; restart definitions
1619
1620 (define-condition abort-failure (control-error) ()
1621   (:report
1622    "An ABORT restart was found that failed to transfer control dynamically."))
1623
1624 (defun abort (&optional condition)
1625   #!+sb-doc
1626   "Transfer control to a restart named ABORT, signalling a CONTROL-ERROR if
1627    none exists."
1628   (invoke-restart (find-restart-or-control-error 'abort condition))
1629   ;; ABORT signals an error in case there was a restart named ABORT
1630   ;; that did not transfer control dynamically. This could happen with
1631   ;; RESTART-BIND.
1632   (error 'abort-failure))
1633
1634 (defun muffle-warning (&optional condition)
1635   #!+sb-doc
1636   "Transfer control to a restart named MUFFLE-WARNING, signalling a
1637    CONTROL-ERROR if none exists."
1638   (invoke-restart (find-restart-or-control-error 'muffle-warning condition)))
1639
1640 (defun try-restart (name condition &rest arguments)
1641   (let ((restart (find-restart name condition)))
1642     (when restart
1643       (apply #'invoke-restart restart arguments))))
1644
1645 (macrolet ((define-nil-returning-restart (name args doc)
1646              #!-sb-doc (declare (ignore doc))
1647              `(defun ,name (,@args &optional condition)
1648                 #!+sb-doc ,doc
1649                 (try-restart ',name condition ,@args))))
1650   (define-nil-returning-restart continue ()
1651     "Transfer control to a restart named CONTINUE, or return NIL if none exists.")
1652   (define-nil-returning-restart store-value (value)
1653     "Transfer control and VALUE to a restart named STORE-VALUE, or return NIL if
1654    none exists.")
1655   (define-nil-returning-restart use-value (value)
1656     "Transfer control and VALUE to a restart named USE-VALUE, or return NIL if
1657    none exists."))
1658
1659 ;;; single-stepping restarts
1660
1661 (macrolet ((def (name doc)
1662                #!-sb-doc (declare (ignore doc))
1663                `(defun ,name (condition)
1664                  #!+sb-doc ,doc
1665                  (invoke-restart (find-restart-or-control-error ',name condition)))))
1666   (def step-continue
1667       "Transfers control to the STEP-CONTINUE restart associated with
1668 the condition, continuing execution without stepping. Signals a
1669 CONTROL-ERROR if the restart does not exist.")
1670   (def step-next
1671       "Transfers control to the STEP-NEXT restart associated with the
1672 condition, executing the current form without stepping and continuing
1673 stepping with the next form. Signals CONTROL-ERROR is the restart does
1674 not exists.")
1675   (def step-into
1676       "Transfers control to the STEP-INTO restart associated with the
1677 condition, stepping into the current form. Signals a CONTROL-ERROR is
1678 the restart does not exist."))
1679
1680 (/show0 "condition.lisp end of file")
1681