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