docgen.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. 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`.
  159. Edit URLs are generated as `href="${url}/tree/${devel}/${path}#L${line}"` by default.
  160. You can edit ``config/nimdoc.cfg`` and modify the ``doc.item.seesrc`` value with a hyperlink to your own code repository.
  161. In the case of Nim's own documentation, the ``commit`` value is just a commit
  162. hash to append to a formatted URL to https://github.com/nim-lang/Nim. The
  163. ``tools/nimweb.nim`` helper queries the current git commit hash during doc
  164. generation, but since you might be working on an unpublished repository, it
  165. also allows specifying a ``githash`` value in ``web/website.ini`` to force a
  166. specific commit in the output.
  167. Other Input Formats
  168. ===================
  169. The *Nim compiler* also has support for RST (reStructuredText) files with
  170. the ``rst2html`` and ``rst2tex`` commands. Documents like this one are
  171. initially written in a dialect of RST which adds support for nim sourcecode
  172. highlighting with the ``.. code-block:: nim`` prefix. ``code-block`` also
  173. supports highlighting of C++ and some other c-like languages.
  174. Usage::
  175. nim rst2html docgen.txt
  176. Output::
  177. You're reading it!
  178. The ``rst2tex`` command is invoked identically to ``rst2html``, but outputs
  179. a .tex file instead of .html.
  180. HTML anchor generation
  181. ======================
  182. When you run the ``rst2html`` command, all sections in the RST document will
  183. get an anchor you can hyperlink to. Usually you can guess the anchor lower
  184. casing the section title and replacing spaces with dashes, and in any case you
  185. can get it from the table of contents. But when you run the ``doc`` or ``doc2``
  186. commands to generate API documentation, some symbol get one or two anchors at
  187. the same time: a numerical identifier, or a plain name plus a complex name.
  188. The numerical identifier is just a random number. The number gets assigned
  189. according to the section and position of the symbol in the file being processed
  190. and you should not rely on it being constant: if you add or remove a symbol the
  191. numbers may shuffle around.
  192. The plain name of a symbol is a simplified version of its fully exported
  193. signature. Variables or constants have the same plain name symbol as their
  194. complex name. The plain name for procs, templates, and other callable types
  195. will be their unquoted value after removing parameters, return types and
  196. pragmas. The plain name allows short and nice linking of symbols which works
  197. unless you have a module with collisions due to overloading.
  198. If you hyperlink a plain name symbol and there are other matches on the same
  199. HTML file, most browsers will go to the first one. To differentiate the rest,
  200. you will need to use the complex name. A complex name for a callable type is
  201. made up from several parts:
  202. (**plain symbol**)(**.type**),(**first param**)?(**,param type**)\*
  203. The first thing to note is that all callable types have at least a comma, even
  204. if they don't have any parameters. If there are parameters, they are
  205. represented by their types and will be comma separated. To the plain symbol a
  206. suffix may be added depending on the type of the callable:
  207. ------------- --------------
  208. Callable type Suffix
  209. ------------- --------------
  210. proc *empty string*
  211. macro ``.m``
  212. method ``.e``
  213. iterator ``.i``
  214. template ``.t``
  215. converter ``.c``
  216. ------------- --------------
  217. The relationship of type to suffix is made by the proc ``complexName`` in the
  218. ``compiler/docgen.nim`` file. Here are some examples of complex names for
  219. symbols in the `system module <system.html>`_.
  220. * ``type SomeSignedInt = int | int8 | int16 | int32 | int64`` **=>**
  221. `#SomeSignedInt <system.html#SomeSignedInt>`_
  222. * ``var globalRaiseHook: proc (e: ref E_Base): bool {.nimcall.}`` **=>**
  223. `#globalRaiseHook <system.html#globalRaiseHook>`_
  224. * ``const NimVersion = "0.0.0"`` **=>**
  225. `#NimVersion <system.html#NimVersion>`_
  226. * ``proc getTotalMem(): int {.rtl, raises: [], tags: [].}`` **=>**
  227. `#getTotalMem, <system.html#getTotalMem>`_
  228. * ``proc len[T](x: seq[T]): int {.magic: "LengthSeq", noSideEffect.}`` **=>**
  229. `#len,seq[T] <system.html#len,seq[T]>`_
  230. * ``iterator pairs[T](a: seq[T]): tuple[key: int, val: T] {.inline.}`` **=>**
  231. `#pairs.i,seq[T] <system.html#pairs.i,seq[T]>`_
  232. * ``template newException[](exceptn: typedesc; message: string;
  233. parentException: ref Exception = nil): untyped`` **=>**
  234. `#newException.t,typedesc,string,ref.Exception
  235. <system.html#newException.t,typedesc,string,ref.Exception>`_
  236. Index (idx) file format
  237. =======================
  238. Files with the ``.idx`` extension are generated when you use the `Index
  239. switch <#related-options-index-switch>`_ along with commands to generate
  240. documentation from source or text files. You can programatically generate
  241. indices with the `setIndexTerm()
  242. <rstgen.html#setIndexTerm,RstGenerator,string,string,string,string,string>`_
  243. and `writeIndexFile() <rstgen.html#writeIndexFile,RstGenerator,string>`_ procs.
  244. The purpose of ``idx`` files is to hold the interesting symbols and their HTML
  245. references so they can be later concatenated into a big index file with
  246. `mergeIndexes() <rstgen.html#mergeIndexes,string>`_. This section documents
  247. the file format in detail.
  248. Index files are line oriented and tab separated (newline and tab characters
  249. have to be escaped). Each line represents a record with at least two fields,
  250. but can have up to four (additional columns are ignored). The content of these
  251. columns is:
  252. 1. Mandatory term being indexed. Terms can include quoting according to
  253. Nim's rules (eg. \`^\`).
  254. 2. Base filename plus anchor hyperlink (eg.
  255. ``algorithm.html#*,int,SortOrder``).
  256. 3. Optional human readable string to display as hyperlink. If the value is not
  257. present or is the empty string, the hyperlink will be rendered
  258. using the term. Prefix whitespace indicates that this entry is
  259. not for an API symbol but for a TOC entry.
  260. 4. Optional title or description of the hyperlink. Browsers usually display
  261. this as a tooltip after hovering a moment over the hyperlink.
  262. The index generation tools try to differentiate between documentation
  263. generated from ``.nim`` files and documentation generated from ``.txt`` or
  264. ``.rst`` files. The former are always closely related to source code and
  265. consist mainly of API entries. The latter are generic documents meant for
  266. human reading.
  267. To differentiate both types (documents and APIs), the index generator will add
  268. to the index of documents an entry with the title of the document. Since the
  269. title is the topmost element, it will be added with a second field containing
  270. just the filename without any HTML anchor. By convention this entry without
  271. anchor is the *title entry*, and since entries in the index file are added as
  272. they are scanned, the title entry will be the first line. The title for APIs
  273. is not present because it can be generated concatenating the name of the file
  274. to the word **Module**.
  275. Normal symbols are added to the index with surrounding whitespaces removed. An
  276. exception to this are table of content (TOC) entries. TOC entries are added to
  277. the index file with their third column having as much prefix spaces as their
  278. level is in the TOC (at least 1 character). The prefix whitespace helps to
  279. filter TOC entries from API or text symbols. This is important because the
  280. amount of spaces is used to replicate the hiearchy for document TOCs in the
  281. final index, and TOC entries found in ``.nim`` files are discarded.
  282. Additional resources
  283. ====================
  284. `Nim Compiler User Guide <nimc.html#compiler-usage-command-line-switches>`_
  285. `RST Quick Reference
  286. <http://docutils.sourceforge.net/docs/user/rst/quickref.html>`_
  287. The output for HTML and LaTeX comes from the ``config/nimdoc.cfg`` and
  288. ``config/nimdoc.tex.cfg`` configuration files. You can add and modify these
  289. files to your project to change the look of docgen output.
  290. You can import the `packages/docutils/rstgen module <rstgen.html>`_ in your
  291. programs if you want to reuse the compiler's documentation generation procs.