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