1.0.13.11: ensure that sb-cover records don't clash with constants in user code
[sbcl.git] / contrib / sb-cover / cover.lisp
1 ;;; A frontend for the SBCL code coverage facility. Written by Juho
2 ;;; Snellman, and placed under public domain.
3
4 ;;; This module includes a modified version of the source path parsing
5 ;;; routines from Swank. That code was written by Helmut Eller, and
6 ;;; was placed under Public Domain
7
8 (defpackage #:sb-cover
9   (:use #:cl #:sb-c)
10   (:export #:report
11            #:reset-coverage #:clear-coverage
12            #:restore-coverage #:restore-coverage-from-file
13            #:save-coverage #:save-coverage-in-file
14            #:store-coverage-data))
15
16 (in-package #:sb-cover)
17
18 (declaim (type (member :whole :car) *source-path-mode*))
19 (defvar *source-path-mode* :whole)
20
21 (defclass sample-count ()
22   ((mode :accessor mode-of :initarg :mode)
23    (all :accessor all-of :initform 0)
24    (ok :accessor ok-of :initform 0)))
25
26 (defun clear-coverage ()
27   "Clear all files from the coverage database. The files will be re-entered
28 into the database when the FASL files (produced by compiling
29 STORE-COVERAGE-DATA optimization policy set to 3) are loaded again into the
30 image."
31   (sb-c::clear-code-coverage))
32
33 (defun reset-coverage ()
34   "Reset all coverage data back to the `Not executed` state."
35   (sb-c::reset-code-coverage))
36
37 (defun save-coverage ()
38   "Returns an opaque representation of the current code coverage state.
39 The only operation that may be done on the state is passing it to
40 RESTORE-COVERAGE. The representation is guaranteed to be readably printable.
41 A representation that has been printed and read back will work identically
42 in RESTORE-COVERAGE."
43   (loop for file being the hash-keys of sb-c::*code-coverage-info*
44         using (hash-value states)
45         collect (cons file states)))
46
47 (defun restore-coverage (coverage-state)
48   "Restore the code coverage data back to an earlier state produced by
49 SAVE-COVERAGE."
50   (loop for (file . states) in coverage-state
51         do (let ((image-states (gethash file sb-c::*code-coverage-info*))
52                  (table (make-hash-table :test 'equal)))
53              (when image-states
54                (loop for cons in image-states
55                      do (setf (gethash (car cons) table) cons))
56                (loop for (key . value) in states
57                      do (let ((state (gethash key table)))
58                           (when state
59                             (setf (cdr state) value))))))))
60
61 (defun save-coverage-in-file (pathname)
62   "Call SAVE-COVERAGE and write the results of that operation into the
63 file designated by PATHNAME."
64   (with-open-file (stream pathname
65                           :direction :output
66                           :if-exists :supersede
67                           :if-does-not-exist :create)
68     (with-standard-io-syntax
69       (let ((*package* (find-package :sb-cover)))
70         (write (save-coverage) :stream stream)))
71     (values)))
72
73 (defun restore-coverage-from-file (pathname)
74   "READ the contents of the file designated by PATHNAME and pass the
75 result to RESTORE-COVERAGE."
76   (with-open-file (stream pathname :direction :input)
77     (with-standard-io-syntax
78       (let ((*package* (find-package :sb-cover)))
79         (restore-coverage (read stream))))
80     (values)))
81
82 (defun report (directory &key ((:form-mode *source-path-mode*) :whole)
83                (external-format :default))
84   "Print a code coverage report of all instrumented files into DIRECTORY.
85 If DIRECTORY does not exist, it will be created. The main report will be
86 printed to the file cover-index.html. The external format of the source
87 files can be specified with the EXTERNAL-FORMAT parameter.
88
89 If the keyword argument FORM-MODE has the value :CAR, the annotations in
90 the coverage report will be placed on the CARs of any cons-forms, while if
91 it has the value :WHOLE the whole form will be annotated (the default).
92 The former mode shows explicitly which forms were instrumented, while the
93 latter mode is generally easier to read."
94   (let ((paths)
95         (*default-pathname-defaults* (merge-pathnames (pathname directory))))
96     (ensure-directories-exist *default-pathname-defaults*)
97     (maphash (lambda (k v)
98                (declare (ignore v))
99                (let* ((n (substitute #\_ #\. (substitute #\_ #\/ k)))
100                       (path (make-pathname :name n :type "html")))
101                  (when (probe-file k)
102                    (with-open-file (stream path
103                                            :direction :output
104                                            :if-exists :supersede
105                                            :if-does-not-exist :create)
106                      (push (list* k n (report-file k stream external-format))
107                            paths)))))
108              *code-coverage-info*)
109     (let ((report-file (make-pathname :name "cover-index" :type "html")))
110       (with-open-file (stream report-file
111                               :direction :output :if-exists :supersede
112                               :if-does-not-exist :create)
113         (write-styles stream)
114         (unless paths
115           (warn "No coverage data found for any file, producing an empty report. Maybe you~%forgot to (DECLAIM (OPTIMIZE SB-COVER:STORE-COVERAGE-DATA))?")
116           (format stream "<h3>No code coverage data found.</h3>")
117           (close stream)
118           (return-from report))
119         (format stream "<table class='summary'>")
120         (format stream "<tr class='head-row'><td></td><td class='main-head' colspan='3'>Expression</td><td class='main-head' colspan='3'>Branch</td></tr>")
121         (format stream "<tr class='head-row'>~{<td width='80px'>~A</td>~}</tr>"
122                 (list "Source file"
123                       "Covered" "Total" "%"
124                       "Covered" "Total" "%"))
125         (setf paths (sort paths #'string< :key #'car))
126         (loop for prev = nil then source-file
127               for (source-file report-file expression branch) in paths
128               for even = nil then (not even)
129               do (when (or (null prev)
130                            (not (equal (pathname-directory (pathname source-file))
131                                        (pathname-directory (pathname prev)))))
132                    (format stream "<tr class='subheading'><td colspan='7'>~A</td></tr>~%"
133                            (namestring (make-pathname :directory (pathname-directory (pathname source-file))))))
134               do (format stream "<tr class='~:[odd~;even~]'><td class='text-cell'><a href='~a.html'>~a</a></td>~{<td>~:[-~;~:*~a~]</td><td>~:[-~;~:*~a~]</td><td>~:[-~;~:*~5,1f~]</td>~}</tr>"
135                          even
136                          report-file
137                          (enough-namestring (pathname source-file)
138                                             (pathname source-file))
139                          (list (ok-of expression)
140                                (all-of expression)
141                                (percent expression)
142                                (ok-of branch)
143                                (all-of branch)
144                                (percent branch))))
145         (format stream "</table>"))
146       report-file)))
147
148 (defun percent (count)
149   (unless (zerop (all-of count))
150     (* 100
151        (/ (ok-of count) (all-of count)))))
152
153 (defun report-file (file html-stream external-format)
154   "Print a code coverage report of FILE into the stream HTML-STREAM."
155   (format html-stream "<html><head>")
156   (write-styles html-stream)
157   (format html-stream "</head><body>")
158   (let* ((source (detabify (read-file file external-format)))
159          (states (make-array (length source)
160                              :initial-element 0
161                              :element-type '(unsigned-byte 4)))
162          ;; Convert the code coverage records to a more suitable format
163          ;; for this function.
164          (expr-records (convert-records (gethash file *code-coverage-info*)
165                                         :expression))
166          (branch-records (convert-records (gethash file *code-coverage-info*)
167                                           :branch))
168          ;; Cache the source-maps
169          (maps (with-input-from-string (stream source)
170                  (loop with map = nil
171                        with form = nil
172                        with eof = nil
173                        for i from 0
174                        do (setf (values form map)
175                                 (handler-case
176                                     (read-and-record-source-map stream)
177                                   (end-of-file ()
178                                     (setf eof t))
179                                   (error (error)
180                                     (warn "Error when recording source map for toplevel form ~A:~%  ~A" i error)
181                                     (values nil
182                                             (make-hash-table)))))
183                        until eof
184                        when map
185                        collect (cons form map)))))
186     (mapcar (lambda (map)
187               (maphash (lambda (k locations)
188                          (declare (ignore k))
189                          (dolist (location locations)
190                            (destructuring-bind (start end suppress) location
191                              (when suppress
192                                (fill-with-state source states 15 (1- start)
193                                                 end)))))
194                        (cdr map)))
195             maps)
196     ;; Go through all records, find the matching source in the file,
197     ;; and update STATES to contain the state of the record in the
198     ;; indexes matching the source location. We do this in two stages:
199     ;; the first stage records the character ranges, and the second stage
200     ;; does the update, in order from shortest to longest ranges. This
201     ;; ensures that for each index in STATES will reflect the state of
202     ;; the innermost containing form.
203     (let ((counts (list :branch (make-instance 'sample-count :mode :branch)
204                         :expression (make-instance 'sample-count
205                                                    :mode :expression))))
206       (let ((records (append branch-records expr-records))
207             (locations nil))
208         (dolist (record records)
209           (destructuring-bind (mode path state) record
210             (let* ((path (reverse path))
211                    (tlf (car path))
212                    (source-form (car (nth tlf maps)))
213                    (source-map (cdr (nth tlf maps)))
214                    (source-path (cdr path)))
215               (cond ((eql mode :branch)
216                      (let ((count (getf counts :branch)))
217                        ;; For branches mode each record accounts for two paths
218                        (incf (ok-of count)
219                              (ecase state
220                                (5 2)
221                                ((6 9) 1)
222                                (10 0)))
223                        (incf (all-of count) 2)))
224                     (t
225                      (let ((count (getf counts :expression)))
226                        (when (eql state 1)
227                          (incf (ok-of count)))
228                        (incf (all-of count)))))
229               (if source-map
230                   (handler-case
231                       (multiple-value-bind (start end)
232                           (source-path-source-position (cons 0 source-path)
233                                                        source-form
234                                                        source-map)
235                         (push (list start end source state) locations))
236                     (error ()
237                       (warn "Error finding source location for source path ~A in file ~A~%" source-path file)))
238                   (warn "Unable to find a source map for toplevel form ~A in file ~A~%" tlf file)))))
239         ;; Now process the locations, from the shortest range to the longest
240         ;; one. If two locations have the same range, the one with the higher
241         ;; state takes precedence. The latter condition ensures that if
242         ;; there are both normal- and a branch-states for the same form,
243         ;; the branch-state will be used.
244         (setf locations (sort locations #'> :key #'fourth))
245         (dolist (location (stable-sort locations #'<
246                                        :key (lambda (location)
247                                               (- (second location)
248                                                  (first location)))))
249           (destructuring-bind (start end source state) location
250             (fill-with-state source states state start end))))
251       (print-report html-stream file counts states source)
252       (format html-stream "</body></html>")
253       (list (getf counts :expression)
254             (getf counts :branch)))))
255
256 (defun fill-with-state (source states state start end)
257   (let* ((pos (position #\Newline source
258                         :end start
259                         :from-end t))
260          (start-column (if pos
261                            (- start 1 pos)
262                            0))
263          (end-column 0))
264     (loop for i from start below end
265           for col from start-column
266           for char = (aref source i)
267           do (cond ((eql char #\Newline)
268                     (setf col -1))
269                    ((not (eql char #\Space))
270                     (setf end-column (max end-column col)))))
271     (loop for i from start below end
272           for col from start-column
273           for char = (aref source i)
274           do (if (eql char #\Newline)
275                  (setf col -1)
276                  (when (and (zerop (aref states i))
277                             #+nil (<= col end-column)
278                             (>= col start-column))
279                    (setf (aref states i) state))))))
280
281 ;;; Convert tabs to spaces
282 (defun detabify (source)
283   (with-output-to-string (stream)
284     (loop for char across source
285           for col from 0
286           for i from 0
287           do (if (eql char #\Tab)
288                  (loop repeat (- 8 (mod col 8))
289                        do (write-char #\Space stream)
290                        do (incf col)
291                        finally (decf col))
292                  (progn
293                    (when (eql char #\Newline)
294                      ;; Filter out empty last line
295                      (when (eql i (1- (length source)))
296                        (return))
297                      (setf col -1))
298                    (write-char char stream))))))
299
300 (defvar *counts* nil)
301
302 (defun print-report (html-stream file counts states source)
303   ;; Just used for testing
304   (setf *counts* counts)
305   (let ((*print-case* :downcase))
306     (format html-stream
307             "<h3>Coverage report: ~a <br />~%</h3>~%" file)
308     (when (zerop (all-of (getf counts :expression)))
309       (format html-stream "<b>File has no instrumented forms</b>")
310       (return-from print-report))
311     (format html-stream "<table class='summary'><tr class='head-row'>~{<td width='80px'>~a</td>~}"
312             (list "Kind" "Covered" "All" "%"))
313     (dolist (mode '(:expression :branch))
314       (let ((count (getf counts mode)))
315         (format html-stream "<tr class='~:[odd~;even~]'><td>~A</td><td>~a</td><td>~a</td><td>~5,1F</td></tr>~%"
316                 (eql mode :branch)
317                 mode
318                 (ok-of count)
319                 (all-of count)
320                 (percent count))))
321     (format html-stream "</table>"))
322   (format html-stream "<div class='key'><b>Key</b><br />~%")
323   (format html-stream "<div class='state-0'>Not instrumented</div>")
324   (format html-stream "<div class='state-15'>Conditionalized out</div>")
325   (format html-stream "<div class='state-1'>Executed</div>")
326   (format html-stream "<div class='state-2'>Not executed</div>")
327   (format html-stream "<div>&#160;</div>")
328   (format html-stream "<div class='state-5'>Both branches taken</div>")
329   (format html-stream "<div class='state-6'>One branch taken</div>")
330   (format html-stream "<div class='state-10''>Neither branch taken</div>")
331   (format html-stream "</div>")
332   (format html-stream "<nobr><div><code>~%")
333   (flet ((line (line)
334            (format html-stream "</code></div></nobr>~%<nobr><div class='source'><div class='line-number'><code>~A</code></div><code>&#160;" line)
335            line))
336     (loop for last-state = nil then state
337           with line = (line 1)
338           for col from 1
339           for char across source
340           for state across states
341           do (unless (eq state last-state)
342                (when last-state
343                  (format html-stream "</span>"))
344                (format html-stream "<span class='state-~a'>" state))
345           do (case char
346                ((#\Newline)
347                 (setf state nil)
348                 (setf col 0)
349                 (format html-stream "</span>")
350                 (line (incf line)))
351                ((#\Space)
352                 (format html-stream "&#160;"))
353                ((#\Tab)
354                 (error "tab"))
355                (t
356                 (if (alphanumericp char)
357                     (write-char char html-stream)
358                     (format html-stream "&#~A;" (char-code char))))))
359     (format html-stream "</code></div>")))
360
361 (defun write-styles (html-stream)
362   (format html-stream "<style type='text/css'>
363 *.state-0 { background-color: #eeeeee }
364 *.state-1 { background-color: #aaffaa }
365 *.state-5 { background-color: #44dd44 }
366 *.state-2 { background-color: #ffaaaa }
367 *.state-10 { background-color: #ee6666 }
368 *.state-15 { color: #aaaaaa; background-color: #eeeeee }
369 *.state-9,*.state-6 { background-color: #ffffaa }
370 div.key { margin: 20px; width: 200px }
371 div.source { width: 88ex; background-color: #eeeeee; padding-left: 5px;
372              /* border-style: solid none none none; border-width: 1px;
373              border-color: #dddddd */ }
374
375 *.line-number { color: #666666; float: left; width: 6ex; text-align: right; margin-right: 1ex; }
376
377 table.summary tr.head-row { background-color: #aaaaff }
378 table.summary tr td.text-cell { text-align: left }
379 table.summary tr td.main-head { text-align: center }
380 table.summary tr td { text-align: right }
381 table.summary tr.even { background-color: #eeeeff }
382 table.summary tr.subheading { background-color: #aaaaff}
383 table.summary tr.subheading td { text-align: left; font-weight: bold; padding-left: 5ex; }
384 </style>"))
385
386 (defun convert-records (records mode)
387   (ecase mode
388     (:expression
389      (loop for record in records
390            unless (member (caar record) '(:then :else))
391            collect (list mode
392                          (car record)
393                          (if (sb-c::code-coverage-record-marked record)
394                              1
395                              2))))
396     (:branch
397      (let ((hash (make-hash-table :test 'equal)))
398        (dolist (record records)
399          (let ((path (car record)))
400            (when (member (car path) '(:then :else))
401              (setf (gethash (cdr path) hash)
402                    (logior (gethash (cdr path) hash 0)
403                            (ash (if (sb-c::code-coverage-record-marked record)
404                                     1
405                                     2)
406                                 (if (eql (car path) :then)
407                                     0
408                                     2)))))))
409        (let ((list nil))
410          (maphash (lambda (k v)
411                     (push (list mode k v) list))
412                   hash)
413          list)))))
414
415 ;;;; A mutant version of swank-source-path-parser from Swank/Slime.
416
417 (defun read-file (filename external-format)
418   "Return the entire contents of FILENAME as a string."
419   (with-open-file (s filename :direction :input
420                      :external-format external-format)
421     (let ((string (make-string (file-length s))))
422       (read-sequence string s)
423       string)))
424
425 (defun make-source-recorder (fn source-map)
426   "Return a macro character function that does the same as FN, but
427 additionally stores the result together with the stream positions
428 before and after of calling FN in the hashtable SOURCE-MAP."
429   (declare (type function fn))
430   (lambda (stream char)
431     (declare (optimize debug safety))
432     (let ((start (file-position stream))
433           (values (multiple-value-list (funcall fn stream char)))
434           (end (file-position stream)))
435       (unless (null values)
436         (push (list start end *read-suppress*)
437               (gethash (car values) source-map)))
438       (values-list values))))
439
440 (defun make-source-recording-readtable (readtable source-map)
441   "Return a source position recording copy of READTABLE.
442 The source locations are stored in SOURCE-MAP."
443   (let* ((tab (copy-readtable readtable))
444          (*readtable* tab))
445     (dotimes (code 128)
446       (let ((char (code-char code)))
447         (multiple-value-bind (fn term) (get-macro-character char tab)
448           (when fn
449             (set-macro-character char (make-source-recorder fn source-map)
450                                  term tab)))))
451     (suppress-sharp-dot tab)
452     (set-macro-character #\(
453                          (make-source-recorder
454                           (make-recording-read-list source-map)
455                           source-map))
456     tab))
457
458 ;;; Ripped from SB-IMPL, since location recording on a cons-cell level
459 ;;; can't be done just by simple read-table tricks.
460 (defun make-recording-read-list (source-map)
461   (lambda (stream ignore)
462     (block return
463       (when (eql *package* (find-package :keyword))
464         (return-from return
465           (sb-impl::read-list stream ignore)))
466       (let* ((thelist (list nil))
467              (listtail thelist))
468         (do ((firstchar (sb-impl::flush-whitespace stream)
469                         (sb-impl::flush-whitespace stream)))
470             ((char= firstchar #\) ) (cdr thelist))
471           (when (char= firstchar #\.)
472             (let ((nextchar (read-char stream t)))
473               (cond ((sb-impl::token-delimiterp nextchar)
474                      (cond ((eq listtail thelist)
475                             (unless *read-suppress*
476                               (sb-int:simple-reader-error
477                                stream
478                                "Nothing appears before . in list.")))
479                            ((sb-impl::whitespace[2]p nextchar)
480                             (setq nextchar (sb-impl::flush-whitespace stream))))
481                      (rplacd listtail
482                              ;; Return list containing last thing.
483                              (car (sb-impl::read-after-dot stream nextchar)))
484                      (return (cdr thelist)))
485                     ;; Put back NEXTCHAR so that we can read it normally.
486                     (t (unread-char nextchar stream)))))
487           ;; Next thing is not an isolated dot.
488           (let ((start (file-position stream))
489                 (listobj (sb-impl::read-maybe-nothing stream firstchar))
490                 (end (file-position stream)))
491             ;; allows the possibility that a comment was read
492             (when listobj
493              (unless (consp (car listobj))
494                (setf (car listobj) (gensym))
495                 (push (list start end *read-suppress*)
496                       (gethash (car listobj) source-map)))
497               (rplacd listtail listobj)
498               (setq listtail listobj))))))))
499
500 (defun suppress-sharp-dot (readtable)
501   (when (get-macro-character #\# readtable)
502     (let ((sharp-dot (get-dispatch-macro-character #\# #\. readtable)))
503       (set-dispatch-macro-character #\# #\.
504                                     (lambda (&rest args)
505                                       (let ((*read-suppress* t))
506                                         (apply sharp-dot args)))
507                                     readtable))))
508
509 (defun read-and-record-source-map (stream)
510   "Read the next object from STREAM.
511 Return the object together with a hashtable that maps
512 subexpressions of the object to stream positions."
513   (let* ((source-map (make-hash-table :test #'eq))
514          (*readtable* (make-source-recording-readtable *readtable* source-map))
515          (start (file-position stream))
516          (form (read stream))
517          (end (file-position stream)))
518     ;; ensure that at least FORM is in the source-map
519     (unless (gethash form source-map)
520       (push (list start end nil)
521             (gethash form source-map)))
522     (values form source-map)))
523
524 (defun read-source-form (n stream)
525   "Read the Nth toplevel form number with source location recording.
526 Return the form and the source-map."
527   (let ((*read-suppress* t))
528     (dotimes (i n)
529       (read stream)))
530   (let ((*read-suppress* nil)
531         (*read-eval* nil))
532     (read-and-record-source-map stream)))
533
534 (defun source-path-stream-position (path stream)
535   "Search the source-path PATH in STREAM and return its position."
536   (check-source-path path)
537   (destructuring-bind (tlf-number . path) path
538     (multiple-value-bind (form source-map) (read-source-form tlf-number stream)
539       (source-path-source-position (cons 0 path) form source-map))))
540
541 (defun check-source-path (path)
542   (unless (and (consp path)
543                (every #'integerp path))
544     (error "The source-path ~S is not valid." path)))
545
546 (defun source-path-string-position (path string)
547   (with-input-from-string (s string)
548     (source-path-stream-position path s)))
549
550 (defun source-path-file-position (path filename)
551   (with-open-file (file filename)
552     (source-path-stream-position path file)))
553
554 (defun source-path-source-position (path form source-map)
555   "Return the start position of PATH from FORM and SOURCE-MAP.  All
556 subforms along the path are considered and the start and end position
557 of the deepest (i.e. smallest) possible form is returned."
558   ;; compute all subforms along path
559   (let ((forms (loop for n in path
560                      for f = form then (nth n f)
561                      collect f into forms
562                      finally (return forms))))
563     ;; select the first subform present in source-map
564     (loop for real-form in (reverse forms)
565           for form = (if (or (eql *source-path-mode* :whole)
566                              (not (consp real-form)))
567                          real-form
568                          (car real-form))
569           for positions = (gethash form source-map)
570           until (and positions (null (cdr positions)))
571           finally (destructuring-bind ((start end suppress)) positions
572                     (declare (ignore suppress))
573                     (return (values (1- start) end))))))