docgen.rst 14 KB

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