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