docgen.rst 13 KB

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