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