d8d529c283ea96d41d4e7aa1bb4468816adf90f7
[sbcl.git] / src / compiler / ir1report.lisp
1 ;;;; machinery for reporting errors/warnings/notes/whatnot from
2 ;;;; the compiler
3
4 ;;;; This software is part of the SBCL system. See the README file for
5 ;;;; more information.
6 ;;;;
7 ;;;; This software is derived from the CMU CL system, which was
8 ;;;; written at Carnegie Mellon University and released into the
9 ;;;; public domain. The software is in the public domain and is
10 ;;;; provided with absolutely no warranty. See the COPYING and CREDITS
11 ;;;; files for more information.
12
13 (in-package "SB!C")
14 \f
15 ;;;; compiler error context determination
16
17 (declaim (special *current-path*))
18
19 (defvar *enclosing-source-cutoff* 1
20   #!+sb-doc
21   "The maximum number of enclosing non-original source forms (i.e. from
22   macroexpansion) that we print in full. For additional enclosing forms, we
23   print only the CAR.")
24 (declaim (type unsigned-byte *enclosing-source-cutoff*))
25
26 ;;; We separate the determination of compiler error contexts from the
27 ;;; actual signalling of those errors by objectifying the error
28 ;;; context. This allows postponement of the determination of how (and
29 ;;; if) to signal the error.
30 ;;;
31 ;;; We take care not to reference any of the IR1 so that pending
32 ;;; potential error messages won't prevent the IR1 from being GC'd. To
33 ;;; this end, we convert source forms to strings so that source forms
34 ;;; that contain IR1 references (e.g. %DEFUN) don't hold onto the IR.
35 (defstruct (compiler-error-context
36             #-no-ansi-print-object
37             (:print-object (lambda (x stream)
38                              (print-unreadable-object (x stream :type t))))
39             (:copier nil))
40   ;; a list of the stringified CARs of the enclosing non-original source forms
41   ;; exceeding the *enclosing-source-cutoff*
42   (enclosing-source nil :type list)
43   ;; a list of stringified enclosing non-original source forms
44   (source nil :type list)
45   ;; the stringified form in the original source that expanded into SOURCE
46   (original-source (missing-arg) :type simple-string)
47   ;; a list of prefixes of "interesting" forms that enclose original-source
48   (context nil :type list)
49   ;; the FILE-INFO-NAME for the relevant FILE-INFO
50   (file-name (missing-arg) :type (or pathname (member :lisp :stream)))
51   ;; the file position at which the top level form starts, if applicable
52   (file-position nil :type (or index null))
53   ;; the original source part of the source path
54   (original-source-path nil :type list)
55   ;; the lexenv active at the time
56   (lexenv nil :type (or null lexenv)))
57
58 ;;; If true, this is the node which is used as context in compiler warning
59 ;;; messages.
60 (declaim (type (or null compiler-error-context node) *compiler-error-context*))
61 (defvar *compiler-error-context* nil)
62
63 ;;; a hashtable mapping macro names to source context parsers. Each parser
64 ;;; function returns the source-context list for that form.
65 (defvar *source-context-methods* (make-hash-table))
66
67 ;;; documentation originally from cmu-user.tex:
68 ;;;   This macro defines how to extract an abbreviated source context from
69 ;;;   the \var{name}d form when it appears in the compiler input.
70 ;;;   \var{lambda-list} is a \code{defmacro} style lambda-list used to
71 ;;;   parse the arguments. The \var{body} should return a list of
72 ;;;   subforms that can be printed on about one line. There are
73 ;;;   predefined methods for \code{defstruct}, \code{defmethod}, etc. If
74 ;;;   no method is defined, then the first two subforms are returned.
75 ;;;   Note that this facility implicitly determines the string name
76 ;;;   associated with anonymous functions.
77 ;;; So even though SBCL itself only uses this macro within this file,
78 ;;; it's a reasonable thing to put in SB-EXT in case some dedicated
79 ;;; user wants to do some heavy tweaking to make SBCL give more
80 ;;; informative output about his code.
81 (defmacro define-source-context (name lambda-list &body body)
82   #!+sb-doc
83   "DEFINE-SOURCE-CONTEXT Name Lambda-List Form*
84    This macro defines how to extract an abbreviated source context from the
85    Named form when it appears in the compiler input. Lambda-List is a DEFMACRO
86    style lambda-list used to parse the arguments. The Body should return a
87    list of subforms suitable for a \"~{~S ~}\" format string."
88   (let ((n-whole (gensym)))
89     `(setf (gethash ',name *source-context-methods*)
90            (lambda (,n-whole)
91              (destructuring-bind ,lambda-list ,n-whole ,@body)))))
92
93 (defmacro def-source-context (&rest rest)
94   (deprecation-warning 'def-source-context 'define-source-context)
95   `(define-source-context ,@rest))
96
97 (define-source-context defstruct (name-or-options &rest slots)
98   (declare (ignore slots))
99   `(defstruct ,(if (consp name-or-options)
100                    (car name-or-options)
101                    name-or-options)))
102
103 (define-source-context function (thing)
104   (if (and (consp thing) (eq (first thing) 'lambda) (consp (rest thing)))
105       `(lambda ,(second thing))
106       `(function ,thing)))
107
108 ;;; Return the first two elements of FORM if FORM is a list. Take the
109 ;;; CAR of the second form if appropriate.
110 (defun source-form-context (form)
111   (cond ((atom form) nil)
112         ((>= (length form) 2)
113          (let* ((context-fun-default (lambda (x)
114                                        (declare (ignore x))
115                                        (list (first form) (second form))))
116                 (context-fun (gethash (first form)
117                                       *source-context-methods*
118                                       context-fun-default)))
119            (declare (type function context-fun))
120            (funcall context-fun (rest form))))
121         (t
122          form)))
123
124 ;;; Given a source path, return the original source form and a
125 ;;; description of the interesting aspects of the context in which it
126 ;;; appeared. The context is a list of lists, one sublist per context
127 ;;; form. The sublist is a list of some of the initial subforms of the
128 ;;; context form.
129 ;;;
130 ;;; For now, we use the first two subforms of each interesting form. A
131 ;;; form is interesting if the first element is a symbol beginning
132 ;;; with "DEF" and it is not the source form. If there is no
133 ;;; DEF-mumble, then we use the outermost containing form. If the
134 ;;; second subform is a list, then in some cases we return the CAR of
135 ;;; that form rather than the whole form (i.e. don't show DEFSTRUCT
136 ;;; options, etc.)
137 (defun find-original-source (path)
138   (declare (list path))
139   (let* ((rpath (reverse (source-path-original-source path)))
140          (tlf (first rpath))
141          (root (find-source-root tlf *source-info*)))
142     (collect ((context))
143       (let ((form root)
144             (current (rest rpath)))
145         (loop
146           (when (atom form)
147             (aver (null current))
148             (return))
149           (let ((head (first form)))
150             (when (symbolp head)
151               (let ((name (symbol-name head)))
152                 (when (and (>= (length name) 3) (string= name "DEF" :end1 3))
153                   (context (source-form-context form))))))
154           (when (null current) (return))
155           (setq form (nth (pop current) form)))
156         
157         (cond ((context)
158                (values form (context)))
159               ((and path root)
160                (let ((c (source-form-context root)))
161                  (values form (if c (list c) nil))))
162               (t
163                (values '(unable to locate source)
164                        '((some strange place)))))))))
165
166 ;;; Convert a source form to a string, suitably formatted for use in
167 ;;; compiler warnings.
168 (defun stringify-form (form &optional (pretty t))
169   (with-standard-io-syntax
170     (with-compiler-io-syntax
171         (let ((*print-pretty* pretty))
172           (if pretty
173               (format nil "~<~@;  ~S~:>" (list form))
174               (prin1-to-string form))))))
175
176 ;;; Return a COMPILER-ERROR-CONTEXT structure describing the current
177 ;;; error context, or NIL if we can't figure anything out. ARGS is a
178 ;;; list of things that are going to be printed out in the error
179 ;;; message, and can thus be blown off when they appear in the source
180 ;;; context.
181 (defun find-error-context (args)
182   (let ((context *compiler-error-context*))
183     (if (compiler-error-context-p context)
184         context
185         (let ((path (or (and (boundp '*current-path*) *current-path*)
186                         (if context
187                             (node-source-path context)
188                             nil))))
189           (when (and *source-info* path)
190             (multiple-value-bind (form src-context) (find-original-source path)
191               (collect ((full nil cons)
192                         (short nil cons))
193                 (let ((forms (source-path-forms path))
194                       (n 0))
195                   (dolist (src (if (member (first forms) args)
196                                    (rest forms)
197                                    forms))
198                     (if (>= n *enclosing-source-cutoff*)
199                         (short (stringify-form (if (consp src)
200                                                    (car src)
201                                                    src)
202                                                nil))
203                         (full (stringify-form src)))
204                     (incf n)))
205
206                 (let* ((tlf (source-path-tlf-number path))
207                        (file-info (source-info-file-info *source-info*)))
208                   (make-compiler-error-context
209                    :enclosing-source (short)
210                    :source (full)
211                    :original-source (stringify-form form)
212                    :context src-context
213                    :file-name (file-info-name file-info)
214                    :file-position
215                    (multiple-value-bind (ignore pos)
216                        (find-source-root tlf *source-info*)
217                      (declare (ignore ignore))
218                      pos)
219                    :original-source-path
220                    (source-path-original-source path)
221                    :lexenv (if context
222                                (node-lexenv context)
223                                (if (boundp '*lexenv*) *lexenv* nil)))))))))))
224 \f
225 ;;;; printing error messages
226
227 ;;; We save the context information that we printed out most recently
228 ;;; so that we don't print it out redundantly.
229
230 ;;; The last COMPILER-ERROR-CONTEXT that we printed.
231 (defvar *last-error-context* nil)
232 (declaim (type (or compiler-error-context null) *last-error-context*))
233
234 ;;; The format string and args for the last error we printed.
235 (defvar *last-format-string* nil)
236 (defvar *last-format-args* nil)
237 (declaim (type (or string null) *last-format-string*))
238 (declaim (type list *last-format-args*))
239
240 ;;; The number of times that the last error message has been emitted,
241 ;;; so that we can compress duplicate error messages.
242 (defvar *last-message-count* 0)
243 (declaim (type index *last-message-count*))
244
245 ;;; If the last message was given more than once, then print out an
246 ;;; indication of how many times it was repeated. We reset the message
247 ;;; count when we are done.
248 (defun note-message-repeats (&optional (terpri t))
249   (cond ((= *last-message-count* 1)
250          (when terpri (terpri *error-output*)))
251         ((> *last-message-count* 1)
252           (format *error-output* "~&; [Last message occurs ~W times.]~2%"
253                  *last-message-count*)))
254   (setq *last-message-count* 0))
255
256 ;;; Print out the message, with appropriate context if we can find it.
257 ;;; If the context is different from the context of the last message
258 ;;; we printed, then we print the context. If the original source is
259 ;;; different from the source we are working on, then we print the
260 ;;; current source in addition to the original source.
261 ;;;
262 ;;; We suppress printing of messages identical to the previous, but
263 ;;; record the number of times that the message is repeated.
264 (defmacro print-compiler-message (format-string format-args)
265   `(with-compiler-io-syntax
266      (%print-compiler-message ,format-string ,format-args)))
267
268 (defun %print-compiler-message (format-string format-args)
269   (declare (type simple-string format-string))
270   (declare (type list format-args))  
271   (let ((stream *error-output*)
272         (context (find-error-context format-args)))
273     (cond
274      (context
275       (let ((file (compiler-error-context-file-name context))
276             (in (compiler-error-context-context context))
277             (form (compiler-error-context-original-source context))
278             (enclosing (compiler-error-context-enclosing-source context))
279             (source (compiler-error-context-source context))
280             (last *last-error-context*))
281
282         (unless (and last
283                      (equal file (compiler-error-context-file-name last)))
284           (when (pathnamep file)
285             (note-message-repeats)
286             (setq last nil)
287             (format stream "~2&; file: ~A~%" (namestring file))))
288
289         (unless (and last
290                      (equal in (compiler-error-context-context last)))
291           (note-message-repeats)
292           (setq last nil)
293           (format stream "~&")
294           (pprint-logical-block (stream nil :per-line-prefix "; ")
295             (format stream "in:~{~<~%    ~4:;~{ ~S~}~>~^ =>~}" in))
296           (format stream "~%"))
297
298
299         (unless (and last
300                      (string= form
301                               (compiler-error-context-original-source last)))
302           (note-message-repeats)
303           (setq last nil)
304           (format stream "~&")
305           (pprint-logical-block (stream nil :per-line-prefix "; ")
306             (format stream "  ~A" form))
307           (format stream "~&"))
308
309         (unless (and last
310                      (equal enclosing
311                             (compiler-error-context-enclosing-source last)))
312           (when enclosing
313             (note-message-repeats)
314             (setq last nil)
315             (format stream "~&; --> ~{~<~%; --> ~1:;~A~> ~}~%" enclosing)))
316
317         (unless (and last
318                      (equal source (compiler-error-context-source last)))
319           (setq *last-format-string* nil)
320           (when source
321             (note-message-repeats)
322             (dolist (src source)
323               (format stream "~&")
324               (write-string "; ==>" stream)
325               (format stream "~&")
326               (pprint-logical-block (stream nil :per-line-prefix "; ")
327                 (write-string src stream)))))))
328      (t
329        (format stream "~&")
330       (note-message-repeats)
331       (setq *last-format-string* nil)
332        (format stream "~&")))
333
334     (setq *last-error-context* context)
335
336     ;; FIXME: this testing for effective equality of compiler messages
337     ;; is ugly, and really ought to be done at a higher level.
338     (unless (and (equal format-string *last-format-string*)
339                  (tree-equal format-args *last-format-args*))
340       (note-message-repeats nil)
341       (setq *last-format-string* format-string)
342       (setq *last-format-args* format-args)
343       (format stream "~&")
344       (pprint-logical-block (stream nil :per-line-prefix "; ")
345         (format stream "~&~?" format-string format-args))
346       (format stream "~&")))
347   
348   (incf *last-message-count*)
349   (values))
350
351 (defun print-compiler-condition (condition)
352   (declare (type condition condition))
353   (let (;; These different classes of conditions have different
354         ;; effects on the return codes of COMPILE-FILE, so it's nice
355         ;; for users to be able to pick them out by lexical search
356         ;; through the output.
357         (what (etypecase condition
358                 (style-warning 'style-warning)
359                 (warning 'warning)
360                 ((or error compiler-error) 'error))))
361     (print-compiler-message
362      (format nil "caught ~S:~%~~@<  ~~@;~~A~~:>" what)
363      (list (with-output-to-string (s) (princ condition s)))))
364   (values))
365
366 ;;; The act of signalling one of these beasts must not cause WARNINGSP
367 ;;; (or FAILUREP) to be set from COMPILE or COMPILE-FILE, so we can't
368 ;;; inherit from WARNING or STYLE-WARNING.
369 ;;;
370 ;;; FIXME: the handling of compiler-notes could be unified with
371 ;;; warnings and style-warnings (see the various handler functions
372 ;;; below).
373 (define-condition compiler-note (condition) ()
374   (:documentation
375    "Root of the hierarchy of conditions representing information discovered
376 by the compiler that the user might wish to know, but which does not merit
377 a STYLE-WARNING (or any more serious condition)."))
378 (define-condition simple-compiler-note (simple-condition compiler-note) ())
379 (define-condition code-deletion-note (simple-compiler-note) ()
380   (:documentation
381    "A condition type signalled when the compiler deletes code that the user
382 has written, having proved that it is unreachable."))
383
384 (defun compiler-notify (datum &rest args)
385   (unless (if *compiler-error-context*
386               (policy *compiler-error-context* (= inhibit-warnings 3))
387               (policy *lexenv* (= inhibit-warnings 3)))
388     (let ((condition
389            (coerce-to-condition datum args
390                                 'simple-compiler-note 'compiler-notify)))
391       (restart-case
392           (signal condition)
393         (muffle-warning ()
394           (return-from compiler-notify (values))))
395       (incf *compiler-note-count*)
396       (print-compiler-message 
397        (format nil "note: ~~A")
398        (list (with-output-to-string (s) (princ condition s))))))
399   (values))
400
401 ;;; Issue a note when we might or might not be in the compiler.
402 (defun maybe-compiler-notify (&rest rest)
403   (if (boundp '*lexenv*) ; if we're in the compiler
404       (apply #'compiler-notify rest)
405       (progn
406         (let ((condition
407                (coerce-to-condition (car rest) (cdr rest)
408                                     'simple-compiler-note
409                                     'maybe-compiler-notify)))
410           (restart-case
411               (signal condition)
412             (muffle-warning ()
413               (return-from maybe-compiler-notify (values))))
414           (let ((stream *error-output*))
415             (pprint-logical-block (stream nil :per-line-prefix ";")
416               (format stream " note: ~3I~_")
417               (pprint-logical-block (stream nil)
418                 (format stream "~A" condition)))
419             ;; (outside logical block, no per-line-prefix)
420             (fresh-line stream)))
421         (values))))
422
423 ;;; The politically correct way to print out progress messages and
424 ;;; such like. We clear the current error context so that we know that
425 ;;; it needs to be reprinted, and we also FORCE-OUTPUT so that the
426 ;;; message gets seen right away.
427 (declaim (ftype (function (string &rest t) (values)) compiler-mumble))
428 (defun compiler-mumble (format-string &rest format-args)
429   (note-message-repeats)
430   (setq *last-error-context* nil)
431   (apply #'format *error-output* format-string format-args)
432   (force-output *error-output*)
433   (values))
434
435 ;;; Return a string that somehow names the code in COMPONENT. We use
436 ;;; the source path for the bind node for an arbitrary entry point to
437 ;;; find the source context, then return that as a string.
438 (declaim (ftype (function (component) simple-string) find-component-name))
439 (defun find-component-name (component)
440   (let ((ep (first (block-succ (component-head component)))))
441     (aver ep) ; else no entry points??
442     (multiple-value-bind (form context)
443         (find-original-source
444          (node-source-path (block-start-node ep)))
445       (declare (ignore form))
446       (let ((*print-level* 2)
447             (*print-pretty* nil))
448         (format nil "~{~{~S~^ ~}~^ => ~}" context)))))
449 \f
450 ;;;; condition system interface
451
452 ;;; Keep track of how many times each kind of condition happens.
453 (defvar *compiler-error-count*)
454 (defvar *compiler-warning-count*)
455 (defvar *compiler-style-warning-count*)
456 (defvar *compiler-note-count*)
457
458 ;;; Keep track of whether any surrounding COMPILE or COMPILE-FILE call
459 ;;; should return WARNINGS-P or FAILURE-P.
460 (defvar *failure-p*)
461 (defvar *warnings-p*)
462
463 ;;; condition handlers established by the compiler. We re-signal the
464 ;;; condition, then if it isn't handled, we increment our warning
465 ;;; counter and print the error message.
466 (defun compiler-error-handler (condition)
467   (signal condition)
468   (incf *compiler-error-count*)
469   (setf *warnings-p* t
470         *failure-p* t)
471   (print-compiler-condition condition)
472   (continue condition))
473 (defun compiler-warning-handler (condition)
474   (signal condition)
475   (incf *compiler-warning-count*)
476   (setf *warnings-p* t
477         *failure-p* t)
478   (print-compiler-condition condition)
479   (muffle-warning condition))
480 (defun compiler-style-warning-handler (condition)
481   (signal condition)
482   (incf *compiler-style-warning-count*)
483   (setf *warnings-p* t)
484   (print-compiler-condition condition)
485   (muffle-warning condition))
486 \f
487 ;;;; undefined warnings
488
489 (defvar *undefined-warning-limit* 3
490   #!+sb-doc
491   "If non-null, then an upper limit on the number of unknown function or type
492   warnings that the compiler will print for any given name in a single
493   compilation. This prevents excessive amounts of output when the real
494   problem is a missing definition (as opposed to a typo in the use.)")
495
496 ;;; Make an entry in the *UNDEFINED-WARNINGS* describing a reference
497 ;;; to NAME of the specified KIND. If we have exceeded the warning
498 ;;; limit, then just increment the count, otherwise note the current
499 ;;; error context.
500 ;;;
501 ;;; Undefined types are noted by a condition handler in
502 ;;; WITH-COMPILATION-UNIT, which can potentially be invoked outside
503 ;;; the compiler, hence the BOUNDP check.
504 (defun note-undefined-reference (name kind)
505   (unless (and
506            ;; Check for boundness so we don't blow up if we're called
507            ;; when IR1 conversion isn't going on.
508            (boundp '*lexenv*)
509            (or
510             ;; FIXME: I'm pretty sure the INHIBIT-WARNINGS test below
511             ;; isn't a good idea; we should have INHIBIT-WARNINGS
512             ;; affect compiler notes, not STYLE-WARNINGs. And I'm not
513             ;; sure what the BOUNDP '*LEXENV* test above is for; it's
514             ;; likely a good idea, but it probably deserves an
515             ;; explanatory comment.
516             (policy *lexenv* (= inhibit-warnings 3))
517             ;; KLUDGE: weird decoupling between here and where we're
518             ;; going to signal the condition.  I don't think we can
519             ;; rewrite this using SIGNAL and RESTART-CASE (to take
520             ;; advantage of the (SATISFIES HANDLE-CONDITION-P)
521             ;; handler, because if that doesn't handle it the ordinary
522             ;; compiler handlers will trigger.
523             (typep
524              (ecase kind
525                (:variable (make-condition 'warning))
526                ((:function :type) (make-condition 'style-warning)))
527              (car
528               (rassoc 'muffle-warning
529                       (lexenv-handled-conditions *lexenv*))))))
530     (let* ((found (dolist (warning *undefined-warnings* nil)
531                     (when (and (equal (undefined-warning-name warning) name)
532                                (eq (undefined-warning-kind warning) kind))
533                       (return warning))))
534            (res (or found
535                     (make-undefined-warning :name name :kind kind))))
536       (unless found (push res *undefined-warnings*))
537       (when (or (not *undefined-warning-limit*)
538                 (< (undefined-warning-count res) *undefined-warning-limit*))
539         (push (find-error-context (list name))
540               (undefined-warning-warnings res)))
541       (incf (undefined-warning-count res))))
542   (values))