docgen.rst 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. ===================================
  2. Nim DocGen Tools Guide
  3. ===================================
  4. :Author: Erik O'Leary
  5. :Version: |nimversion|
  6. .. contents::
  7. Introduction
  8. ============
  9. This document describes the `documentation generation tools`:idx: built into
  10. the `Nim compiler <nimc.html>`_, which can generate HTML and JSON output
  11. from input .nim files and projects, as well as HTML and LaTeX from input RST
  12. (reStructuredText) files. The output documentation will include module
  13. dependencies (``import``), any top-level documentation comments (##), and
  14. exported symbols (*), including procedures, types, and variables.
  15. Documentation Comments
  16. ----------------------
  17. Any comments which are preceded by a double-hash (##), are interpreted as
  18. documentation. Comments are parsed as RST (see `reference
  19. <http://docutils.sourceforge.net/docs/user/rst/quickref.html>`_), providing
  20. Nim module authors the ability to easily generate richly formatted
  21. documentation with only their well-documented code.
  22. Example:
  23. .. code-block:: nim
  24. type Person* = object
  25. ## This type contains a description of a person
  26. name: string
  27. age: int
  28. Outputs::
  29. Person* = object
  30. name: string
  31. age: int
  32. This type contains a description of a person
  33. Field documentation comments can be added to fields like so:
  34. .. code-block:: nim
  35. var numValues: int ## \
  36. ## `numValues` stores the number of values
  37. Note that without the `*` following the name of the type, the documentation for
  38. this type would not be generated. Documentation will only be generated for
  39. *exported* types/procedures/etc.
  40. Nim file input
  41. -----------------
  42. The following examples will generate documentation for the below contrived
  43. *Nim* module, aptly named 'sample.nim'
  44. sample.nim:
  45. .. code-block:: nim
  46. ## This module is a sample.
  47. import strutils
  48. proc helloWorld*(times: int) =
  49. ## Takes an integer and outputs
  50. ## as many "hello world!"s
  51. for i in 0 .. times-1:
  52. echo "hello world!"
  53. helloWorld(5)
  54. Document Types
  55. ==============
  56. HTML
  57. ----
  58. Generation of HTML documents is done via both the ``doc`` and ``doc2``
  59. commands. These command take either a single .nim file, outputting a single
  60. .html file with the same base filename, or multiple .nim files, outputting
  61. multiple .html files and, optionally, an index file.
  62. The ``doc`` command::
  63. nim doc sample
  64. Partial Output::
  65. ...
  66. proc helloWorld*(times: int)
  67. ...
  68. Output can be viewed in full here: `docgen_sample.html <docgen_sample.html>`_.
  69. The next command, called ``doc2``, is very similar to the ``doc`` command, but
  70. will be run after the compiler performs semantic checking on the input nim
  71. module(s), which allows it to process macros.
  72. The ``doc2`` command::
  73. nim doc2 sample
  74. Partial Output::
  75. ...
  76. proc helloWorld(times: int) {.raises: [], tags: [].}
  77. ...
  78. The full output can be seen here: `docgen_sample2.html <docgen_sample2.html>`_.
  79. As you can see, the tool has extracted additional information provided to it by
  80. the compiler beyond what the ``doc`` command provides, such as pragmas attached
  81. implicitly by the compiler. This type of information is not available from
  82. looking at the AST (Abstract Syntax Tree) prior to semantic checking, as the
  83. ``doc`` command does.
  84. JSON
  85. ----
  86. Generation of JSON documents is done via the ``jsondoc`` command. This command
  87. takes in a .nim file, and outputs a .json file with the same base filename.
  88. Note that this tool is built off of the ``doc`` command, and therefore is
  89. performed before semantic checking.
  90. The ``jsondoc`` command::
  91. nim jsondoc sample
  92. Output::
  93. [
  94. {
  95. "comment": "This module is a sample."
  96. },
  97. {
  98. "name": "helloWorld",
  99. "type": "skProc",
  100. "description": "Takes an integer and outputs as many &quot;hello world!&quot;s",
  101. "code": "proc helloWorld*(times: int)"
  102. }
  103. ]
  104. Related Options
  105. ===============
  106. Project switch
  107. --------------
  108. ::
  109. nim doc2 --project filename.nim
  110. This will recursively generate documentation of all nim modules imported
  111. into the input module, including system modules. Be careful with this command,
  112. as it may end up sprinkling html files all over your filesystem!
  113. Index switch
  114. ------------
  115. ::
  116. nim doc2 --index:on filename.nim
  117. This will generate an index of all the exported symbols in the input Nim
  118. module, and put it into a neighboring file with the extension of ``.idx``. The
  119. index file is line oriented (newlines have to be escaped). Each line
  120. represents a tab separated record of several columns, the first two mandatory,
  121. the rest optional. See the `Index (idx) file format`_ section for details.
  122. Once index files have been generated for one or more modules, the Nim
  123. compiler command ``buildIndex directory`` can be run to go over all the index
  124. files in the specified directory to generate a `theindex.html <theindex.html>`_
  125. file.
  126. See source switch
  127. -----------------
  128. ::
  129. nim doc2 --docSeeSrcUrl:txt filename.nim
  130. When you pass the ``docSeeSrcUrl`` switch to docgen, after each documented item
  131. in your source code the hyper link *See source* will appear pointing to the
  132. implementation of that item on a GitHub repository. You can click the link to
  133. see the implementation of the item.
  134. If you want to reuse this feature in your own documentation you will have to
  135. modify ``config/nimdoc.cfg`` to contain a ``doc.item.seesrc`` value with a
  136. hyper link to your own code repository. As you will see by the comments in that
  137. file, the value ``txt`` passed on the command line will be used in the HTML
  138. template along others like ``$path`` and ``$line``.
  139. In the case of Nim's own documentation, the ``txt`` value is just a commit
  140. hash to append to a formatted URL to https://github.com/Araq/Nim. The
  141. ``tools/nimweb.nim`` helper queries the current git commit hash during doc
  142. generation, but since you might be working on an unpublished repository, it
  143. also allows specifying a ``githash`` value in ``web/website.ini`` to force a
  144. specific commit in the output.
  145. Other Input Formats
  146. ===================
  147. The *Nim compiler* also has support for RST (reStructuredText) files with
  148. the ``rst2html`` and ``rst2tex`` commands. Documents like this one are
  149. initially written in a dialect of RST which adds support for nim sourcecode
  150. highlighting with the ``.. code-block:: nim`` prefix. ``code-block`` also
  151. supports highlighting of C++ and some other c-like languages.
  152. Usage::
  153. nim rst2html docgen.txt
  154. Output::
  155. You're reading it!
  156. The input can be viewed here `docgen.txt <docgen.txt>`_. The ``rst2tex``
  157. command is invoked identically to ``rst2html``, but outputs a .tex file instead
  158. of .html.
  159. HTML anchor generation
  160. ======================
  161. When you run the ``rst2html`` command, all sections in the RST document will
  162. get an anchor you can hyper link to. Usually you can guess the anchor lower
  163. casing the section title and replacing spaces with dashes, and in any case you
  164. can get it from the table of contents. But when you run the ``doc`` or ``doc2``
  165. commands to generate API documentation, some symbol get one or two anchors at
  166. the same time: a numerical identifier, or a plain name plus a complex name.
  167. The numerical identifier is just a random number. The number gets assigned
  168. according to the section and position of the symbol in the file being processed
  169. and you should not rely on it being constant: if you add or remove a symbol the
  170. numbers may shuffle around.
  171. The plain name of a symbol is a simplified version of its fully exported
  172. signature. Variables or constants have the same plain name symbol as their
  173. complex name. The plain name for procs, templates, and other callable types
  174. will be their unquoted value after removing parameters, return types and
  175. pragmas. The plain name allows short and nice linking of symbols which works
  176. unless you have a module with collisions due to overloading.
  177. If you hyper link a plain name symbol and there are other matches on the same
  178. HTML file, most browsers will go to the first one. To differentiate the rest,
  179. you will need to use the complex name. A complex name for a callable type is
  180. made up from several parts:
  181. (**plain symbol**)(**.type**),(**first param**)?(**,param type**)\*
  182. The first thing to note is that all callable types have at least a comma, even
  183. if they don't have any parameters. If there are parameters, they are
  184. represented by their types and will be comma separated. To the plain symbol a
  185. suffix may be added depending on the type of the callable:
  186. ------------- --------------
  187. Callable type Suffix
  188. ------------- --------------
  189. proc *empty string*
  190. macro ``.m``
  191. method ``.e``
  192. iterator ``.i``
  193. template ``.t``
  194. converter ``.c``
  195. ------------- --------------
  196. The relationship of type to suffix is made by the proc ``complexName`` in the
  197. ``compiler/docgen.nim`` file. Here are some examples of complex names for
  198. symbols in the `system module <system.html>`_.
  199. * ``type SignedInt = int | int8 | int16 | int32 | int64`` **=>**
  200. `#SignedInt <system.html#SignedInt>`_
  201. * ``var globalRaiseHook: proc (e: ref E_Base): bool {.nimcall.}`` **=>**
  202. `#globalRaiseHook <system.html#globalRaiseHook>`_
  203. * ``const NimVersion = "0.0.0"`` **=>**
  204. `#NimVersion <system.html#NimVersion>`_
  205. * ``proc getTotalMem(): int {.rtl, raises: [], tags: [].}`` **=>**
  206. `#getTotalMem, <system.html#getTotalMem,>`_
  207. * ``proc len[T](x: seq[T]): int {.magic: "LengthSeq", noSideEffect.}`` **=>**
  208. `#len,seq[T] <system.html#len,seq[T]>`_
  209. * ``iterator pairs[T](a: seq[T]): tuple[key: int, val: T] {.inline.}`` **=>**
  210. `#pairs.i,seq[T] <system.html#pairs.i,seq[T]>`_
  211. * ``template newException[](exceptn: typedesc; message: string): expr`` **=>**
  212. `#newException.t,typedesc,string
  213. <system.html#newException.t,typedesc,string>`_
  214. Index (idx) file format
  215. =======================
  216. Files with the ``.idx`` extension are generated when you use the `Index
  217. switch`_ along with commands to generate documentation from source or text
  218. files. You can programatically generate indices with the `setIndexTerm()
  219. <rstgen.html#setIndexTerm>`_ and `writeIndexFile()
  220. <rstgen.html#writeIndexFile>`_ procs. The purpose of ``idx`` files is to hold
  221. the interesting symbols and their HTML references so they can be later
  222. concatenated into a big index file with `mergeIndexes()
  223. <rstgen.html#mergeIndexes>`_. This section documents the file format in
  224. detail.
  225. Index files are line oriented and tab separated (newline and tab characters
  226. have to be escaped). Each line represents a record with at least two fields,
  227. but can have up to four (additional columns are ignored). The content of these
  228. columns is:
  229. 1. Mandatory term being indexed. Terms can include quoting according to
  230. Nim's rules (eg. \`^\` like in `the actors module
  231. <actors.html#^,ptr.TChannel[T]>`_).
  232. 2. Base filename plus anchor hyper link (eg.
  233. ``algorithm.html#*,int,SortOrder``).
  234. 3. Optional human readable string to display as hyper link. If the value is not
  235. present or is the empty string, the hyper link will be rendered
  236. using the term. Prefix whitespace indicates that this entry is
  237. not for an API symbol but for a TOC entry.
  238. 4. Optional title or description of the hyper link. Browsers usually display
  239. this as a tooltip after hovering a moment over the hyper link.
  240. The index generation tools try to differentiate between documentation
  241. generated from ``.nim`` files and documentation generated from ``.txt`` or
  242. ``.rst`` files. The former are always closely related to source code and
  243. consist mainly of API entries. The latter are generic documents meant for
  244. human reading.
  245. To differentiate both types (documents and APIs), the index generator will add
  246. to the index of documents an entry with the title of the document. Since the
  247. title is the topmost element, it will be added with a second field containing
  248. just the filename without any HTML anchor. By convention this entry without
  249. anchor is the *title entry*, and since entries in the index file are added as
  250. they are scanned, the title entry will be the first line. The title for APIs
  251. is not present because it can be generated concatenating the name of the file
  252. to the word **Module**.
  253. Normal symbols are added to the index with surrounding whitespaces removed. An
  254. exception to this are table of content (TOC) entries. TOC entries are added to
  255. the index file with their third column having as much prefix spaces as their
  256. level is in the TOC (at least 1 character). The prefix whitespace helps to
  257. filter TOC entries from API or text symbols. This is important because the
  258. amount of spaces is used to replicate the hiearchy for document TOCs in the
  259. final index, and TOC entries found in ``.nim`` files are discarded.
  260. Additional resources
  261. ====================
  262. `Nim Compiler User Guide <nimc.html#command-line-switches>`_
  263. `RST Quick Reference
  264. <http://docutils.sourceforge.net/docs/user/rst/quickref.html>`_
  265. The output for HTML and LaTeX comes from the ``config/nimdoc.cfg`` and
  266. ``config/nimdoc.tex.cfg`` configuration files. You can add and modify these
  267. files to your project to change the look of docgen output.
  268. You can import the `packages/docutils/rstgen module <rstgen.html>`_ in your
  269. programs if you want to reuse the compiler's documentation generation procs.