nep1.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. ==============================================
  2. Nim Enhancement Proposal #1 - Standard Library Style Guide
  3. ==============================================
  4. :Author: Clay Sweetser, Dominik Picheta
  5. :Version: |nimversion|
  6. .. contents::
  7. Introduction
  8. ============
  9. Although Nim supports a variety of code and formatting styles, it is
  10. nevertheless beneficial that certain community efforts, such as the standard
  11. library, should follow a consistent set of style guidelines when suitable.
  12. This enhancement proposal aims to list a series of guidelines that the standard
  13. library should follow.
  14. Note that there can be exceptions to these rules. Nim being as flexible as it
  15. is, there will be parts of this style guide that don't make sense in certain
  16. contexts. Furthermore, just as
  17. `Python's style guide<http://legacy.python.org/dev/peps/pep-0008/>`_ changes
  18. over time, this style guide will too.
  19. These rules will only be enforced for contributions to the Nim
  20. codebase and official projects, such as the Nim compiler, the standard library,
  21. and the various official tools such as C2Nim.
  22. ----------------
  23. Style Guidelines
  24. ----------------
  25. Spacing and Whitespace Conventions
  26. -----------------------------------
  27. - Lines should be no longer than 80 characters. Limiting the amount of
  28. information present on each line makes for more readable code - the reader
  29. has smaller chunks to process.
  30. - Two spaces should be used for indentation of blocks; tabstops are not allowed
  31. (the compiler enforces this). Using spaces means that the appearance of code
  32. is more consistent across editors. Unlike spaces, tabstop width varies across
  33. editors, and not all editors provide means of changing this width.
  34. - Although use of whitespace for stylistic reasons other than the ones endorsed
  35. by this guide are allowed, careful thought should be put into such practices.
  36. Not all editors support automatic alignment of code sections, and re-aligning
  37. long sections of code by hand can quickly become tedious.
  38. .. code-block:: nim
  39. # This is bad, as the next time someone comes
  40. # to edit this code block, they
  41. # must re-align all the assignments again:
  42. type
  43. WordBool* = int16
  44. CalType* = int
  45. ... # 5 lines later
  46. CalId* = int
  47. LongLong* = int64
  48. LongLongPtr* = ptr LongLong
  49. Naming Conventions
  50. ------------------
  51. Note: While the rules outlined below are the *current* naming conventions,
  52. these conventions have not always been in place. Previously, the naming
  53. conventions for identifiers followed the Pascal tradition of prefixes which
  54. indicated the base type of the identifier - PFoo for pointer and reference
  55. types, TFoo for value types, EFoo for exceptions, etc. Though this has since
  56. changed, there are many places in the standard library which still use this
  57. convention. Such style remains in place purely for legacy reasons, and will be
  58. changed in the future.
  59. - Type identifiers should be in PascalCase. All other identifiers should be in
  60. camelCase with the exception of constants which **may** use PascalCase but
  61. are not required to.
  62. .. code-block:: nim
  63. # Constants can start with either a lower case or upper case letter.
  64. const aConstant = 42
  65. const FooBar = 4.2
  66. var aVariable = "Meep" # Variables must start with a lowercase letter.
  67. # Types must start with an uppercase letter.
  68. type
  69. FooBar = object
  70. For constants coming from a C/C++ wrapper, ALL_UPPERCASE are allowed, but ugly.
  71. (Why shout CONSTANT? Constants do no harm, variables do!)
  72. - When naming types that come in value, pointer, and reference varieties, use a
  73. regular name for the variety that is to be used the most, and add a "Obj",
  74. "Ref", or "Ptr" suffix for the other varieties. If there is no single variety
  75. that will be used the most, add the suffixes to the pointer variants only. The
  76. same applies to C/C++ wrappers.
  77. .. code-block:: nim
  78. type
  79. Handle = object # Will be used most often
  80. fd: int64
  81. HandleRef = ref Handle # Will be used less often
  82. - Exception and Error types should have the "Error" suffix.
  83. .. code-block:: nim
  84. type
  85. UnluckyError = object of Exception
  86. - Unless marked with the `{.pure.}` pragma, members of enums should have an
  87. identifying prefix, such as an abbreviation of the enum's name.
  88. .. code-block:: nim
  89. type
  90. PathComponent = enum
  91. pcDir
  92. pcLinkToDir
  93. pcFile
  94. pcLinkToFile
  95. - Non-pure enum values should use camelCase whereas pure enum values should use
  96. PascalCase.
  97. .. code-block:: nim
  98. type
  99. PathComponent {.pure.} = enum
  100. Dir
  101. LinkToDir
  102. File
  103. LinkToFile
  104. - In the age of HTTP, HTML, FTP, TCP, IP, UTF, WWW it is foolish to pretend
  105. these are somewhat special words requiring all uppercase. Instead treat them
  106. as what they are: Real words. So it's ``parseUrl`` rather than
  107. ``parseURL``, ``checkHttpHeader`` instead of ``checkHTTPHeader`` etc.
  108. - Operations like ``mitems`` or ``mpairs`` (or the now deprecated ``mget``)
  109. that allow a *mutating view* into some data structure should start with an ``m``.
  110. - When both in-place mutation and 'returns transformed copy' are available the latter
  111. is a past participle of the former:
  112. - reverse and reversed in algorithm
  113. - sort and sorted
  114. - rotate and rotated
  115. - When the 'returns transformed copy' version already exists like ``strutils.replace``
  116. an in-place version should get an ``-In`` suffix (``replaceIn`` for this example).
  117. The stdlib API is designed to be **easy to use** and consistent. Ease of use is
  118. measured by the number of calls to achieve a concrete high level action. The
  119. ultimate goal is that the programmer can *guess* a name.
  120. The library uses a simple naming scheme that makes use of common abbreviations
  121. to keep the names short but meaningful.
  122. ------------------- ------------ --------------------------------------
  123. English word To use Notes
  124. ------------------- ------------ --------------------------------------
  125. initialize initT ``init`` is used to create a
  126. value type ``T``
  127. new newP ``new`` is used to create a
  128. reference type ``P``
  129. find find should return the position where
  130. something was found; for a bool result
  131. use ``contains``
  132. contains contains often short for ``find() >= 0``
  133. append add use ``add`` instead of ``append``
  134. compare cmp should return an int with the
  135. ``< 0`` ``== 0`` or ``> 0`` semantics;
  136. for a bool result use ``sameXYZ``
  137. put put, ``[]=`` consider overloading ``[]=`` for put
  138. get get, ``[]`` consider overloading ``[]`` for get;
  139. consider to not use ``get`` as a
  140. prefix: ``len`` instead of ``getLen``
  141. length len also used for *number of elements*
  142. size size, len size should refer to a byte size
  143. capacity cap
  144. memory mem implies a low-level operation
  145. items items default iterator over a collection
  146. pairs pairs iterator over (key, value) pairs
  147. delete delete, del del is supposed to be faster than
  148. delete, because it does not keep
  149. the order; delete keeps the order
  150. remove delete, del inconsistent right now
  151. include incl
  152. exclude excl
  153. command cmd
  154. execute exec
  155. environment env
  156. variable var
  157. value value, val val is preferred, inconsistent right
  158. now
  159. executable exe
  160. directory dir
  161. path path path is the string "/usr/bin" (for
  162. example), dir is the content of
  163. "/usr/bin"; inconsistent right now
  164. extension ext
  165. separator sep
  166. column col, column col is preferred, inconsistent right
  167. now
  168. application app
  169. configuration cfg
  170. message msg
  171. argument arg
  172. object obj
  173. parameter param
  174. operator opr
  175. procedure proc
  176. function func
  177. coordinate coord
  178. rectangle rect
  179. point point
  180. symbol sym
  181. literal lit
  182. string str
  183. identifier ident
  184. indentation indent
  185. ------------------- ------------ --------------------------------------
  186. Coding Conventions
  187. ------------------
  188. - The 'return' statement should ideally be used when its control-flow properties
  189. are required. Use a procedure's implicit 'result' variable whenever possible.
  190. This improves readability.
  191. .. code-block:: nim
  192. proc repeat(text: string, x: int): string =
  193. result = ""
  194. for i in 0 .. x:
  195. result.add($i)
  196. - Use a proc when possible, only using the more powerful facilities of macros,
  197. templates, iterators, and converters when necessary.
  198. - Use the ``let`` statement (not the ``var`` statement) when declaring variables that
  199. do not change within their scope. Using the ``let`` statement ensures that
  200. variables remain immutable, and gives those who read the code a better idea
  201. of the code's purpose.
  202. Conventions for multi-line statements and expressions
  203. -----------------------------------------------------
  204. - Tuples which are longer than one line should indent their parameters to
  205. align with the parameters above it.
  206. .. code-block:: nim
  207. type
  208. LongTupleA = tuple[wordyTupleMemberOne: int, wordyTupleMemberTwo: string,
  209. wordyTupleMemberThree: float]
  210. - Similarly, any procedure and procedure type declarations that are longer
  211. than one line should do the same thing.
  212. .. code-block:: nim
  213. type
  214. EventCallback = proc (timeReceived: Time, errorCode: int, event: Event,
  215. output: var string)
  216. proc lotsOfArguments(argOne: string, argTwo: int, argThree: float
  217. argFour: proc(), argFive: bool): int
  218. {.heyLookALongPragma.} =
  219. - Multi-line procedure calls should continue on the same column as the opening
  220. parenthesis (like multi-line procedure declarations).
  221. .. code-block:: nim
  222. startProcess(nimExecutable, currentDirectory, compilerArguments
  223. environment, processOptions)