contributing.rst 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593
  1. ============
  2. Contributing
  3. ============
  4. .. contents::
  5. Contributing happens via "Pull requests" (PR) on github. Every PR needs to be
  6. reviewed before it can be merged and the Continuous Integration should be green.
  7. The PR has to be approved by two core developers or by Araq.
  8. Writing tests
  9. =============
  10. There are 4 types of tests:
  11. 1. ``runnableExamples`` documentation comment tests, ran by ``nim doc mymod.nim``
  12. These end up in documentation and ensure documentation stays in sync with code.
  13. 2. separate test files, e.g.: ``tests/stdlib/tos.nim``.
  14. In nim repo, `testament` (see below) runs all `$nim/tests/*/t*.nim` test files;
  15. for nimble packages, see https://github.com/nim-lang/nimble#tests.
  16. 3. (deprecated) tests in ``when isMainModule:`` block, ran by ``nim r mymod.nim``.
  17. ``nimble test`` can run those in nimble packages when specified in a
  18. `task "test"`.
  19. 4. (not preferred) `.. code-block:: nim` RST snippets; these should only be used in rst sources,
  20. in nim sources `runnableExamples` should now always be preferred to those for
  21. several reasons (cleaner syntax, syntax highlights, batched testing, and
  22. `rdoccmd` allows customization).
  23. Not all the tests follow the convention here, feel free to change the ones
  24. that don't. Always leave the code cleaner than you found it.
  25. Stdlib
  26. ------
  27. Each stdlib module (anything under ``lib/``, e.g. ``lib/pure/os.nim``) should
  28. preferably have a corresponding separate test file, e.g. `tests/stdlib/tos.nim`.
  29. The old convention was to add a ``when isMainModule:`` block in the source file,
  30. which only gets executed when the tester is building the file.
  31. Each test should be in a separate ``block:`` statement, such that
  32. each has its own scope. Use boolean conditions and ``doAssert`` for the
  33. testing by itself, don't rely on echo statements or similar; in particular, avoid
  34. things like `echo "done"`.
  35. Sample test:
  36. .. code-block:: nim
  37. block: # bug #1234
  38. static: doAssert 1+1 == 2
  39. block: # bug #1235
  40. var seq2D = newSeqWith(4, newSeq[bool](2))
  41. seq2D[0][0] = true
  42. seq2D[1][0] = true
  43. seq2D[0][1] = true
  44. doAssert seq2D == @[@[true, true], @[true, false],
  45. @[false, false], @[false, false]]
  46. # doAssert with `not` can now be done as follows:
  47. doAssert not (1 == 2)
  48. Always refer to a GitHub issue using the following exact syntax: `bug #1234` as shown
  49. above, so that it's consistent and easier to search or for tooling. Some browser
  50. extensions (e.g. https://github.com/sindresorhus/refined-github) will even turn those
  51. in clickable links when it works.
  52. Rationale for using a separate test file instead of `when isMainModule:` block:
  53. * allows custom compiler flags or testing options (see details below)
  54. * faster CI since they can be joined in `megatest` (combined into a single test)
  55. * avoids making the parser do un-necessary work when a source file is merely imported
  56. * avoids mixing source and test code when reporting line of code statistics or code coverage
  57. Compiler
  58. --------
  59. The tests for the compiler use a testing tool called ``testament``. They are all
  60. located in ``tests/`` (e.g.: ``tests/destructor/tdestructor3.nim``).
  61. Each test has its own file. All test files are prefixed with ``t``. If you want
  62. to create a file for import into another test only, use the prefix ``m``.
  63. At the beginning of every test is the expected behavior of the test.
  64. Possible keys are:
  65. - ``cmd``: A compilation command template e.g. ``nim $target --threads:on $options $file``
  66. - ``output``: The expected output (stdout + stderr), most likely via ``echo``
  67. - ``exitcode``: Exit code of the test (via ``exit(number)``)
  68. - ``errormsg``: The expected compiler error message
  69. - ``file``: The file the errormsg was produced at
  70. - ``line``: The line the errormsg was produced at
  71. For a full spec, see here: ``testament/specs.nim``
  72. An example of a test:
  73. .. code-block:: nim
  74. discard """
  75. errormsg: "type mismatch: got (PTest)"
  76. """
  77. type
  78. PTest = ref object
  79. proc test(x: PTest, y: int) = nil
  80. var buf: PTest
  81. buf.test()
  82. Running tests
  83. =============
  84. You can run the tests with
  85. ::
  86. ./koch tests
  87. which will run a good subset of tests. Some tests may fail. If you
  88. only want to see the output of failing tests, go for
  89. ::
  90. ./koch tests --failing all
  91. You can also run only a single category of tests. A category is a subdirectory
  92. in the ``tests`` directory. There are a couple of special categories; for a
  93. list of these, see ``testament/categories.nim``, at the bottom.
  94. ::
  95. ./koch tests c lib # compiles/runs stdlib modules, including `isMainModule` tests
  96. ./koch tests c megatest # runs a set of tests that can be combined into 1
  97. To run a single test:
  98. ::
  99. ./koch test run <category>/<name> # e.g.: tuples/ttuples_issues
  100. ./koch test run tests/stdlib/tos.nim # can also provide relative path
  101. For reproducible tests (to reproduce an environment more similar to the one
  102. run by Continuous Integration on travis/appveyor), you may want to disable your
  103. local configuration (e.g. in ``~/.config/nim/nim.cfg``) which may affect some
  104. tests; this can also be achieved by using
  105. ``export XDG_CONFIG_HOME=pathtoAlternateConfig`` before running ``./koch``
  106. commands.
  107. Comparing tests
  108. ===============
  109. Test failures can be grepped using ``Failure:``.
  110. The tester can compare two test runs. First, you need to create a
  111. reference test. You'll also need to the commit id, because that's what
  112. the tester needs to know in order to compare the two.
  113. ::
  114. git checkout devel
  115. DEVEL_COMMIT=$(git rev-parse HEAD)
  116. ./koch tests
  117. Then switch over to your changes and run the tester again.
  118. ::
  119. git checkout your-changes
  120. ./koch tests
  121. Then you can ask the tester to create a ``testresults.html`` which will
  122. tell you if any new tests passed/failed.
  123. ::
  124. ./koch tests --print html $DEVEL_COMMIT
  125. Deprecation
  126. ===========
  127. Backward compatibility is important, so instead of a rename you need to deprecate
  128. the old name and introduce a new name:
  129. .. code-block:: nim
  130. # for routines (proc/template/macro/iterator) and types:
  131. proc oldProc(a: int, b: float): bool {.deprecated:
  132. "deprecated since v1.2.3; use `newImpl: string -> int` instead".} = discard
  133. # for (const/var/let/fields) the msg is not yet supported:
  134. const Foo {.deprecated.} = 1
  135. # for enum types, you can deprecate the type or some elements
  136. # (likewise with object types and their fields):
  137. type Bar {.deprecated.} = enum bar0, bar1
  138. type Barz = enum baz0, baz1 {.deprecated.}, baz2
  139. See also `Deprecated <manual.html#pragmas-deprecated-pragma>`_
  140. pragma in the manual.
  141. Documentation
  142. =============
  143. When contributing new procs, be sure to add documentation, especially if
  144. the proc is public. Even private procs benefit from documentation and can be
  145. viewed using ``nim doc --docInternal foo.nim``.
  146. Documentation begins on the line
  147. following the ``proc`` definition, and is prefixed by ``##`` on each line.
  148. Runnable code examples are also encouraged, to show typical behavior with a few
  149. test cases (typically 1 to 3 ``assert`` statements, depending on complexity).
  150. These ``runnableExamples`` are automatically run by ``nim doc mymodule.nim``
  151. as well as ``testament`` and guarantee they stay in sync.
  152. .. code-block:: nim
  153. proc addBar*(a: string): string =
  154. ## Adds "Bar" to `a`.
  155. runnableExamples:
  156. assert "baz".addBar == "bazBar"
  157. result = a & "Bar"
  158. See `parentDir <os.html#parentDir,string>`_ example.
  159. The RestructuredText Nim uses has a special syntax for including code snippets
  160. embedded in documentation; these are not run by ``nim doc`` and therefore are
  161. not guaranteed to stay in sync, so ``runnableExamples`` is usually preferred:
  162. .. code-block:: nim
  163. proc someproc*(): string =
  164. ## Return "something"
  165. ##
  166. ## .. code-block::
  167. ## echo someproc() # "something"
  168. result = "something" # single-hash comments do not produce documentation
  169. The ``.. code-block:: nim`` followed by a newline and an indentation instructs the
  170. ``nim doc`` command to produce syntax-highlighted example code with the
  171. documentation (``.. code-block::`` is sufficient from inside a nim module).
  172. When forward declaration is used, the documentation should be included with the
  173. first appearance of the proc.
  174. .. code-block:: nim
  175. proc hello*(): string
  176. ## Put documentation here
  177. proc nothing() = discard
  178. proc hello*(): string =
  179. ## ignore this
  180. echo "hello"
  181. The preferred documentation style is to begin with a capital letter and use
  182. the imperative (command) form. That is, between:
  183. .. code-block:: nim
  184. proc hello*(): string =
  185. ## Return "hello"
  186. result = "hello"
  187. or
  188. .. code-block:: nim
  189. proc hello*(): string =
  190. ## says hello
  191. result = "hello"
  192. the first is preferred.
  193. Best practices
  194. ==============
  195. Note: these are general guidelines, not hard rules; there are always exceptions.
  196. Code reviews can just point to a specific section here to save time and
  197. propagate best practices.
  198. .. _define_needs_prefix:
  199. New `defined(foo)` symbols need to be prefixed by the nimble package name, or
  200. by `nim` for symbols in nim sources (e.g. compiler, standard library). This is
  201. to avoid name conflicts across packages.
  202. .. code-block:: nim
  203. # if in nim sources
  204. when defined(allocStats): discard # bad, can cause conflicts
  205. when defined(nimAllocStats): discard # preferred
  206. # if in a pacakge `cligen`:
  207. when defined(debug): discard # bad, can cause conflicts
  208. when defined(cligenDebug): discard # preferred
  209. .. _noimplicitbool:
  210. Take advantage of no implicit bool conversion
  211. .. code-block:: nim
  212. doAssert isValid() == true
  213. doAssert isValid() # preferred
  214. .. _design_for_mcs:
  215. Design with method call syntax chaining in mind
  216. .. code-block:: nim
  217. proc foo(cond: bool, lines: seq[string]) # bad
  218. proc foo(lines: seq[string], cond: bool) # preferred
  219. # can be called as: `getLines().foo(false)`
  220. .. _avoid_quit:
  221. Use exceptions (including assert / doAssert) instead of ``quit``
  222. rationale: https://forum.nim-lang.org/t/4089
  223. .. code-block:: nim
  224. quit() # bad in almost all cases
  225. doAssert() # preferred
  226. .. _tests_use_doAssert:
  227. Use ``doAssert`` (or ``require``, etc), not ``assert`` in all tests so they'll
  228. be enabled even in release mode (except for tests in ``runnableExamples`` blocks
  229. which for which ``nim doc`` ignores ``-d:release``).
  230. .. code-block:: nim
  231. when isMainModule:
  232. assert foo() # bad
  233. doAssert foo() # preferred
  234. .. _delegate_printing:
  235. Delegate printing to caller: return ``string`` instead of calling ``echo``
  236. rationale: it's more flexible (e.g. allows the caller to call custom printing,
  237. including prepending location info, writing to log files, etc).
  238. .. code-block:: nim
  239. proc foo() = echo "bar" # bad
  240. proc foo(): string = "bar" # preferred (usually)
  241. .. _use_Option:
  242. [Ongoing debate] Consider using Option instead of return bool + var argument,
  243. unless stack allocation is needed (e.g. for efficiency).
  244. .. code-block:: nim
  245. proc foo(a: var Bar): bool
  246. proc foo(): Option[Bar]
  247. .. _use_doAssert_not_echo:
  248. Tests (including in testament) should always prefer assertions over ``echo``,
  249. except when that's not possible. It's more precise, easier for readers and
  250. maintainers to where expected values refer to. See for example
  251. https://github.com/nim-lang/Nim/pull/9335 and https://forum.nim-lang.org/t/4089
  252. .. code-block:: nim
  253. echo foo() # adds a line for testament in `output:` block inside `discard`.
  254. doAssert foo() == [1, 2] # preferred, except when not possible to do so.
  255. The Git stuff
  256. =============
  257. General commit rules
  258. --------------------
  259. 1. Important, critical bugfixes that have a tiny chance of breaking
  260. somebody's code should be backported to the latest stable release
  261. branch (currently 1.4.x) and maybe also all the way back to the 1.0.x branch.
  262. The commit message should contain the tag ``[backport]`` for "backport to all
  263. stable releases" and the tag ``[backport:$VERSION]`` for backporting to the
  264. given $VERSION.
  265. 2. If you introduce changes which affect backward compatibility,
  266. make breaking changes, or have PR which is tagged as ``[feature]``,
  267. the changes should be mentioned in `the changelog
  268. <https://github.com/nim-lang/Nim/blob/devel/changelog.md>`_.
  269. 3. All changes introduced by the commit (diff lines) must be related to the
  270. subject of the commit.
  271. If you change something unrelated to the subject parts of the file, because
  272. your editor reformatted automatically the code or whatever different reason,
  273. this should be excluded from the commit.
  274. *Tip:* Never commit everything as is using ``git commit -a``, but review
  275. carefully your changes with ``git add -p``.
  276. 4. Changes should not introduce any trailing whitespace.
  277. Always check your changes for whitespace errors using ``git diff --check``
  278. or add the following ``pre-commit`` hook:
  279. .. code-block:: sh
  280. #!/bin/sh
  281. git diff --check --cached || exit $?
  282. 5. Describe your commit and use your common sense.
  283. Example commit message:
  284. ``Fixes #123; refs #124``
  285. indicates that issue ``#123`` is completely fixed (GitHub may automatically
  286. close it when the PR is committed), wheres issue ``#124`` is referenced
  287. (e.g.: partially fixed) and won't close the issue when committed.
  288. 6. PR body (not just PR title) should contain references to fixed/referenced github
  289. issues, e.g.: `fix #123` or `refs #123`. This is so that you get proper cross
  290. referencing from linked issue to the PR (github won't make those links with just
  291. PR title, and commit messages aren't always sufficient to ensure that, e.g.
  292. can't be changed after a PR is merged).
  293. 7. Commits should be always be rebased against devel (so a fast forward
  294. merge can happen)
  295. e.g.: use ``git pull --rebase origin devel``. This is to avoid messing up
  296. git history.
  297. Exceptions should be very rare: when rebase gives too many conflicts, simply
  298. squash all commits using the script shown in
  299. https://github.com/nim-lang/Nim/pull/9356
  300. 8. Do not mix pure formatting changes (e.g. whitespace changes, nimpretty) or
  301. automated changes (e.g. nimfix) with other code changes: these should be in
  302. separate commits (and the merge on GitHub should not squash these into 1).
  303. Continuous Integration (CI)
  304. ---------------------------
  305. 1. Continuous Integration is by default run on every push in a PR; this clogs
  306. the CI pipeline and affects other PR's; if you don't need it (e.g. for WIP or
  307. documentation only changes), add ``[ci skip]`` to your commit message title.
  308. This convention is supported by `Appveyor
  309. <https://www.appveyor.com/docs/how-to/filtering-commits/#skip-directive-in-commit-message>`_
  310. and `Travis <https://docs.travis-ci.com/user/customizing-the-build/#skipping-a-build>`_.
  311. 2. Consider enabling CI (azure, GitHub actions and builds.sr.ht) in your own Nim fork, and
  312. waiting for CI to be green in that fork (fixing bugs as needed) before
  313. opening your PR in the original Nim repo, so as to reduce CI congestion. Same
  314. applies for updates on a PR: you can test commits on a separate private
  315. branch before updating the main PR.
  316. Debugging CI failures, flaky tests, etc
  317. ---------------------------------------
  318. 1. First check the CI logs and search for `FAIL` to find why CI failed; if the
  319. failure seems related to your PR, try to fix the code instead of restarting CI.
  320. 2. If CI failure seems unrelated to your PR, it could be caused by a flaky test.
  321. File a bug for it if it isn't already reported. A PR push (or opening/closing PR)
  322. will re-trigger all CI jobs (even successful ones, which can be wasteful). Instead,
  323. follow these instructions to only restart the jobs that failed:
  324. * Azure: if on your own fork, it's possible from inside azure console
  325. (e.g. `dev.azure.com/username/username/_build/results?buildId=1430&view=results`) via `rerun failed jobs` on top.
  326. If either on you own fork or in Nim repo, it's possible from inside GitHub UI
  327. under checks tab, see https://github.com/timotheecour/Nim/issues/211#issuecomment-629751569
  328. * GitHub actions: under "Checks" tab, click "Re-run jobs" in the right.
  329. * builds.sr.ht: create a sourcehut account so you can restart a PR job as illustrated
  330. Code reviews
  331. ------------
  332. 1. Whenever possible, use GitHub's new 'Suggested change' in code reviews, which
  333. saves time explaining the change or applying it; see also
  334. https://forum.nim-lang.org/t/4317
  335. 2. When reviewing large diffs that may involve code moving around, GitHub's interface
  336. doesn't help much as it doesn't highlight moves. Instead, you can use something
  337. like this, see visual results `here <https://github.com/nim-lang/Nim/pull/10431#issuecomment-456968196>`_:
  338. .. code-block:: sh
  339. git fetch origin pull/10431/head && git checkout FETCH_HEAD
  340. git diff --color-moved-ws=allow-indentation-change --color-moved=blocks HEAD^
  341. 3. In addition, you can view GitHub-like diffs locally to identify what was changed
  342. within a code block using `diff-highlight` or `diff-so-fancy`, e.g.:
  343. .. code-block:: sh
  344. # put this in ~/.gitconfig:
  345. [core]
  346. pager = "diff-so-fancy | less -R" # or: use: `diff-highlight`
  347. .. include:: docstyle.rst
  348. Evolving the stdlib
  349. ===================
  350. As outlined in https://github.com/nim-lang/RFCs/issues/173 there are a couple
  351. of guidelines about what should go into the stdlib, what should be added and
  352. what eventually should be removed.
  353. What the compiler itself needs must be part of the stdlib
  354. ---------------------------------------------------------
  355. Maybe in the future the compiler itself can depend on Nimble packages but for
  356. the time being, we strive to have zero dependencies in the compiler as the
  357. compiler is the root of the bootstrapping process and is also used to build
  358. Nimble.
  359. Vocabulary types must be part of the stdlib
  360. -------------------------------------------
  361. These are types most packages need to agree on for better interoperability,
  362. for example ``Option[T]``. This rule also covers the existing collections like
  363. ``Table``, ``CountTable`` etc. "Sorted" containers based on a tree-like data
  364. structure are still missing and should be added.
  365. Time handling, especially the ``Time`` type are also covered by this rule.
  366. Existing, battle-tested modules stay
  367. ------------------------------------
  368. Reason: There is no benefit in moving them around just to fullfill some design
  369. fashion as in "Nim's core MUST BE SMALL". If you don't like an existing module,
  370. don't import it. If a compilation target (e.g. JS) cannot support a module,
  371. document this limitation.
  372. This covers modules like ``os``, ``osproc``, ``strscans``, ``strutils``,
  373. ``strformat``, etc.
  374. Syntactic helpers can start as experimental stdlib modules
  375. ----------------------------------------------------------
  376. Reason: Generally speaking as external dependencies they are not exposed
  377. to enough users so that we can see if the shortcuts provide enough benefit
  378. or not. Many programmers avoid external dependencies, even moreso for
  379. "tiny syntactic improvements". However, this is only true for really good
  380. syntactic improvements that have the potential to clean up other parts of
  381. the Nim library substantially. If in doubt, new stdlib modules should start
  382. as external, successful Nimble packages.
  383. Other new stdlib modules do not start as stdlib modules
  384. -------------------------------------------------------
  385. As we strive for higher quality everywhere, it's easier to adopt existing,
  386. battle-tested modules eventually rather than creating modules from scratch.
  387. Little additions are acceptable
  388. -------------------------------
  389. As long as they are documented and tested well, adding little helpers
  390. to existing modules is acceptable. For two reasons:
  391. 1. It makes Nim easier to learn and use in the long run.
  392. ("Why does sequtils lack a ``countIt``?
  393. Because version 1.0 happens to have lacked it? Silly...")
  394. 2. To encourage contributions. Contributors often start with PRs that
  395. add simple things and then they stay and also fix bugs. Nim is an
  396. open source project and lives from people's contributions and involvement.
  397. Newly introduced issues have to be balanced against motivating new people. We know where
  398. to find perfectly designed pieces of software that have no bugs -- these are the systems
  399. that nobody uses.
  400. Conventions
  401. -----------
  402. 1. New stdlib modules should go under `Nim/lib/std/`. The rationale is to require
  403. users to import via `import std/foo` instead of `import foo`, which would cause
  404. potential conflicts with nimble packages. Note that this still applies for new modules
  405. in existing logical directories, e.g.:
  406. use `lib/std/collections/foo.nim`, not `lib/pure/collections/foo.nim`.
  407. 2. New module names should prefer plural form whenever possible, e.g.:
  408. `std/sums.nim` instead of `std/sum.nim`. In particular, this reduces chances of conflicts
  409. between module name and the symbols it defines. Furthermore, is should use `snake_case`
  410. and not use capital letters, which cause issues when going from an OS without case
  411. sensitivity to an OS without it.