intern.rst 21 KB

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