intern.rst 26 KB

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