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