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