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