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