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 (defclass sample-count ()
19 ((mode :accessor mode-of :initarg :mode)
20 (all :accessor all-of :initform 0)
21 (ok :accessor ok-of :initform 0)))
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
28 (sb-c::clear-code-coverage))
30 (defun reset-coverage ()
31 "Reset all coverage data back to the `Not executed` state."
32 (sb-c::reset-code-coverage))
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
40 (loop for file being the hash-keys of sb-c::*code-coverage-info*
41 using (hash-value states)
42 collect (cons file states)))
44 (defun restore-coverage (coverage-state)
45 "Restore the code coverage data back to an earlier state produced by
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)))
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)))
56 (setf (cdr state) value))))))))
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
64 :if-does-not-exist :create)
65 (with-standard-io-syntax
66 (let ((*package* (find-package :sb-cover)))
67 (write (save-coverage) :stream stream)))
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))))
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."
85 (*default-pathname-defaults* (merge-pathnames (pathname directory))))
86 (ensure-directories-exist *default-pathname-defaults*)
87 (maphash (lambda (k v)
89 (let* ((n (substitute #\_ #\. (substitute #\_ #\/ k)))
90 (path (make-pathname :name n :type "html")))
92 (with-open-file (stream path
95 :if-does-not-exist :create)
96 (push (list* k n (report-file k stream external-format))
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)
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>")
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>"
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>"
127 (enough-namestring (pathname source-file)
128 (pathname source-file))
129 (list (ok-of expression)
135 (format stream "</table>"))
138 (defun percent (count)
139 (unless (zerop (all-of count))
141 (/ (ok-of count) (all-of count)))))
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)
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*)
156 (branch-records (convert-records (gethash file *code-coverage-info*)
158 ;; Cache the source-maps
159 (maps (with-input-from-string (stream source)
164 do (setf (values form map)
166 (read-and-record-source-map stream)
170 (warn "Error when recording source map for toplevel form ~A:~% ~A" i error)
172 (make-hash-table)))))
175 collect (cons form map)))))
176 (mapcar (lambda (map)
177 (maphash (lambda (k locations)
179 (dolist (location locations)
180 (destructuring-bind (start end suppress) location
182 (fill-with-state source states 15 (1- start)
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))
198 (dolist (record records)
199 (destructuring-bind (mode path state) record
200 (let* ((path (reverse 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
213 (incf (all-of count) 2)))
215 (let ((count (getf counts :expression)))
217 (incf (ok-of count)))
218 (incf (all-of count)))))
221 (multiple-value-bind (start end)
222 (source-path-source-position (cons 0 source-path)
225 (push (list start end source state) locations))
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
231 (dolist (location (sort locations #'<
232 :key (lambda (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)))))
242 (defun fill-with-state (source states state start end)
243 (let* ((pos (position #\Newline source
246 (start-column (if pos
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)
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)
262 (when (and (zerop (aref states i))
263 #+nil (<= col end-column)
264 (>= col start-column))
265 (setf (aref states i) state))))))
267 ;;; Convert tabs to spaces
268 (defun detabify (source)
269 (with-output-to-string (stream)
270 (loop for char across source
273 do (if (eql char #\Tab)
274 (loop repeat (- 8 (mod col 8))
275 do (write-char #\Space stream)
279 (when (eql char #\Newline)
280 ;; Filter out empty last line
281 (when (eql i (1- (length source)))
284 (write-char char stream))))))
286 (defvar *counts* nil)
288 (defun print-report (html-stream file counts states source)
289 ;; Just used for testing
290 (setf *counts* counts)
291 (let ((*print-case* :downcase))
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>~%"
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> </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>~%")
320 (format html-stream "</code></div></nobr>~%<nobr><div class='source'><div class='line-number'><code>~A</code></div><code> " line)
322 (loop for last-state = nil then state
325 for char across source
326 for state across states
327 do (unless (eq state last-state)
329 (format html-stream "</span>"))
330 (format html-stream "<span class='state-~a'>" state))
335 (format html-stream "</span>")
338 (format html-stream " "))
342 (if (alphanumericp char)
343 (write-char char html-stream)
344 (format html-stream "&#~A;" (char-code char))))))
345 (format html-stream "</code></div>")))
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 */ }
361 *.line-number { color: #666666; float: left; width: 6ex; text-align: right; margin-right: 1ex; }
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; }
372 (defun convert-records (records mode)
375 (loop for record in records
376 unless (member (caar record) '(:then :else))
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)
392 (if (eql (car path) :then)
396 (maphash (lambda (k v)
397 (push (list mode k v) list))
401 ;;;; A mutant version of swank-source-path-parser from Swank/Slime.
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)
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))))
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))
432 (let ((char (code-char code)))
433 (multiple-value-bind (fn term) (get-macro-character char tab)
435 (set-macro-character char (make-source-recorder fn source-map)
437 (suppress-sharp-dot tab)
438 (set-macro-character #\(
439 (make-source-recorder
440 (make-recording-read-list source-map)
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)
449 (when (eql *package* (find-package :keyword))
451 (sb-impl::read-list stream ignore)))
452 (let* ((thelist (list nil))
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
464 "Nothing appears before . in list.")))
465 ((sb-impl::whitespace[2]p nextchar)
466 (setq nextchar (sb-impl::flush-whitespace stream))))
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
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))))))))
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 #\# #\.
491 (let ((*read-suppress* t))
492 (apply sharp-dot args)))
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))
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)))
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))
516 (let ((*read-suppress* nil)
518 (read-and-record-source-map stream)))
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))))
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)))
532 (defun source-path-string-position (path string)
533 (with-input-from-string (s string)
534 (source-path-stream-position path s)))
536 (defun source-path-file-position (path filename)
537 (with-open-file (file filename)
538 (source-path-stream-position path file)))
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
547 for dummy = (when (eql n :progn)
549 for f = form then (nth n f)
550 unless (null (cdr m))
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))))))