docgen.rst 13 KB

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