0.9.13.13: docstrings.lisp robustification
[sbcl.git] / doc / manual / docstrings.lisp
1 ;;; -*- lisp -*-
2
3 ;;;; A docstring extractor for the sbcl manual.  Creates
4 ;;;; @include-ready documentation from the docstrings of exported
5 ;;;; symbols of specified packages.
6
7 ;;;; This software is part of the SBCL software system. SBCL is in the
8 ;;;; public domain and is provided with absolutely no warranty. See
9 ;;;; the COPYING file for more information.
10 ;;;;
11 ;;;; Written by Rudi Schlatte <rudi@constantly.at>, mangled
12 ;;;; by Nikodemus Siivola.
13
14 ;;;; TODO
15 ;;;; * Verbatim text
16 ;;;; * Quotations
17 ;;;; * Method documentation untested
18 ;;;; * Method sorting, somehow
19 ;;;; * Index for macros & constants?
20 ;;;; * This is getting complicated enough that tests would be good
21 ;;;; * Nesting (currently only nested itemizations work)
22 ;;;; * doc -> internal form -> texinfo (so that non-texinfo format are also
23 ;;;;   easily generated)
24
25 ;;;; FIXME: The description below is no longer complete. This
26 ;;;; should possibly be turned into a contrib with proper documentation.
27
28 ;;;; Formatting heuristics (tweaked to format SAVE-LISP-AND-DIE sanely):
29 ;;;;
30 ;;;; Formats SYMBOL as @code{symbol}, or @var{symbol} if symbol is in
31 ;;;; the argument list of the defun / defmacro.
32 ;;;;
33 ;;;; Lines starting with * or - that are followed by intented lines
34 ;;;; are marked up with @itemize.
35 ;;;;
36 ;;;; Lines containing only a SYMBOL that are followed by indented
37 ;;;; lines are marked up as @table @code, with the SYMBOL as the item.
38
39 (eval-when (:compile-toplevel :load-toplevel :execute)
40   (require 'sb-introspect))
41
42 (defpackage :sb-texinfo
43   (:use :cl :sb-mop)
44   (:shadow #:documentation)
45   (:export #:generate-includes #:document-package)
46   (:documentation
47    "Tools to generate TexInfo documentation from docstrings."))
48
49 (in-package :sb-texinfo)
50
51 ;;;; various specials and parameters
52
53 (defvar *texinfo-output*)
54 (defvar *texinfo-variables*)
55 (defvar *documentation-package*)
56
57 (defparameter *undocumented-packages* '(sb-pcl sb-int sb-kernel sb-sys sb-c))
58
59 (defparameter *documentation-types*
60   '(compiler-macro
61     function
62     method-combination
63     setf
64     ;;structure  ; also handled by `type'
65     type
66     variable)
67   "A list of symbols accepted as second argument of `documentation'")
68
69 (defparameter *character-replacements*
70   '((#\* . "star") (#\/ . "slash") (#\+ . "plus")
71     (#\< . "lt") (#\> . "gt"))
72   "Characters and their replacement names that `alphanumize' uses. If
73 the replacements contain any of the chars they're supposed to replace,
74 you deserve to lose.")
75
76 (defparameter *characters-to-drop* '(#\\ #\` #\')
77   "Characters that should be removed by `alphanumize'.")
78
79 (defparameter *texinfo-escaped-chars* "@{}"
80   "Characters that must be escaped with #\@ for Texinfo.")
81
82 (defparameter *itemize-start-characters* '(#\* #\-)
83   "Characters that might start an itemization in docstrings when
84   at the start of a line.")
85
86 (defparameter *symbol-characters* "ABCDEFGHIJKLMNOPQRSTUVWXYZ*:-+&"
87   "List of characters that make up symbols in a docstring.")
88
89 (defparameter *symbol-delimiters* " ,.!?;")
90
91 (defparameter *ordered-documentation-kinds*
92   '(package type structure condition class macro))
93
94 ;;;; utilities
95
96 (defun flatten (list)
97   (cond ((null list)
98          nil)
99         ((consp (car list))
100          (nconc (flatten (car list)) (flatten (cdr list))))
101         ((null (cdr list))
102          (cons (car list) nil))
103         (t
104          (cons (car list) (flatten (cdr list))))))
105
106 (defun whitespacep (char)
107   (find char #(#\tab #\space #\page)))
108
109 (defun setf-name-p (name)
110   (or (symbolp name)
111       (and (listp name) (= 2 (length name)) (eq (car name) 'setf))))
112
113 (defgeneric specializer-name (specializer))
114
115 (defmethod specializer-name ((specializer eql-specializer))
116   (list 'eql (eql-specializer-object specializer)))
117
118 (defmethod specializer-name ((specializer class))
119   (class-name specializer))
120
121 (defun specialized-lambda-list (method)
122   ;; courtecy of AMOP p. 61
123   (let* ((specializers (method-specializers method))
124          (lambda-list (method-lambda-list method))
125          (n-required (length specializers)))
126     (append (mapcar (lambda (arg specializer)
127                       (if  (eq specializer (find-class 't))
128                            arg
129                            `(,arg ,(specializer-name specializer))))
130                     (subseq lambda-list 0 n-required)
131                     specializers)
132            (subseq lambda-list n-required))))
133
134 (defun string-lines (string)
135   "Lines in STRING as a vector."
136   (coerce (with-input-from-string (s string)
137             (loop for line = (read-line s nil nil)
138                while line collect line))
139           'vector))
140
141 (defun indentation (line)
142   "Position of first non-SPACE character in LINE."
143   (position-if-not (lambda (c) (char= c #\Space)) line))
144
145 (defun docstring (x doc-type)
146   (cl:documentation x doc-type))
147
148 (defun flatten-to-string (list)
149   (format nil "~{~A~^-~}" (flatten list)))
150
151 (defun alphanumize (original)
152   "Construct a string without characters like *`' that will f-star-ck
153 up filename handling. See `*character-replacements*' and
154 `*characters-to-drop*' for customization."
155   (let ((name (remove-if (lambda (x) (member x *characters-to-drop*))
156                          (if (listp original)
157                              (flatten-to-string original)
158                              (string original))))
159         (chars-to-replace (mapcar #'car *character-replacements*)))
160     (flet ((replacement-delimiter (index)
161              (cond ((or (< index 0) (>= index (length name))) "")
162                    ((alphanumericp (char name index)) "-")
163                    (t ""))))
164       (loop for index = (position-if #'(lambda (x) (member x chars-to-replace))
165                                      name)
166          while index
167          do (setf name (concatenate 'string (subseq name 0 index)
168                                     (replacement-delimiter (1- index))
169                                     (cdr (assoc (aref name index)
170                                                 *character-replacements*))
171                                     (replacement-delimiter (1+ index))
172                                     (subseq name (1+ index))))))
173     name))
174
175 ;;;; generating various names
176
177 (defgeneric name (thing)
178   (:documentation "Name for a documented thing. Names are either
179 symbols or lists of symbols."))
180
181 (defmethod name ((symbol symbol))
182   symbol)
183
184 (defmethod name ((cons cons))
185   cons)
186
187 (defmethod name ((package package))
188   (package-name package))
189
190 (defmethod name ((method method))
191   (list
192    (generic-function-name (method-generic-function method))
193    (method-qualifiers method)
194    (specialized-lambda-list method)))
195
196 ;;; Node names for DOCUMENTATION instances
197
198 (defgeneric name-using-kind/name (kind name doc))
199
200 (defmethod name-using-kind/name (kind (name string) doc)
201   (declare (ignore kind doc))
202   name)
203
204 (defmethod name-using-kind/name (kind (name symbol) doc)
205   (declare (ignore kind))
206   (format nil "~A:~A" (package-name (get-package doc)) name))
207
208 (defmethod name-using-kind/name (kind (name list) doc)
209   (declare (ignore kind))
210   (assert (setf-name-p name))
211   (format nil "(setf ~A:~A)" (package-name (get-package doc)) (second name)))
212
213 (defmethod name-using-kind/name ((kind (eql 'method)) name doc)
214   (format nil "~A~{ ~A~} ~A"
215           (name-using-kind/name nil (first name) doc)
216           (second name)
217           (third name)))
218
219 (defun node-name (doc)
220   "Returns TexInfo node name as a string for a DOCUMENTATION instance."
221   (let ((kind (get-kind doc)))
222     (format nil "~:(~A~) ~(~A~)" kind (name-using-kind/name kind (get-name doc) doc))))
223
224 ;;; Definition titles for DOCUMENTATION instances
225
226 (defgeneric title-using-kind/name (kind name doc))
227
228 (defmethod title-using-kind/name (kind (name string) doc)
229   (declare (ignore kind doc))
230   name)
231
232 (defmethod title-using-kind/name (kind (name symbol) doc)
233   (declare (ignore kind))
234   (format nil "~A:~A" (package-name (get-package doc)) name))
235
236 (defmethod title-using-kind/name (kind (name list) doc)
237   (declare (ignore kind))
238   (assert (setf-name-p name))
239   (format nil "(setf ~A:~A)" (package-name (get-package doc)) (second name)))
240
241 (defmethod title-using-kind/name ((kind (eql 'method)) name doc)
242   (format nil "~{~A ~}~A"
243           (second name)
244           (title-using-kind/name nil (first name) doc)))
245
246 (defun title-name (doc)
247   "Returns a string to be used as name of the definition."
248   (string-downcase (title-using-kind/name (get-kind doc) (get-name doc) doc)))
249
250 (defun include-pathname (doc)
251   (let* ((kind (get-kind doc))
252          (name (nstring-downcase
253                 (if (eq 'package kind)
254                     (format nil "package-~A" (alphanumize (get-name doc)))
255                     (format nil "~A-~A-~A"
256                             (case (get-kind doc)
257                               ((function generic-function) "fun")
258                               (structure "struct")
259                               (variable "var")
260                               (otherwise (symbol-name (get-kind doc))))
261                             (alphanumize (package-name (get-package doc)))
262                             (alphanumize (get-name doc)))))))
263     (make-pathname :name name  :type "texinfo")))
264
265 ;;;; documentation class and related methods
266
267 (defclass documentation ()
268   ((name :initarg :name :reader get-name)
269    (kind :initarg :kind :reader get-kind)
270    (string :initarg :string :reader get-string)
271    (children :initarg :children :initform nil :reader get-children)
272    (package :initform *documentation-package* :reader get-package)))
273
274 (defmethod print-object ((documentation documentation) stream)
275   (print-unreadable-object (documentation stream :type t)
276     (princ (list (get-kind documentation) (get-name documentation)) stream)))
277
278 (defgeneric make-documentation (x doc-type string))
279
280 (defmethod make-documentation ((x package) doc-type string)
281   (declare (ignore doc-type))
282   (make-instance 'documentation
283                  :name (name x)
284                  :kind 'package
285                  :string string))
286
287 (defmethod make-documentation (x (doc-type (eql 'function)) string)
288   (declare (ignore doc-type))
289   (let* ((fdef (and (fboundp x) (fdefinition x)))
290          (name x)
291          (kind (cond ((and (symbolp x) (special-operator-p x))
292                       'special-operator)
293                      ((and (symbolp x) (macro-function x))
294                       'macro)
295                      ((typep fdef 'generic-function)
296                       (assert (or (symbolp name) (setf-name-p name)))
297                       'generic-function)
298                      (fdef
299                       (assert (or (symbolp name) (setf-name-p name)))
300                       'function)))
301          (children (when (eq kind 'generic-function)
302                      (collect-gf-documentation fdef))))
303     (make-instance 'documentation
304                    :name (name x)
305                    :string string
306                    :kind kind
307                    :children children)))
308
309 (defmethod make-documentation ((x method) doc-type string)
310   (declare (ignore doc-type))
311   (make-instance 'documentation
312                  :name (name x)
313                  :kind 'method
314                  :string string))
315
316 (defmethod make-documentation (x (doc-type (eql 'type)) string)
317   (make-instance 'documentation
318                  :name (name x)
319                  :string string
320                  :kind (etypecase (find-class x nil)
321                          (structure-class 'structure)
322                          (standard-class 'class)
323                          (sb-pcl::condition-class 'condition)
324                          ((or built-in-class null) 'type))))
325
326 (defmethod make-documentation (x (doc-type (eql 'variable)) string)
327   (make-instance 'documentation
328                  :name (name x)
329                  :string string
330                  :kind (if (constantp x)
331                            'constant
332                            'variable)))
333
334 (defmethod make-documentation (x (doc-type (eql 'setf)) string)
335   (declare (ignore doc-type))
336   (make-instance 'documentation
337                  :name (name x)
338                  :kind 'setf-expander
339                  :string string))
340
341 (defmethod make-documentation (x doc-type string)
342   (make-instance 'documentation
343                  :name (name x)
344                  :kind doc-type
345                  :string string))
346
347 (defun maybe-documentation (x doc-type)
348   "Returns a DOCUMENTATION instance for X and DOC-TYPE, or NIL if
349 there is no corresponding docstring."
350   (let ((docstring (docstring x doc-type)))
351     (when docstring
352       (make-documentation x doc-type docstring))))
353
354 (defun lambda-list (doc)
355   (case (get-kind doc)
356     ((package constant variable type structure class condition nil)
357      nil)
358     (method
359      (third (get-name doc)))    
360     (t
361      ;; KLUDGE: Eugh.
362      ;;
363      ;; believe it or not, the above comment was written before CSR
364      ;; came along and obfuscated this.  (2005-07-04)
365      (when (symbolp (get-name doc))
366        (labels ((clean (x &key optional key)
367                   (typecase x
368                     (atom x)
369                     ((cons (member &optional))
370                      (cons (car x) (clean (cdr x) :optional t)))
371                     ((cons (member &key))
372                      (cons (car x) (clean (cdr x) :key t)))
373                     ((cons cons)
374                      (cons
375                       (cond (key (if (consp (caar x))
376                                      (caaar x)
377                                      (caar x)))
378                             (optional (caar x))
379                             (t (clean (car x))))
380                       (clean (cdr x) :key key :optional optional)))
381                     (cons
382                      (cons
383                       (cond ((or key optional) (car x))
384                             (t (clean (car x))))
385                       (clean (cdr x) :key key :optional optional))))))
386          (clean (sb-introspect:function-arglist (get-name doc))))))))
387
388 (defun documentation< (x y)
389   (let ((p1 (position (get-kind x) *ordered-documentation-kinds*))
390         (p2 (position (get-kind y) *ordered-documentation-kinds*)))
391     (if (or (not (and p1 p2)) (= p1 p2))
392         (string< (string (get-name x)) (string (get-name y)))
393         (< p1 p2))))
394
395 ;;;; turning text into texinfo
396
397 (defun escape-for-texinfo (string &optional downcasep)
398   "Return STRING with characters in *TEXINFO-ESCAPED-CHARS* escaped
399 with #\@. Optionally downcase the result."
400   (let ((result (with-output-to-string (s)
401                   (loop for char across string
402                         when (find char *texinfo-escaped-chars*)
403                         do (write-char #\@ s)
404                         do (write-char char s)))))
405     (if downcasep (nstring-downcase result) result)))
406
407 (defun empty-p (line-number lines)
408   (and (< -1 line-number (length lines))
409        (not (indentation (svref lines line-number)))))
410
411 ;;; line markups
412
413 (defun locate-symbols (line)
414   "Return a list of index pairs of symbol-like parts of LINE."
415   ;; This would be a good application for a regex ...
416   (do ((result nil)
417        (begin nil)
418        (maybe-begin t)
419        (i 0 (1+ i)))
420       ((= i (length line))
421        ;; symbol at end of line
422        (when (and begin (or (> i (1+ begin))
423                             (not (member (char line begin) '(#\A #\I)))))
424          (push (list begin i) result))
425        (nreverse result))
426     (cond
427       ((and begin (find (char line i) *symbol-delimiters*))
428        ;; symbol end; remember it if it's not "A" or "I"
429        (when (or (> i (1+ begin)) (not (member (char line begin) '(#\A #\I))))
430          (push (list begin i) result))
431        (setf begin nil
432              maybe-begin t))
433       ((and begin (not (find (char line i) *symbol-characters*)))
434        ;; Not a symbol: abort
435        (setf begin nil))
436       ((and maybe-begin (not begin) (find (char line i) *symbol-characters*))
437        ;; potential symbol begin at this position
438        (setf begin i
439              maybe-begin nil))
440       ((find (char line i) *symbol-delimiters*)
441        ;; potential symbol begin after this position
442        (setf maybe-begin t))
443       (t
444        ;; Not reading a symbol, not at potential start of symbol
445        (setf maybe-begin nil)))))
446
447 (defun texinfo-line (line)
448   "Format symbols in LINE texinfo-style: either as code or as
449 variables if the symbol in question is contained in symbols
450 *TEXINFO-VARIABLES*."
451   (with-output-to-string (result)
452     (let ((last 0))
453       (dolist (symbol/index (locate-symbols line))
454         (write-string (subseq line last (first symbol/index)) result)
455         (let ((symbol-name (apply #'subseq line symbol/index)))
456           (format result (if (member symbol-name *texinfo-variables*
457                                      :test #'string=)
458                              "@var{~A}"
459                              "@code{~A}")
460                   (string-downcase symbol-name)))
461         (setf last (second symbol/index)))
462       (write-string (subseq line last) result))))
463
464 ;;; lisp sections
465
466 (defun lisp-section-p (line line-number lines)
467   "Returns T if the given LINE looks like start of lisp code --
468 ie. if it starts with whitespace followed by a paren or
469 semicolon, and the previous line is empty"
470   (let ((offset (indentation line)))
471     (and offset
472          (plusp offset)
473          (find (find-if-not #'whitespacep line) "(;")
474          (empty-p (1- line-number) lines))))
475
476 (defun collect-lisp-section (lines line-number)
477   (let ((lisp (loop for index = line-number then (1+ index)
478                     for line = (and (< index (length lines)) (svref lines index))
479                     while (indentation line)
480                     collect line)))
481     (values (length lisp) `("@lisp" ,@lisp "@end lisp"))))
482
483 ;;; itemized sections
484
485 (defun maybe-itemize-offset (line)
486   "Return NIL or the indentation offset if LINE looks like it starts
487 an item in an itemization."
488   (let* ((offset (indentation line))
489          (char (when offset (char line offset))))
490     (and offset
491          (member char *itemize-start-characters* :test #'char=)
492          (char= #\Space (find-if-not (lambda (c) (char= c char))
493                                      line :start offset))
494          offset)))
495
496 (defun collect-maybe-itemized-section (lines starting-line)
497   ;; Return index of next line to be processed outside
498   (let ((this-offset (maybe-itemize-offset (svref lines starting-line)))
499         (result nil)
500         (lines-consumed 0))
501     (loop for line-number from starting-line below (length lines)
502        for line = (svref lines line-number)
503        for indentation = (indentation line)
504        for offset = (maybe-itemize-offset line)
505        do (cond
506             ((not indentation)
507              ;; empty line -- inserts paragraph.
508              (push "" result)
509              (incf lines-consumed))
510             ((and offset (> indentation this-offset))
511              ;; nested itemization -- handle recursively
512              ;; FIXME: tables in itemizations go wrong
513              (multiple-value-bind (sub-lines-consumed sub-itemization)
514                  (collect-maybe-itemized-section lines line-number)
515                (when sub-lines-consumed
516                  (incf line-number (1- sub-lines-consumed)) ; +1 on next loop
517                  (incf lines-consumed sub-lines-consumed)
518                  (setf result (nconc (nreverse sub-itemization) result)))))
519             ((and offset (= indentation this-offset))
520              ;; start of new item
521              (push (format nil "@item ~A"
522                            (texinfo-line (subseq line (1+ offset))))
523                    result)
524              (incf lines-consumed))
525             ((and (not offset) (> indentation this-offset))
526              ;; continued item from previous line
527              (push (texinfo-line line) result)
528              (incf lines-consumed))
529             (t
530              ;; end of itemization
531              (loop-finish))))
532     ;; a single-line itemization isn't.
533     (if (> (count-if (lambda (line) (> (length line) 0)) result) 1)
534         (values lines-consumed `("@itemize" ,@(reverse result) "@end itemize"))
535         nil)))
536
537 ;;; table sections
538
539 (defun tabulation-body-p (offset line-number lines)
540   (when (< line-number (length lines))
541     (let ((offset2 (indentation (svref lines line-number))))
542       (and offset2 (< offset offset2)))))
543
544 (defun tabulation-p (offset line-number lines direction)
545   (let ((step  (ecase direction
546                  (:backwards (1- line-number))
547                  (:forwards (1+ line-number)))))
548     (when (and (plusp line-number) (< line-number (length lines)))
549       (and (eql offset (indentation (svref lines line-number)))
550            (or (when (eq direction :backwards)
551                  (empty-p step lines))
552                (tabulation-p offset step lines direction)
553                (tabulation-body-p offset step lines))))))
554
555 (defun maybe-table-offset (line-number lines)
556   "Return NIL or the indentation offset if LINE looks like it starts
557 an item in a tabulation. Ie, if it is (1) indented, (2) preceded by an
558 empty line, another tabulation label, or a tabulation body, (3) and
559 followed another tabulation label or a tabulation body."
560   (let* ((line (svref lines line-number))
561          (offset (indentation line))
562          (prev (1- line-number))
563          (next (1+ line-number)))
564     (when (and offset (plusp offset))
565       (and (or (empty-p prev lines)
566                (tabulation-body-p offset prev lines)
567                (tabulation-p offset prev lines :backwards))
568            (or (tabulation-body-p offset next lines)
569                (tabulation-p offset next lines :forwards))
570            offset))))
571
572 ;;; FIXME: This and itemization are very similar: could they share
573 ;;; some code, mayhap?
574
575 (defun collect-maybe-table-section (lines starting-line)
576   ;; Return index of next line to be processed outside
577   (let ((this-offset (maybe-table-offset starting-line lines))
578         (result nil)
579         (lines-consumed 0))
580     (loop for line-number from starting-line below (length lines)
581           for line = (svref lines line-number)
582           for indentation = (indentation line)
583           for offset = (maybe-table-offset line-number lines)
584           do (cond
585                ((not indentation)
586                 ;; empty line -- inserts paragraph.
587                 (push "" result)
588                 (incf lines-consumed))
589                ((and offset (= indentation this-offset))
590                 ;; start of new item, or continuation of previous item
591                 (if (and result (search "@item" (car result) :test #'char=))
592                     (push (format nil "@itemx ~A" (texinfo-line line))
593                           result)
594                     (progn
595                       (push "" result)
596                       (push (format nil "@item ~A" (texinfo-line line))
597                             result)))
598                 (incf lines-consumed))
599                ((> indentation this-offset)
600                 ;; continued item from previous line
601                 (push (texinfo-line line) result)
602                 (incf lines-consumed))
603                (t
604                 ;; end of itemization
605                 (loop-finish))))
606      ;; a single-line table isn't.
607     (if (> (count-if (lambda (line) (> (length line) 0)) result) 1)
608         (values lines-consumed
609                 `("" "@table @emph" ,@(reverse result) "@end table" ""))
610         nil)))
611
612 ;;; section markup
613
614 (defmacro with-maybe-section (index &rest forms)
615   `(multiple-value-bind (count collected) (progn ,@forms)
616     (when count
617       (dolist (line collected)
618         (write-line line *texinfo-output*))
619       (incf ,index (1- count)))))
620
621 (defun write-texinfo-string (string &optional lambda-list)
622   "Try to guess as much formatting for a raw docstring as possible."
623   (let ((*texinfo-variables* (flatten lambda-list))
624         (lines (string-lines (escape-for-texinfo string nil))))
625       (loop for line-number from 0 below (length lines)
626             for line = (svref lines line-number)
627             do (cond
628                  ((with-maybe-section line-number
629                     (and (lisp-section-p line line-number lines)
630                          (collect-lisp-section lines line-number))))
631                  ((with-maybe-section line-number
632                     (and (maybe-itemize-offset line)
633                          (collect-maybe-itemized-section lines line-number))))
634                  ((with-maybe-section line-number
635                     (and (maybe-table-offset line-number lines)
636                          (collect-maybe-table-section lines line-number))))
637                  (t
638                   (write-line (texinfo-line line) *texinfo-output*))))))
639
640 ;;;; texinfo formatting tools
641
642 (defun hide-superclass-p (class-name super-name)
643   (let ((super-package (symbol-package super-name)))
644     (or
645      ;; KLUDGE: We assume that we don't want to advertise internal
646      ;; classes in CP-lists, unless the symbol we're documenting is
647      ;; internal as well.
648      (and (member super-package #.'(mapcar #'find-package *undocumented-packages*))
649           (not (eq super-package (symbol-package class-name))))
650      ;; KLUDGE: We don't generally want to advertise SIMPLE-ERROR or
651      ;; SIMPLE-CONDITION in the CPLs of conditions that inherit them
652      ;; simply as a matter of convenience. The assumption here is that
653      ;; the inheritance is incidental unless the name of the condition
654      ;; begins with SIMPLE-.
655      (and (member super-name '(simple-error simple-condition))
656           (let ((prefix "SIMPLE-"))
657             (mismatch prefix (string class-name) :end2 (length prefix)))
658           t ; don't return number from MISMATCH
659           ))))
660
661 (defun hide-slot-p (symbol slot)
662   ;; FIXME: There is no pricipal reason to avoid the slot docs fo
663   ;; structures and conditions, but their DOCUMENTATION T doesn't
664   ;; currently work with them the way we'd like.
665   (not (and (typep (find-class symbol nil) 'standard-class)
666             (docstring slot t))))
667
668 (defun texinfo-anchor (doc)
669   (format *texinfo-output* "@anchor{~A}~%" (node-name doc)))
670
671 ;;; KLUDGE: &AUX *PRINT-PRETTY* here means "no linebreaks please"
672 (defun texinfo-begin (doc &aux *print-pretty*)
673   (let ((kind (get-kind doc)))
674     (format *texinfo-output* "@~A {~:(~A~)} ~(~A~@[ ~{~A~^ ~}~]~)~%"
675             (case kind
676               ((package constant variable)
677                "defvr")
678               ((structure class condition type)
679                "deftp")
680               (t
681                "deffn"))
682             (map 'string (lambda (char) (if (eql char #\-) #\Space char)) (string kind))
683             (title-name doc)
684             (lambda-list doc))))
685
686 (defun texinfo-index (doc)
687   (let ((title (title-name doc)))
688     (case (get-kind doc)
689       ((structure type class condition)
690        (format *texinfo-output* "@tindex ~A~%" title))
691       ((variable constant)
692        (format *texinfo-output* "@vindex ~A~%" title))
693       ((compiler-macro function method-combination macro generic-function)
694        (format *texinfo-output* "@findex ~A~%" title)))))
695
696 (defun texinfo-inferred-body (doc)
697   (when (member (get-kind doc) '(class structure condition))
698     (let ((name (get-name doc)))
699       ;; class precedence list
700       (format *texinfo-output* "Class precedence list: @code{~(~{@w{~A}~^, ~}~)}~%~%"
701               (remove-if (lambda (class)  (hide-superclass-p name class))
702                          (mapcar #'class-name (class-precedence-list (find-class name)))))
703       ;; slots
704       (let ((slots (remove-if (lambda (slot) (hide-slot-p name slot))
705                               (class-direct-slots (find-class name)))))
706         (when slots
707           (format *texinfo-output* "Slots:~%@itemize~%")
708           (dolist (slot slots)
709             (format *texinfo-output* "@item ~(@code{~A} ~
710                                      ~@[--- initargs: @code{~{@w{~S}~^, ~}}~]~)~%~%"
711                     (slot-definition-name slot)
712                     (slot-definition-initargs slot))
713             ;; FIXME: Would be neater to handler as children
714             (write-texinfo-string (docstring slot t)))
715           (format *texinfo-output* "@end itemize~%~%"))))))
716
717 (defun texinfo-body (doc)
718   (write-texinfo-string (get-string doc)))
719
720 (defun texinfo-end (doc)
721   (write-line (case (get-kind doc)
722                 ((package variable constant) "@end defvr")
723                 ((structure type class condition) "@end deftp")
724                 (t "@end deffn"))
725               *texinfo-output*))
726
727 (defun write-texinfo (doc)
728   "Writes TexInfo for a DOCUMENTATION instance to *TEXINFO-OUTPUT*."
729   (texinfo-anchor doc)
730   (texinfo-begin doc)
731   (texinfo-index doc)
732   (texinfo-inferred-body doc)
733   (texinfo-body doc)
734   (texinfo-end doc)
735   ;; FIXME: Children should be sorted one way or another
736   (mapc #'write-texinfo (get-children doc)))
737
738 ;;;; main logic
739
740 (defun collect-gf-documentation (gf)
741   "Collects method documentation for the generic function GF"
742   (loop for method in (generic-function-methods gf)
743         for doc = (maybe-documentation method t)
744         when doc
745         collect doc))
746
747 (defun collect-name-documentation (name)
748   (loop for type in *documentation-types*
749         for doc = (maybe-documentation name type)
750         when doc
751         collect doc))
752
753 (defun collect-symbol-documentation (symbol)
754   "Collects all docs for a SYMBOL and (SETF SYMBOL), returns a list of
755 the form DOC instances. See `*documentation-types*' for the possible
756 values of doc-type."
757   (nconc (collect-name-documentation symbol)
758          (collect-name-documentation (list 'setf symbol))))
759
760 (defun collect-documentation (package)
761   "Collects all documentation for all external symbols of the given
762 package, as well as for the package itself."
763   (let* ((*documentation-package* (find-package package))
764          (docs nil))
765     (check-type package package)
766     (do-external-symbols (symbol package)
767       (setf docs (nconc (collect-symbol-documentation symbol) docs)))
768     (let ((doc (maybe-documentation *documentation-package* t)))
769       (when doc
770         (push doc docs)))
771     docs))
772
773 (defmacro with-texinfo-file (pathname &body forms)
774   `(with-open-file (*texinfo-output* ,pathname
775                                     :direction :output
776                                     :if-does-not-exist :create
777                                     :if-exists :supersede)
778     ,@forms))
779
780 (defun generate-includes (directory &rest packages)
781   "Create files in `directory' containing Texinfo markup of all
782 docstrings of each exported symbol in `packages'. `directory' is
783 created if necessary. If you supply a namestring that doesn't end in a
784 slash, you lose. The generated files are of the form
785 \"<doc-type>_<packagename>_<symbol-name>.texinfo\" and can be included
786 via @include statements. Texinfo syntax-significant characters are
787 escaped in symbol names, but if a docstring contains invalid Texinfo
788 markup, you lose."
789   (handler-bind ((warning #'muffle-warning))
790     (let ((directory (merge-pathnames (pathname directory))))
791       (ensure-directories-exist directory)
792       (dolist (package packages)
793         (dolist (doc (collect-documentation (find-package package)))
794           (with-texinfo-file (merge-pathnames (include-pathname doc) directory)
795             (write-texinfo doc))))
796       directory)))
797
798 (defun document-package (package &optional filename)
799   "Create a file containing all available documentation for the
800 exported symbols of `package' in Texinfo format. If `filename' is not
801 supplied, a file \"<packagename>.texinfo\" is generated.
802
803 The definitions can be referenced using Texinfo statements like
804 @ref{<doc-type>_<packagename>_<symbol-name>.texinfo}. Texinfo
805 syntax-significant characters are escaped in symbol names, but if a
806 docstring contains invalid Texinfo markup, you lose."
807   (handler-bind ((warning #'muffle-warning))
808     (let* ((package (find-package package))
809            (filename (or filename (make-pathname
810                                    :name (string-downcase (package-name package))
811                                    :type "texinfo")))
812            (docs (sort (collect-documentation package) #'documentation<)))
813       (with-texinfo-file filename
814         (dolist (doc docs)
815           (write-texinfo doc)))
816       filename)))