intern.rst 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. =========================================
  2. Internals of the Nim Compiler
  3. =========================================
  4. :Author: Andreas Rumpf
  5. :Version: |nimversion|
  6. .. contents::
  7. "Abstraction is layering ignorance on top of reality." -- Richard Gabriel
  8. Directory structure
  9. ===================
  10. The Nim project's directory structure is:
  11. ============ ===================================================
  12. Path Purpose
  13. ============ ===================================================
  14. ``bin`` generated binary files
  15. ``build`` generated C code for the installation
  16. ``compiler`` the Nim compiler itself; note that this
  17. code has been translated from a bootstrapping
  18. version written in Pascal, so the code is **not**
  19. a poster child of good Nim code
  20. ``config`` configuration files for Nim
  21. ``dist`` additional packages for the distribution
  22. ``doc`` the documentation; it is a bunch of
  23. reStructuredText files
  24. ``lib`` the Nim library
  25. ``web`` website of Nim; generated by ``nimweb``
  26. from the ``*.txt`` and ``*.nimf`` files
  27. ============ ===================================================
  28. Bootstrapping the compiler
  29. ==========================
  30. Compiling the compiler is a simple matter of running::
  31. nim c koch.nim
  32. ./koch boot
  33. For a release version use::
  34. nim c koch.nim
  35. ./koch boot -d:release
  36. And for a debug version compatible with GDB::
  37. nim c koch.nim
  38. ./koch boot --debuginfo --linedir:on
  39. The ``koch`` program is Nim's maintenance script. It is a replacement for
  40. make and shell scripting with the advantage that it is much more portable.
  41. More information about its options can be found in the `koch <koch.html>`_
  42. documentation.
  43. Coding Guidelines
  44. =================
  45. * Use CamelCase, not underscored_identifiers.
  46. * Indent with two spaces.
  47. * Max line length is 80 characters.
  48. * Provide spaces around binary operators if that enhances readability.
  49. * Use a space after a colon, but not before it.
  50. * [deprecated] Start types with a capital ``T``, unless they are
  51. pointers/references which start with ``P``.
  52. See also the `API naming design <apis.html>`_ document.
  53. Porting to new platforms
  54. ========================
  55. Porting Nim to a new architecture is pretty easy, since C is the most
  56. portable programming language (within certain limits) and Nim generates
  57. C code, porting the code generator is not necessary.
  58. POSIX-compliant systems on conventional hardware are usually pretty easy to
  59. port: Add the platform to ``platform`` (if it is not already listed there),
  60. check that the OS, System modules work and recompile Nim.
  61. The only case where things aren't as easy is when the garbage
  62. collector needs some assembler tweaking to work. The standard
  63. version of the GC uses C's ``setjmp`` function to store all registers
  64. on the hardware stack. It may be necessary that the new platform needs to
  65. replace this generic code by some assembler code.
  66. Runtime type information
  67. ========================
  68. *Runtime type information* (RTTI) is needed for several aspects of the Nim
  69. programming language:
  70. Garbage collection
  71. The most important reason for RTTI. Generating
  72. traversal procedures produces bigger code and is likely to be slower on
  73. modern hardware as dynamic procedure binding is hard to predict.
  74. Complex assignments
  75. Sequences and strings are implemented as
  76. pointers to resizeable buffers, but Nim requires copying for
  77. assignments. Apart from RTTI the compiler could generate copy procedures
  78. for any type that needs one. However, this would make the code bigger and
  79. the RTTI is likely already there for the GC.
  80. We already know the type information as a graph in the compiler.
  81. Thus we need to serialize this graph as RTTI for C code generation.
  82. Look at the file ``lib/system/hti.nim`` for more information.
  83. Rebuilding the compiler
  84. ========================
  85. After an initial build via `sh build_all.sh` on posix or `build_all.bat` on windows,
  86. you can rebuild the compiler as follows:
  87. * `nim c koch` if you need to rebuild koch
  88. * `./koch boot -d:release` this ensures the compiler can rebuild itself
  89. (use `koch` instead of `./koch` on windows), which builds the compiler 3 times.
  90. A faster approach if you don't need to run the full bootstrapping implied by `koch boot`,
  91. is the following:
  92. * `pathto/nim c --lib:lib -d:release -o:bin/nim_temp compiler/nim.nim`
  93. Where `pathto/nim` is any nim binary sufficiently recent (e.g. `bin/nim_cources`
  94. built during bootstrap or `$HOME/.nimble/bin/nim` installed by `choosenim 1.2.0`)
  95. You can pass any additional options such as `-d:leanCompiler` if you don't need
  96. certain features or `-d:debug --stacktrace:on --excessiveStackTrace --stackTraceMsgs`
  97. for debugging the compiler. See also
  98. [Debugging the compiler](intern.html#debugging-the-compiler).
  99. Debugging the compiler
  100. ======================
  101. You can of course use GDB or Visual Studio to debug the
  102. compiler (via ``--debuginfo --lineDir:on``). However, there
  103. are also lots of procs that aid in debugging:
  104. .. code-block:: nim
  105. # pretty prints the Nim AST
  106. echo renderTree(someNode)
  107. # outputs some JSON representation
  108. debug(someNode)
  109. # pretty prints some type
  110. echo typeToString(someType)
  111. debug(someType)
  112. echo symbol.name.s
  113. debug(symbol)
  114. # pretty prints the Nim ast, but annotates symbol IDs:
  115. echo renderTree(someNode, {renderIds})
  116. if n.info ?? "temp.nim":
  117. # only output when it comes from "temp.nim"
  118. echo renderTree(n)
  119. if n.info ?? "temp.nim":
  120. # why does it process temp.nim here?
  121. writeStackTrace()
  122. To create a new compiler for each run, use ``koch temp``::
  123. ./koch temp c /tmp/test.nim
  124. ``koch temp`` creates a debug build of the compiler, which is useful
  125. to create stacktraces for compiler debugging. See also
  126. [Rebuilding the compiler](intern.html#rebuilding-the-compiler) if you need
  127. more control.
  128. Bisecting for regressions
  129. =========================
  130. ``koch temp`` returns 125 as the exit code in case the compiler
  131. compilation fails. This exit code tells ``git bisect`` to skip the
  132. current commit.::
  133. git bisect start bad-commit good-commit
  134. git bisect run ./koch temp -r c test-source.nim
  135. You can also bisect using custom options to build the compiler, for example if
  136. you don't need a debug version of the compiler (which runs slower), you can replace
  137. `./koch temp` by explicit compilation command, see
  138. [Rebuilding the compiler](intern.html#rebuilding-the-compiler).
  139. The compiler's architecture
  140. ===========================
  141. Nim uses the classic compiler architecture: A lexer/scanner feds tokens to a
  142. parser. The parser builds a syntax tree that is used by the code generator.
  143. This syntax tree is the interface between the parser and the code generator.
  144. It is essential to understand most of the compiler's code.
  145. In order to compile Nim correctly, type-checking has to be separated from
  146. parsing. Otherwise generics cannot work.
  147. .. include:: filelist.txt
  148. The syntax tree
  149. ---------------
  150. The syntax tree consists of nodes which may have an arbitrary number of
  151. children. Types and symbols are represented by other nodes, because they
  152. may contain cycles. The AST changes its shape after semantic checking. This
  153. is needed to make life easier for the code generators. See the "ast" module
  154. for the type definitions. The `macros <macros.html>`_ module contains many
  155. examples how the AST represents each syntactic structure.
  156. How the RTL is compiled
  157. =======================
  158. The ``system`` module contains the part of the RTL which needs support by
  159. compiler magic (and the stuff that needs to be in it because the spec
  160. says so). The C code generator generates the C code for it, just like any other
  161. module. However, calls to some procedures like ``addInt`` are inserted by
  162. the CCG. Therefore the module ``magicsys`` contains a table (``compilerprocs``)
  163. with all symbols that are marked as ``compilerproc``. ``compilerprocs`` are
  164. needed by the code generator. A ``magic`` proc is not the same as a
  165. ``compilerproc``: A ``magic`` is a proc that needs compiler magic for its
  166. semantic checking, a ``compilerproc`` is a proc that is used by the code
  167. generator.
  168. Compilation cache
  169. =================
  170. The implementation of the compilation cache is tricky: There are lots
  171. of issues to be solved for the front- and backend.
  172. General approach: AST replay
  173. ----------------------------
  174. We store a module's AST of a successful semantic check in a SQLite
  175. database. There are plenty of features that require a sub sequence
  176. to be re-applied, for example:
  177. .. code-block:: nim
  178. {.compile: "foo.c".} # even if the module is loaded from the DB,
  179. # "foo.c" needs to be compiled/linked.
  180. The solution is to **re-play** the module's top level statements.
  181. This solves the problem without having to special case the logic
  182. that fills the internal seqs which are affected by the pragmas.
  183. In fact, this describes how the AST should be stored in the database,
  184. as a "shallow" tree. Let's assume we compile module ``m`` with the
  185. following contents:
  186. .. code-block:: nim
  187. import strutils
  188. var x*: int = 90
  189. {.compile: "foo.c".}
  190. proc p = echo "p"
  191. proc q = echo "q"
  192. static:
  193. echo "static"
  194. Conceptually this is the AST we store for the module:
  195. .. code-block:: nim
  196. import strutils
  197. var x*
  198. {.compile: "foo.c".}
  199. proc p
  200. proc q
  201. static:
  202. echo "static"
  203. The symbol's ``ast`` field is loaded lazily, on demand. This is where most
  204. savings come from, only the shallow outer AST is reconstructed immediately.
  205. It is also important that the replay involves the ``import`` statement so
  206. that dependencies are resolved properly.
  207. Shared global compiletime state
  208. -------------------------------
  209. Nim allows ``.global, compiletime`` variables that can be filled by macro
  210. invocations across different modules. This feature breaks modularity in a
  211. severe way. Plenty of different solutions have been proposed:
  212. - Restrict the types of global compiletime variables to ``Set[T]`` or
  213. similar unordered, only-growable collections so that we can track
  214. the module's write effects to these variables and reapply the changes
  215. in a different order.
  216. - In every module compilation, reset the variable to its default value.
  217. - Provide a restrictive API that can load/save the compiletime state to
  218. a file.
  219. (These solutions are not mutually exclusive.)
  220. Since we adopt the "replay the top level statements" idea, the natural
  221. solution to this problem is to emit pseudo top level statements that
  222. reflect the mutations done to the global variable. However, this is
  223. MUCH harder than it sounds, for example ``squeaknim`` uses this
  224. snippet:
  225. .. code-block:: nim
  226. apicall.add(") module: '" & dllName & "'>\C" &
  227. "\t^self externalCallFailed\C!\C\C")
  228. stCode.add(st & "\C\t\"Generated by NimSqueak\"\C\t" & apicall)
  229. We can "replay" ``stCode.add`` only if the values of ``st``
  230. and ``apicall`` are known. And even then a hash table's ``add`` with its
  231. hashing mechanism is too hard to replay.
  232. In practice, things are worse still, consider ``someGlobal[i][j].add arg``.
  233. We only know the root is ``someGlobal`` but the concrete path to the data
  234. is unknown as is the value that is added. We could compute a "diff" between
  235. the global states and use that to compute a symbol patchset, but this is
  236. quite some work, expensive to do at runtime (it would need to run after
  237. every module has been compiled) and would also break for hash tables.
  238. We need an API that hides the complex aliasing problems by not relying
  239. on Nim's global variables. The obvious solution is to use string keys
  240. instead of global variables:
  241. .. code-block:: nim
  242. proc cachePut*(key: string; value: string)
  243. proc cacheGet*(key: string): string
  244. However, the values being strings/json is quite problematic: Many
  245. lookup tables that are built at compiletime embed *proc vars* and
  246. types which have no obvious string representation... Seems like
  247. AST diffing is still the best idea as it will not require to use
  248. an alien API and works with some existing Nimble packages, at least.
  249. On the other hand, in Nim's future I would like to replace the VM
  250. by native code. A diff algorithm wouldn't work for that.
  251. Instead the native code would work with an API like ``put``, ``get``:
  252. .. code-block:: nim
  253. proc cachePut*(key: string; value: NimNode)
  254. proc cacheGet*(key: string): NimNode
  255. The API should embrace the AST diffing notion: See the
  256. module ``macrocache`` for the final details.
  257. Methods and type converters
  258. ---------------------------
  259. In the following
  260. sections *global* means *shared between modules* or *property of the whole
  261. program*.
  262. Nim contains language features that are *global*. The best example for that
  263. are multi methods: Introducing a new method with the same name and some
  264. compatible object parameter means that the method's dispatcher needs to take
  265. the new method into account. So the dispatching logic is only completely known
  266. after the whole program has been translated!
  267. Other features that are *implicitly* triggered cause problems for modularity
  268. too. Type converters fall into this category:
  269. .. code-block:: nim
  270. # module A
  271. converter toBool(x: int): bool =
  272. result = x != 0
  273. .. code-block:: nim
  274. # module B
  275. import A
  276. if 1:
  277. echo "ugly, but should work"
  278. If in the above example module ``B`` is re-compiled, but ``A`` is not then
  279. ``B`` needs to be aware of ``toBool`` even though ``toBool`` is not referenced
  280. in ``B`` *explicitly*.
  281. Both the multi method and the type converter problems are solved by the
  282. AST replay implementation.
  283. Generics
  284. ~~~~~~~~
  285. We cache generic instantiations and need to ensure this caching works
  286. well with the incremental compilation feature. Since the cache is
  287. attached to the ``PSym`` datastructure, it should work without any
  288. special logic.
  289. Backend issues
  290. --------------
  291. - Init procs must not be "forgotten" to be called.
  292. - Files must not be "forgotten" to be linked.
  293. - Method dispatchers are global.
  294. - DLL loading via ``dlsym`` is global.
  295. - Emulated thread vars are global.
  296. However the biggest problem is that dead code elimination breaks modularity!
  297. To see why, consider this scenario: The module ``G`` (for example the huge
  298. Gtk2 module...) is compiled with dead code elimination turned on. So none
  299. of ``G``'s procs is generated at all.
  300. Then module ``B`` is compiled that requires ``G.P1``. Ok, no problem,
  301. ``G.P1`` is loaded from the symbol file and ``G.c`` now contains ``G.P1``.
  302. Then module ``A`` (that depends on ``B`` and ``G``) is compiled and ``B``
  303. and ``G`` are left unchanged. ``A`` requires ``G.P2``.
  304. So now ``G.c`` MUST contain both ``P1`` and ``P2``, but we haven't even
  305. loaded ``P1`` from the symbol file, nor do we want to because we then quickly
  306. would restore large parts of the whole program.
  307. Solution
  308. ~~~~~~~~
  309. The backend must have some logic so that if the currently processed module
  310. is from the compilation cache, the ``ast`` field is not accessed. Instead
  311. the generated C(++) for the symbol's body needs to be cached too and
  312. inserted back into the produced C file. This approach seems to deal with
  313. all the outlined problems above.
  314. Debugging Nim's memory management
  315. =================================
  316. The following paragraphs are mostly a reminder for myself. Things to keep
  317. in mind:
  318. * If an assertion in Nim's memory manager or GC fails, the stack trace
  319. keeps allocating memory! Thus a stack overflow may happen, hiding the
  320. real issue.
  321. * What seem to be C code generation problems is often a bug resulting from
  322. not producing prototypes, so that some types default to ``cint``. Testing
  323. without the ``-w`` option helps!
  324. The Garbage Collector
  325. =====================
  326. Introduction
  327. ------------
  328. I use the term *cell* here to refer to everything that is traced
  329. (sequences, refs, strings).
  330. This section describes how the GC works.
  331. The basic algorithm is *Deferrent Reference Counting* with cycle detection.
  332. References on the stack are not counted for better performance and easier C
  333. code generation.
  334. Each cell has a header consisting of a RC and a pointer to its type
  335. descriptor. However the program does not know about these, so they are placed at
  336. negative offsets. In the GC code the type ``PCell`` denotes a pointer
  337. decremented by the right offset, so that the header can be accessed easily. It
  338. is extremely important that ``pointer`` is not confused with a ``PCell``
  339. as this would lead to a memory corruption.
  340. The CellSet data structure
  341. --------------------------
  342. The GC depends on an extremely efficient datastructure for storing a
  343. set of pointers - this is called a ``TCellSet`` in the source code.
  344. Inserting, deleting and searching are done in constant time. However,
  345. modifying a ``TCellSet`` during traversal leads to undefined behaviour.
  346. .. code-block:: Nim
  347. type
  348. TCellSet # hidden
  349. proc cellSetInit(s: var TCellSet) # initialize a new set
  350. proc cellSetDeinit(s: var TCellSet) # empty the set and free its memory
  351. proc incl(s: var TCellSet, elem: PCell) # include an element
  352. proc excl(s: var TCellSet, elem: PCell) # exclude an element
  353. proc `in`(elem: PCell, s: TCellSet): bool # tests membership
  354. iterator elements(s: TCellSet): (elem: PCell)
  355. All the operations have to perform efficiently. Because a Cellset can
  356. become huge a hash table alone is not suitable for this.
  357. We use a mixture of bitset and hash table for this. The hash table maps *pages*
  358. to a page descriptor. The page descriptor contains a bit for any possible cell
  359. address within this page. So including a cell is done as follows:
  360. - Find the page descriptor for the page the cell belongs to.
  361. - Set the appropriate bit in the page descriptor indicating that the
  362. cell points to the start of a memory block.
  363. Removing a cell is analogous - the bit has to be set to zero.
  364. Single page descriptors are never deleted from the hash table. This is not
  365. needed as the data structures needs to be rebuilt periodically anyway.
  366. Complete traversal is done in this way::
  367. for each page descriptor d:
  368. for each bit in d:
  369. if bit == 1:
  370. traverse the pointer belonging to this bit
  371. Further complications
  372. ---------------------
  373. In Nim the compiler cannot always know if a reference
  374. is stored on the stack or not. This is caused by var parameters.
  375. Consider this example:
  376. .. code-block:: Nim
  377. proc setRef(r: var ref TNode) =
  378. new(r)
  379. proc usage =
  380. var
  381. r: ref TNode
  382. setRef(r) # here we should not update the reference counts, because
  383. # r is on the stack
  384. setRef(r.left) # here we should update the refcounts!
  385. We have to decide at runtime whether the reference is on the stack or not.
  386. The generated code looks roughly like this:
  387. .. code-block:: C
  388. void setref(TNode** ref) {
  389. unsureAsgnRef(ref, newObj(TNode_TI, sizeof(TNode)))
  390. }
  391. void usage(void) {
  392. setRef(&r)
  393. setRef(&r->left)
  394. }
  395. Note that for systems with a continuous stack (which most systems have)
  396. the check whether the ref is on the stack is very cheap (only two
  397. comparisons).
  398. Code generation for closures
  399. ============================
  400. Code generation for closures is implemented by `lambda lifting`:idx:.
  401. Design
  402. ------
  403. A ``closure`` proc var can call ordinary procs of the default Nim calling
  404. convention. But not the other way round! A closure is implemented as a
  405. ``tuple[prc, env]``. ``env`` can be nil implying a call without a closure.
  406. This means that a call through a closure generates an ``if`` but the
  407. interoperability is worth the cost of the ``if``. Thunk generation would be
  408. possible too, but it's slightly more effort to implement.
  409. Tests with GCC on Amd64 showed that it's really beneficial if the
  410. 'environment' pointer is passed as the last argument, not as the first argument.
  411. Proper thunk generation is harder because the proc that is to wrap
  412. could stem from a complex expression:
  413. .. code-block:: nim
  414. receivesClosure(returnsDefaultCC[i])
  415. A thunk would need to call 'returnsDefaultCC[i]' somehow and that would require
  416. an *additional* closure generation... Ok, not really, but it requires to pass
  417. the function to call. So we'd end up with 2 indirect calls instead of one.
  418. Another much more severe problem which this solution is that it's not GC-safe
  419. to pass a proc pointer around via a generic ``ref`` type.
  420. Example code:
  421. .. code-block:: nim
  422. proc add(x: int): proc (y: int): int {.closure.} =
  423. return proc (y: int): int =
  424. return x + y
  425. var add2 = add(2)
  426. echo add2(5) #OUT 7
  427. This should produce roughly this code:
  428. .. code-block:: nim
  429. type
  430. PEnv = ref object
  431. x: int # data
  432. proc anon(y: int, c: PEnv): int =
  433. return y + c.x
  434. proc add(x: int): tuple[prc, data] =
  435. var env: PEnv
  436. new env
  437. env.x = x
  438. result = (anon, env)
  439. var add2 = add(2)
  440. let tmp = if add2.data == nil: add2.prc(5) else: add2.prc(5, add2.data)
  441. echo tmp
  442. Beware of nesting:
  443. .. code-block:: nim
  444. proc add(x: int): proc (y: int): proc (z: int): int {.closure.} {.closure.} =
  445. return lambda (y: int): proc (z: int): int {.closure.} =
  446. return lambda (z: int): int =
  447. return x + y + z
  448. var add24 = add(2)(4)
  449. echo add24(5) #OUT 11
  450. This should produce roughly this code:
  451. .. code-block:: nim
  452. type
  453. PEnvX = ref object
  454. x: int # data
  455. PEnvY = ref object
  456. y: int
  457. ex: PEnvX
  458. proc lambdaZ(z: int, ey: PEnvY): int =
  459. return ey.ex.x + ey.y + z
  460. proc lambdaY(y: int, ex: PEnvX): tuple[prc, data: PEnvY] =
  461. var ey: PEnvY
  462. new ey
  463. ey.y = y
  464. ey.ex = ex
  465. result = (lambdaZ, ey)
  466. proc add(x: int): tuple[prc, data: PEnvX] =
  467. var ex: PEnvX
  468. ex.x = x
  469. result = (labmdaY, ex)
  470. var tmp = add(2)
  471. var tmp2 = tmp.fn(4, tmp.data)
  472. var add24 = tmp2.fn(4, tmp2.data)
  473. echo add24(5)
  474. We could get rid of nesting environments by always inlining inner anon procs.
  475. More useful is escape analysis and stack allocation of the environment,
  476. however.
  477. Alternative
  478. -----------
  479. Process the closure of all inner procs in one pass and accumulate the
  480. environments. This is however not always possible.
  481. Accumulator
  482. -----------
  483. .. code-block:: nim
  484. proc getAccumulator(start: int): proc (): int {.closure} =
  485. var i = start
  486. return lambda: int =
  487. inc i
  488. return i
  489. proc p =
  490. var delta = 7
  491. proc accumulator(start: int): proc(): int =
  492. var x = start-1
  493. result = proc (): int =
  494. x = x + delta
  495. inc delta
  496. return x
  497. var a = accumulator(3)
  498. var b = accumulator(4)
  499. echo a() + b()
  500. Internals
  501. ---------
  502. Lambda lifting is implemented as part of the ``transf`` pass. The ``transf``
  503. pass generates code to setup the environment and to pass it around. However,
  504. this pass does not change the types! So we have some kind of mismatch here; on
  505. the one hand the proc expression becomes an explicit tuple, on the other hand
  506. the tyProc(ccClosure) type is not changed. For C code generation it's also
  507. important the hidden formal param is ``void*`` and not something more
  508. specialized. However the more specialized env type needs to passed to the
  509. backend somehow. We deal with this by modifying ``s.ast[paramPos]`` to contain
  510. the formal hidden parameter, but not ``s.typ``!
  511. Integer literals:
  512. -----------------
  513. In Nim, there is a redundant way to specify the type of an
  514. integer literal. First of all, it should be unsurprising that every
  515. node has a node kind. The node of an integer literal can be any of the
  516. following values:
  517. nkIntLit, nkInt8Lit, nkInt16Lit, nkInt32Lit, nkInt64Lit,
  518. nkUIntLit, nkUInt8Lit, nkUInt16Lit, nkUInt32Lit, nkUInt64Lit
  519. On top of that, there is also the `typ` field for the type. It the
  520. kind of the `typ` field can be one of the following ones, and it
  521. should be matching the literal kind:
  522. tyInt, tyInt8, tyInt16, tyInt32, tyInt64, tyUInt, tyUInt8,
  523. tyUInt16, tyUInt32, tyUInt64
  524. Then there is also the integer literal type. This is a specific type
  525. that is implicitly convertible into the requested type if the
  526. requested type can hold the value. For this to work, the type needs to
  527. know the concrete value of the literal. For example an expression
  528. `321` will be of type `int literal(321)`. This type is implicitly
  529. convertible to all integer types and ranges that contain the value
  530. `321`. That would be all builtin integer types except `uint8` and
  531. `int8` where `321` would be out of range. When this literal type is
  532. assigned to a new `var` or `let` variable, it's type will be resolved
  533. to just `int`, not `int literal(321)` unlike constants. A constant
  534. keeps the full `int literal(321)` type. Here is an example where that
  535. difference matters.
  536. .. code-block:: nim
  537. proc foo(arg: int8) =
  538. echo "def"
  539. const tmp1 = 123
  540. foo(tmp1) # OK
  541. let tmp2 = 123
  542. foo(tmp2) # Error
  543. In a context with multiple overloads, the integer literal kind will
  544. always prefer the `int` type over all other types. If none of the
  545. overloads is of type `int`, then there will be an error because of
  546. ambiguity.
  547. .. code-block:: nim
  548. proc foo(arg: int) =
  549. echo "abc"
  550. proc foo(arg: int8) =
  551. echo "def"
  552. foo(123) # output: abc
  553. proc bar(arg: int16) =
  554. echo "abc"
  555. proc bar(arg: int8) =
  556. echo "def"
  557. bar(123) # Error ambiguous call
  558. In the compiler these integer literal types are represented with the
  559. node kind `nkIntLit`, type kind `tyInt` and the member `n` of the type
  560. pointing back to the integer literal node in the ast containing the
  561. integer value. These are the properties that hold true for integer
  562. literal types.
  563. n.kind == nkIntLit
  564. n.typ.kind == tyInt
  565. n.typ.n == n
  566. Other literal types, such as `uint literal(123)` that would
  567. automatically convert to other integer types, but prefers to
  568. become a `uint` are not part of the Nim language.
  569. In an unchecked AST, the `typ` field is nil. The type checker will set
  570. the `typ` field accordingly to the node kind. Nodes of kind `nkIntLit`
  571. will get the integer literal type (e.g. `int literal(123)`). Nodes of
  572. kind `nkUIntLit` will get type `uint` (kind `tyUint`), etc.
  573. This also means that it is not possible to write a literal in an
  574. unchecked AST that will after sem checking just be of type `int` and
  575. not implicitly convertible to other integer types. This only works for
  576. all integer types that are not `int`.