1.0.39.9: improvements to the manual
[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"))
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) '("ANSI" "CLHS"))
455                (push (list start end) result))))
456       (do ((begin nil)
457            (maybe-begin t)
458            (i 0 (1+ i)))
459           ((= i (length line))
460            ;; symbol at end of line
461            (when (and begin (or (> i (1+ begin))
462                                 (not (member (char line begin) '(#\A #\I)))))
463              (grab begin i))
464            (nreverse result))
465         (cond
466           ((and begin (find (char line i) *symbol-delimiters*))
467            ;; symbol end; remember it if it's not "A" or "I"
468            (when (or (> i (1+ begin)) (not (member (char line begin) '(#\A #\I))))
469              (grab begin i))
470            (setf begin nil
471                  maybe-begin t))
472           ((and begin (not (find (char line i) *symbol-characters*)))
473            ;; Not a symbol: abort
474            (setf begin nil))
475           ((and maybe-begin (not begin) (find (char line i) *symbol-characters*))
476            ;; potential symbol begin at this position
477            (setf begin i
478                  maybe-begin nil))
479           ((find (char line i) *symbol-delimiters*)
480            ;; potential symbol begin after this position
481            (setf maybe-begin t))
482           (t
483            ;; Not reading a symbol, not at potential start of symbol
484            (setf maybe-begin nil)))))))
485
486 (defun texinfo-line (line)
487   "Format symbols in LINE texinfo-style: either as code or as
488 variables if the symbol in question is contained in symbols
489 *TEXINFO-VARIABLES*."
490   (with-output-to-string (result)
491     (let ((last 0))
492       (dolist (symbol/index (locate-symbols line))
493         (write-string (subseq line last (first symbol/index)) result)
494         (let ((symbol-name (apply #'subseq line symbol/index)))
495           (format result (if (member symbol-name *texinfo-variables*
496                                      :test #'string=)
497                              "@var{~A}"
498                              "@code{~A}")
499                   (string-downcase symbol-name)))
500         (setf last (second symbol/index)))
501       (write-string (subseq line last) result))))
502
503 ;;; lisp sections
504
505 (defun lisp-section-p (line line-number lines)
506   "Returns T if the given LINE looks like start of lisp code --
507 ie. if it starts with whitespace followed by a paren or
508 semicolon, and the previous line is empty"
509   (let ((offset (indentation line)))
510     (and offset
511          (plusp offset)
512          (find (find-if-not #'whitespacep line) "(;")
513          (empty-p (1- line-number) lines))))
514
515 (defun collect-lisp-section (lines line-number)
516   (flet ((maybe-line (index)
517            (and (< index (length lines)) (svref lines index))))
518     (let ((lisp (loop for index = line-number then (1+ index)
519                       for line = (maybe-line index)
520                       while (or (indentation line)
521                                 ;; Allow empty lines in middle of lisp sections.
522                                 (let ((next (1+ index)))
523                                   (lisp-section-p (maybe-line next) next lines)))
524                       collect line)))
525      (values (length lisp) `("@lisp" ,@lisp "@end lisp")))))
526
527 ;;; itemized sections
528
529 (defun maybe-itemize-offset (line)
530   "Return NIL or the indentation offset if LINE looks like it starts
531 an item in an itemization."
532   (let* ((offset (indentation line))
533          (char (when offset (char line offset))))
534     (and offset
535          (member char *itemize-start-characters* :test #'char=)
536          (char= #\Space (find-if-not (lambda (c) (char= c char))
537                                      line :start offset))
538          offset)))
539
540 (defun collect-maybe-itemized-section (lines starting-line)
541   ;; Return index of next line to be processed outside
542   (let ((this-offset (maybe-itemize-offset (svref lines starting-line)))
543         (result nil)
544         (lines-consumed 0))
545     (loop for line-number from starting-line below (length lines)
546        for line = (svref lines line-number)
547        for indentation = (indentation line)
548        for offset = (maybe-itemize-offset line)
549        do (cond
550             ((not indentation)
551              ;; empty line -- inserts paragraph.
552              (push "" result)
553              (incf lines-consumed))
554             ((and offset (> indentation this-offset))
555              ;; nested itemization -- handle recursively
556              ;; FIXME: tables in itemizations go wrong
557              (multiple-value-bind (sub-lines-consumed sub-itemization)
558                  (collect-maybe-itemized-section lines line-number)
559                (when sub-lines-consumed
560                  (incf line-number (1- sub-lines-consumed)) ; +1 on next loop
561                  (incf lines-consumed sub-lines-consumed)
562                  (setf result (nconc (nreverse sub-itemization) result)))))
563             ((and offset (= indentation this-offset))
564              ;; start of new item
565              (push (format nil "@item ~A"
566                            (texinfo-line (subseq line (1+ offset))))
567                    result)
568              (incf lines-consumed))
569             ((and (not offset) (> indentation this-offset))
570              ;; continued item from previous line
571              (push (texinfo-line line) result)
572              (incf lines-consumed))
573             (t
574              ;; end of itemization
575              (loop-finish))))
576     ;; a single-line itemization isn't.
577     (if (> (count-if (lambda (line) (> (length line) 0)) result) 1)
578         (values lines-consumed `("@itemize" ,@(reverse result) "@end itemize"))
579         nil)))
580
581 ;;; table sections
582
583 (defun tabulation-body-p (offset line-number lines)
584   (when (< line-number (length lines))
585     (let ((offset2 (indentation (svref lines line-number))))
586       (and offset2 (< offset offset2)))))
587
588 (defun tabulation-p (offset line-number lines direction)
589   (let ((step  (ecase direction
590                  (:backwards (1- line-number))
591                  (:forwards (1+ line-number)))))
592     (when (and (plusp line-number) (< line-number (length lines)))
593       (and (eql offset (indentation (svref lines line-number)))
594            (or (when (eq direction :backwards)
595                  (empty-p step lines))
596                (tabulation-p offset step lines direction)
597                (tabulation-body-p offset step lines))))))
598
599 (defun maybe-table-offset (line-number lines)
600   "Return NIL or the indentation offset if LINE looks like it starts
601 an item in a tabulation. Ie, if it is (1) indented, (2) preceded by an
602 empty line, another tabulation label, or a tabulation body, (3) and
603 followed another tabulation label or a tabulation body."
604   (let* ((line (svref lines line-number))
605          (offset (indentation line))
606          (prev (1- line-number))
607          (next (1+ line-number)))
608     (when (and offset (plusp offset))
609       (and (or (empty-p prev lines)
610                (tabulation-body-p offset prev lines)
611                (tabulation-p offset prev lines :backwards))
612            (or (tabulation-body-p offset next lines)
613                (tabulation-p offset next lines :forwards))
614            offset))))
615
616 ;;; FIXME: This and itemization are very similar: could they share
617 ;;; some code, mayhap?
618
619 (defun collect-maybe-table-section (lines starting-line)
620   ;; Return index of next line to be processed outside
621   (let ((this-offset (maybe-table-offset starting-line lines))
622         (result nil)
623         (lines-consumed 0))
624     (loop for line-number from starting-line below (length lines)
625           for line = (svref lines line-number)
626           for indentation = (indentation line)
627           for offset = (maybe-table-offset line-number lines)
628           do (cond
629                ((not indentation)
630                 ;; empty line -- inserts paragraph.
631                 (push "" result)
632                 (incf lines-consumed))
633                ((and offset (= indentation this-offset))
634                 ;; start of new item, or continuation of previous item
635                 (if (and result (search "@item" (car result) :test #'char=))
636                     (push (format nil "@itemx ~A" (texinfo-line line))
637                           result)
638                     (progn
639                       (push "" result)
640                       (push (format nil "@item ~A" (texinfo-line line))
641                             result)))
642                 (incf lines-consumed))
643                ((> indentation this-offset)
644                 ;; continued item from previous line
645                 (push (texinfo-line line) result)
646                 (incf lines-consumed))
647                (t
648                 ;; end of itemization
649                 (loop-finish))))
650      ;; a single-line table isn't.
651     (if (> (count-if (lambda (line) (> (length line) 0)) result) 1)
652         (values lines-consumed
653                 `("" "@table @emph" ,@(reverse result) "@end table" ""))
654         nil)))
655
656 ;;; section markup
657
658 (defmacro with-maybe-section (index &rest forms)
659   `(multiple-value-bind (count collected) (progn ,@forms)
660     (when count
661       (dolist (line collected)
662         (write-line line *texinfo-output*))
663       (incf ,index (1- count)))))
664
665 (defun write-texinfo-string (string &optional lambda-list)
666   "Try to guess as much formatting for a raw docstring as possible."
667   (let ((*texinfo-variables* (flatten lambda-list))
668         (lines (string-lines (escape-for-texinfo string nil))))
669       (loop for line-number from 0 below (length lines)
670             for line = (svref lines line-number)
671             do (cond
672                  ((with-maybe-section line-number
673                     (and (lisp-section-p line line-number lines)
674                          (collect-lisp-section lines line-number))))
675                  ((with-maybe-section line-number
676                     (and (maybe-itemize-offset line)
677                          (collect-maybe-itemized-section lines line-number))))
678                  ((with-maybe-section line-number
679                     (and (maybe-table-offset line-number lines)
680                          (collect-maybe-table-section lines line-number))))
681                  (t
682                   (write-line (texinfo-line line) *texinfo-output*))))))
683
684 ;;;; texinfo formatting tools
685
686 (defun hide-superclass-p (class-name super-name)
687   (let ((super-package (symbol-package super-name)))
688     (or
689      ;; KLUDGE: We assume that we don't want to advertise internal
690      ;; classes in CP-lists, unless the symbol we're documenting is
691      ;; internal as well.
692      (and (member super-package #.'(mapcar #'find-package *undocumented-packages*))
693           (not (eq super-package (symbol-package class-name))))
694      ;; KLUDGE: We don't generally want to advertise SIMPLE-ERROR or
695      ;; SIMPLE-CONDITION in the CPLs of conditions that inherit them
696      ;; simply as a matter of convenience. The assumption here is that
697      ;; the inheritance is incidental unless the name of the condition
698      ;; begins with SIMPLE-.
699      (and (member super-name '(simple-error simple-condition))
700           (let ((prefix "SIMPLE-"))
701             (mismatch prefix (string class-name) :end2 (length prefix)))
702           t ; don't return number from MISMATCH
703           ))))
704
705 (defun hide-slot-p (symbol slot)
706   ;; FIXME: There is no pricipal reason to avoid the slot docs fo
707   ;; structures and conditions, but their DOCUMENTATION T doesn't
708   ;; currently work with them the way we'd like.
709   (not (and (typep (find-class symbol nil) 'standard-class)
710             (docstring slot t))))
711
712 (defun texinfo-anchor (doc)
713   (format *texinfo-output* "@anchor{~A}~%" (node-name doc)))
714
715 ;;; KLUDGE: &AUX *PRINT-PRETTY* here means "no linebreaks please"
716 (defun texinfo-begin (doc &aux *print-pretty*)
717   (let ((kind (get-kind doc)))
718     (format *texinfo-output* "@~A {~:(~A~)} ~(~A~@[ ~{~A~^ ~}~]~)~%"
719             (case kind
720               ((package constant variable)
721                "defvr")
722               ((structure class condition type)
723                "deftp")
724               (t
725                "deffn"))
726             (map 'string (lambda (char) (if (eql char #\-) #\Space char)) (string kind))
727             (title-name doc)
728             ;; &foo would be amusingly bold in the pdf thanks to TeX/Texinfo
729             ;; interactions,so we escape the ampersand -- amusingly for TeX.
730             ;; sbcl.texinfo defines macros that expand @&key and friends to &key.
731             (mapcar (lambda (name)
732                       (if (member name lambda-list-keywords)
733                           (format nil "@~A" name)
734                           name))
735                     (lambda-list doc)))))
736
737 (defun texinfo-inferred-body (doc)
738   (when (member (get-kind doc) '(class structure condition))
739     (let ((name (get-name doc)))
740       ;; class precedence list
741       (format *texinfo-output* "Class precedence list: @code{~(~{@lw{~A}~^, ~}~)}~%~%"
742               (remove-if (lambda (class)  (hide-superclass-p name class))
743                          (mapcar #'class-name (ensure-class-precedence-list (find-class name)))))
744       ;; slots
745       (let ((slots (remove-if (lambda (slot) (hide-slot-p name slot))
746                               (class-direct-slots (find-class name)))))
747         (when slots
748           (format *texinfo-output* "Slots:~%@itemize~%")
749           (dolist (slot slots)
750             (format *texinfo-output*
751                     "@item ~(@code{~A}~#[~:; --- ~]~
752                       ~:{~2*~@[~2:*~A~P: ~{@code{@w{~S}}~^, ~}~]~:^; ~}~)~%~%"
753                     (slot-definition-name slot)
754                     (remove
755                      nil
756                      (mapcar
757                       (lambda (name things)
758                         (if things
759                             (list name (length things) things)))
760                       '("initarg" "reader"  "writer")
761                       (list
762                        (slot-definition-initargs slot)
763                        (slot-definition-readers slot)
764                        (slot-definition-writers slot)))))
765             ;; FIXME: Would be neater to handler as children
766             (write-texinfo-string (docstring slot t)))
767           (format *texinfo-output* "@end itemize~%~%"))))))
768
769 (defun texinfo-body (doc)
770   (write-texinfo-string (get-string doc)))
771
772 (defun texinfo-end (doc)
773   (write-line (case (get-kind doc)
774                 ((package variable constant) "@end defvr")
775                 ((structure type class condition) "@end deftp")
776                 (t "@end deffn"))
777               *texinfo-output*))
778
779 (defun write-texinfo (doc)
780   "Writes TexInfo for a DOCUMENTATION instance to *TEXINFO-OUTPUT*."
781   (texinfo-anchor doc)
782   (texinfo-begin 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 write-package-macro (package)
832   (let* ((package-name (package-shortest-name package))
833          (macro-name (package-macro-name package)))
834     (write-packageish-macro package-name macro-name)))
835
836 (defun write-packageish-macro (package-name macro-name)
837   ;; a word of explanation about the iftex branch here is probably
838   ;; warranted.  The package information should be present for
839   ;; clarity, because these produce body text as well as index
840   ;; entries (though in info output it's more important to use a
841   ;; very restricted character set because the info reader parses
842   ;; the link, and colon is a special character).  In TeX output we
843   ;; make the package name unconditionally small, and arrange such
844   ;; that the start of the symbol name is at a constant horizontal
845   ;; offset, that offset being such that the longest package names
846   ;; have the "sb-" extending into the left margin.  (At the moment,
847   ;; the length of the longest package name, sb-concurrency, is
848   ;; hard-coded).
849   (format *texinfo-output* "~
850 @iftex
851 @macro ~A{name}
852 {@smallertt@phantom{concurrency:}~@[@llap{~(~A~):}~]}\\name\\
853 @end macro
854 @end iftex
855 @ifinfo
856 @macro ~2:*~A{name}
857 \\name\\
858 @end macro
859 @end ifinfo
860 @ifnottex
861 @ifnotinfo
862 @macro ~:*~A{name}
863 \\name\\ ~@[[~(~A~)]~]
864 @end macro
865 @end ifnotinfo
866 @end ifnottex~%"
867           macro-name package-name))
868
869 (defun generate-includes (directory &rest packages)
870   "Create files in `directory' containing Texinfo markup of all
871 docstrings of each exported symbol in `packages'. `directory' is
872 created if necessary. If you supply a namestring that doesn't end in a
873 slash, you lose. The generated files are of the form
874 \"<doc-type>_<packagename>_<symbol-name>.texinfo\" and can be included
875 via @include statements. Texinfo syntax-significant characters are
876 escaped in symbol names, but if a docstring contains invalid Texinfo
877 markup, you lose."
878   (handler-bind ((warning #'muffle-warning))
879     (let ((directory (merge-pathnames (pathname directory))))
880       (ensure-directories-exist directory)
881       (dolist (package packages)
882         (dolist (doc (collect-documentation (find-package package)))
883           (with-texinfo-file (merge-pathnames (include-pathname doc) directory)
884             (write-texinfo doc))))
885       (with-texinfo-file (merge-pathnames "package-macros.texinfo" directory)
886         (dolist (package packages)
887           (write-package-macro package))
888         (write-packageish-macro nil "nopkg"))
889       directory)))
890
891 (defun document-package (package &optional filename)
892   "Create a file containing all available documentation for the
893 exported symbols of `package' in Texinfo format. If `filename' is not
894 supplied, a file \"<packagename>.texinfo\" is generated.
895
896 The definitions can be referenced using Texinfo statements like
897 @ref{<doc-type>_<packagename>_<symbol-name>.texinfo}. Texinfo
898 syntax-significant characters are escaped in symbol names, but if a
899 docstring contains invalid Texinfo markup, you lose."
900   (handler-bind ((warning #'muffle-warning))
901     (let* ((package (find-package package))
902            (filename (or filename (make-pathname
903                                    :name (string-downcase (package-name package))
904                                    :type "texinfo")))
905            (docs (sort (collect-documentation package) #'documentation<)))
906       (with-texinfo-file filename
907         (dolist (doc docs)
908           (write-texinfo doc)))
909       filename)))