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