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