1 ;;; A frontend for the SBCL code coverage facility. Written by Juho
2 ;;; Snellman, and placed under public domain.
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
11 #:reset-coverage #:clear-coverage
12 #:restore-coverage #:restore-coverage-from-file
13 #:save-coverage #:save-coverage-in-file
14 #:store-coverage-data))
16 (in-package #:sb-cover)
18 (declaim (type (member :whole :car) *source-path-mode*))
19 (defvar *source-path-mode* :whole)
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)))
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
31 (sb-c::clear-code-coverage))
33 (defun reset-coverage ()
34 "Reset all coverage data back to the `Not executed` state."
35 (sb-c::reset-code-coverage))
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
43 (loop for file being the hash-keys of sb-c::*code-coverage-info*
44 using (hash-value states)
45 collect (cons file states)))
47 (defun restore-coverage (coverage-state)
48 "Restore the code coverage data back to an earlier state produced by
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)))
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)))
59 (setf (cdr state) value))))))))
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
67 :if-does-not-exist :create)
68 (with-standard-io-syntax
69 (let ((*package* (find-package :sb-cover)))
70 (write (save-coverage) :stream stream)))
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))))
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)))
88 (error "~S does not designate a directory" pathname)
89 (make-pathname :directory (append (or (pathname-directory pathname)
91 (list (file-namestring pathname)))
93 :defaults pathname)))))
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.
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."
108 (*default-pathname-defaults* (pathname-as-directory directory)))
109 (ensure-directories-exist *default-pathname-defaults*)
110 (maphash (lambda (k v)
112 (let* ((n (format nil "~(~{~2,'0X~}~)"
113 (coerce (sb-md5:md5sum-string
114 (sb-ext:native-namestring k))
116 (path (make-pathname :name n :type "html")))
118 (with-open-file (stream path
120 :if-exists :supersede
121 :if-does-not-exist :create)
122 (push (list* k n (report-file k stream external-format))
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)
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>")
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>"
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>"
153 (enough-namestring (pathname source-file)
154 (pathname source-file))
155 (list (ok-of expression)
161 (format stream "</table>"))
164 (defun percent (count)
165 (unless (zerop (all-of count))
167 (/ (ok-of count) (all-of count)))))
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)
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*)
182 (branch-records (convert-records (gethash file *code-coverage-info*)
184 ;; Cache the source-maps
185 (maps (with-input-from-string (stream source)
190 do (setf (values form map)
192 (read-and-record-source-map stream)
196 (warn "Error when recording source map for toplevel form ~A:~% ~A" i error)
198 (make-hash-table)))))
201 collect (cons form map)))))
202 (mapcar (lambda (map)
203 (maphash (lambda (k locations)
205 (dolist (location locations)
206 (destructuring-bind (start end suppress) location
208 (fill-with-state source states 15 (1- start)
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))
224 (dolist (record records)
225 (destructuring-bind (mode path state) record
226 (let* ((path (reverse 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
239 (incf (all-of count) 2)))
241 (let ((count (getf counts :expression)))
243 (incf (ok-of count)))
244 (incf (all-of count)))))
247 (multiple-value-bind (start end)
248 (source-path-source-position (cons 0 source-path)
251 (push (list start end source state) locations))
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)
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)))))
272 (defun fill-with-state (source states state start end)
273 (let* ((pos (position #\Newline source
276 (start-column (if pos
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)
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)
292 (when (and (zerop (aref states i))
293 #+nil (<= col end-column)
294 (>= col start-column))
295 (setf (aref states i) state))))))
297 ;;; Convert tabs to spaces
298 (defun detabify (source)
299 (with-output-to-string (stream)
300 (loop for char across source
303 do (if (eql char #\Tab)
304 (loop repeat (- 8 (mod col 8))
305 do (write-char #\Space stream)
309 (when (eql char #\Newline)
310 ;; Filter out empty last line
311 (when (eql i (1- (length source)))
314 (write-char char stream))))))
316 (defvar *counts* nil)
318 (defun print-report (html-stream file counts states source)
319 ;; Just used for testing
320 (setf *counts* counts)
321 (let ((*print-case* :downcase))
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>~%"
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> </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>~%")
350 (format html-stream "</code></div></nobr>~%<nobr><div class='source'><div class='line-number'><code>~A</code></div><code> " line)
352 (loop for last-state = nil then state
355 for char across source
356 for state across states
357 do (unless (eq state last-state)
359 (format html-stream "</span>"))
360 (format html-stream "<span class='state-~a'>" state))
365 (format html-stream "</span>")
368 (format html-stream " "))
372 (if (alphanumericp char)
373 (write-char char html-stream)
374 (format html-stream "&#~A;" (char-code char))))))
375 (format html-stream "</code></div>")))
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 */ }
391 *.line-number { color: #666666; float: left; width: 6ex; text-align: right; margin-right: 1ex; }
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; }
402 (defun convert-records (records mode)
405 (loop for record in records
406 unless (member (caar record) '(:then :else))
409 (if (sb-c::code-coverage-record-marked record)
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)
422 (if (eql (car path) :then)
426 (maphash (lambda (k v)
427 (push (list mode k v) list))
431 ;;;; A mutant version of swank-source-path-parser from Swank/Slime.
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)
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))))
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))
462 (let ((char (code-char code)))
463 (multiple-value-bind (fn term) (get-macro-character char tab)
465 (set-macro-character char (make-source-recorder fn source-map)
467 (suppress-sharp-dot tab)
468 (set-macro-character #\(
469 (make-source-recorder
470 (make-recording-read-list source-map)
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)
479 (when (eql *package* (find-package :keyword))
481 (sb-impl::read-list stream ignore)))
482 (let* ((thelist (list nil))
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
494 "Nothing appears before . in list.")))
495 ((sb-impl::whitespace[2]p nextchar)
496 (setq nextchar (sb-impl::flush-whitespace stream))))
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
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))))))))
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 #\# #\.
521 (let ((*read-suppress* t))
522 (apply sharp-dot args)))
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))
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)))
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))
546 (let ((*read-suppress* nil)
548 (read-and-record-source-map stream)))
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))))
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)))
562 (defun source-path-string-position (path string)
563 (with-input-from-string (s string)
564 (source-path-stream-position path s)))
566 (defun source-path-file-position (path filename)
567 (with-open-file (file filename)
568 (source-path-stream-position path file)))
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)
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)))
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))))))