intern.rst 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. =========================================
  2. Internals of the Nim Compiler
  3. =========================================
  4. :Author: Andreas Rumpf
  5. :Version: |nimversion|
  6. .. default-role:: code
  7. .. include:: rstcommon.rst
  8. .. contents::
  9. "Abstraction is layering ignorance on top of reality." -- Richard Gabriel
  10. Directory structure
  11. ===================
  12. The Nim project's directory structure is:
  13. ============ ===================================================
  14. Path Purpose
  15. ============ ===================================================
  16. `bin` generated binary files
  17. `build` generated C code for the installation
  18. `compiler` the Nim compiler itself; note that this
  19. code has been translated from a bootstrapping
  20. version written in Pascal, so the code is **not**
  21. a poster child of good Nim code
  22. `config` configuration files for Nim
  23. `dist` additional packages for the distribution
  24. `doc` the documentation; it is a bunch of
  25. reStructuredText files
  26. `lib` the Nim library
  27. ============ ===================================================
  28. Bootstrapping the compiler
  29. ==========================
  30. **Note**: Add ``.`` to your PATH so that `koch`:cmd: can be used without the ``./``.
  31. Compiling the compiler is a simple matter of running:
  32. .. code:: cmd
  33. nim c koch.nim
  34. koch boot -d:release
  35. For a debug version use:
  36. .. code:: cmd
  37. nim c koch.nim
  38. koch boot
  39. And for a debug version compatible with GDB:
  40. .. code:: cmd
  41. nim c koch.nim
  42. koch boot --debuginfo --linedir:on
  43. The `koch`:cmd: program is Nim's maintenance script. It is a replacement for
  44. make and shell scripting with the advantage that it is much more portable.
  45. More information about its options can be found in the `koch <koch.html>`_
  46. documentation.
  47. Reproducible builds
  48. -------------------
  49. Set the compilation timestamp with the `SOURCE_DATE_EPOCH` environment variable.
  50. .. code:: cmd
  51. export SOURCE_DATE_EPOCH=$(git log -n 1 --format=%at)
  52. koch boot # or `./build_all.sh`
  53. Developing the compiler
  54. =======================
  55. To create a new compiler for each run, use `koch temp`:cmd:\:
  56. .. code:: cmd
  57. koch temp c test.nim
  58. `koch temp`:cmd: creates a debug build of the compiler, which is useful
  59. to create stacktraces for compiler debugging.
  60. You can of course use GDB or Visual Studio to debug the
  61. compiler (via `--debuginfo --lineDir:on`:option:). However, there
  62. are also lots of procs that aid in debugging:
  63. .. code-block:: nim
  64. # dealing with PNode:
  65. echo renderTree(someNode)
  66. debug(someNode) # some JSON representation
  67. # dealing with PType:
  68. echo typeToString(someType)
  69. debug(someType)
  70. # dealing with PSym:
  71. echo symbol.name.s
  72. debug(symbol)
  73. # pretty prints the Nim ast, but annotates symbol IDs:
  74. echo renderTree(someNode, {renderIds})
  75. if `??`(conf, n.info, "temp.nim"):
  76. # only output when it comes from "temp.nim"
  77. echo renderTree(n)
  78. if `??`(conf, n.info, "temp.nim"):
  79. # why does it process temp.nim here?
  80. writeStackTrace()
  81. These procs may not already be imported by the module you're editing.
  82. You can import them directly for debugging:
  83. .. code-block:: nim
  84. from astalgo import debug
  85. from types import typeToString
  86. from renderer import renderTree
  87. from msgs import `??`
  88. The compiler's architecture
  89. ===========================
  90. Nim uses the classic compiler architecture: A lexer/scanner feeds tokens to a
  91. parser. The parser builds a syntax tree that is used by the code generators.
  92. This syntax tree is the interface between the parser and the code generator.
  93. It is essential to understand most of the compiler's code.
  94. Semantic analysis is separated from parsing.
  95. .. include:: filelist.txt
  96. The syntax tree
  97. ---------------
  98. The syntax tree consists of nodes which may have an arbitrary number of
  99. children. Types and symbols are represented by other nodes, because they
  100. may contain cycles. The AST changes its shape after semantic checking. This
  101. is needed to make life easier for the code generators. See the "ast" module
  102. for the type definitions. The `macros <macros.html>`_ module contains many
  103. examples how the AST represents each syntactic structure.
  104. Bisecting for regressions
  105. =========================
  106. `koch temp`:cmd: returns 125 as the exit code in case the compiler
  107. compilation fails. This exit code tells `git bisect`:cmd: to skip the
  108. current commit:
  109. .. code:: cmd
  110. git bisect start bad-commit good-commit
  111. git bisect run ./koch temp -r c test-source.nim
  112. You can also bisect using custom options to build the compiler, for example if
  113. you don't need a debug version of the compiler (which runs slower), you can replace
  114. `./koch temp`:cmd: by explicit compilation command, see `Rebuilding the compiler`_.
  115. Runtimes
  116. ========
  117. Nim has two different runtimes, the "old runtime" and the "new runtime". The old
  118. runtime supports the old GCs (markAndSweep, refc, Boehm), the new runtime supports
  119. ARC/ORC. The new runtime is active `when defined(nimV2)`.
  120. Coding Guidelines
  121. =================
  122. * We follow Nim's official style guide, see `<nep1.html>`_.
  123. * Max line length is 100 characters.
  124. * Provide spaces around binary operators if that enhances readability.
  125. * Use a space after a colon, but not before it.
  126. * [deprecated] Start types with a capital `T`, unless they are
  127. pointers/references which start with `P`.
  128. See also the `API naming design <apis.html>`_ document.
  129. Porting to new platforms
  130. ========================
  131. Porting Nim to a new architecture is pretty easy, since C is the most
  132. portable programming language (within certain limits) and Nim generates
  133. C code, porting the code generator is not necessary.
  134. POSIX-compliant systems on conventional hardware are usually pretty easy to
  135. port: Add the platform to `platform` (if it is not already listed there),
  136. check that the OS, System modules work and recompile Nim.
  137. The only case where things aren't as easy is when old runtime's garbage
  138. collectors need some assembler tweaking to work. The default
  139. implementation uses C's `setjmp`:c: function to store all registers
  140. on the hardware stack. It may be necessary that the new platform needs to
  141. replace this generic code by some assembler code.
  142. Runtime type information
  143. ========================
  144. **Note**: This section describes the "old runtime".
  145. *Runtime type information* (RTTI) is needed for several aspects of the Nim
  146. programming language:
  147. Garbage collection
  148. The old GCs use the RTTI for traversing abitrary Nim types, but usually
  149. only the `marker` field which contains a proc that does the traversal.
  150. Complex assignments
  151. Sequences and strings are implemented as
  152. pointers to resizeable buffers, but Nim requires copying for
  153. assignments. Apart from RTTI the compiler also generates copy procedures
  154. as a specialization.
  155. We already know the type information as a graph in the compiler.
  156. Thus we need to serialize this graph as RTTI for C code generation.
  157. Look at the file ``lib/system/hti.nim`` for more information.
  158. Magics and compilerProcs
  159. ========================
  160. The `system` module contains the part of the RTL which needs support by
  161. compiler magic. The C code generator generates the C code for it, just like any other
  162. module. However, calls to some procedures like `addInt` are inserted by
  163. the generator. Therefore there is a table (`compilerprocs`)
  164. with all symbols that are marked as `compilerproc`. `compilerprocs` are
  165. needed by the code generator. A `magic` proc is not the same as a
  166. `compilerproc`: A `magic` is a proc that needs compiler magic for its
  167. semantic checking, a `compilerproc` is a proc that is used by the code
  168. generator.
  169. Code generation for closures
  170. ============================
  171. Code generation for closures is implemented by `lambda lifting`:idx:.
  172. Design
  173. ------
  174. A `closure` proc var can call ordinary procs of the default Nim calling
  175. convention. But not the other way round! A closure is implemented as a
  176. `tuple[prc, env]`. `env` can be nil implying a call without a closure.
  177. This means that a call through a closure generates an `if` but the
  178. interoperability is worth the cost of the `if`. Thunk generation would be
  179. possible too, but it's slightly more effort to implement.
  180. Tests with GCC on Amd64 showed that it's really beneficial if the
  181. 'environment' pointer is passed as the last argument, not as the first argument.
  182. Proper thunk generation is harder because the proc that is to wrap
  183. could stem from a complex expression:
  184. .. code-block:: nim
  185. receivesClosure(returnsDefaultCC[i])
  186. A thunk would need to call 'returnsDefaultCC[i]' somehow and that would require
  187. an *additional* closure generation... Ok, not really, but it requires to pass
  188. the function to call. So we'd end up with 2 indirect calls instead of one.
  189. Another much more severe problem which this solution is that it's not GC-safe
  190. to pass a proc pointer around via a generic `ref` type.
  191. Example code:
  192. .. code-block:: nim
  193. proc add(x: int): proc (y: int): int {.closure.} =
  194. return proc (y: int): int =
  195. return x + y
  196. var add2 = add(2)
  197. echo add2(5) #OUT 7
  198. This should produce roughly this code:
  199. .. code-block:: nim
  200. type
  201. Env = ref object
  202. x: int # data
  203. proc anon(y: int, c: Env): int =
  204. return y + c.x
  205. proc add(x: int): tuple[prc, data] =
  206. var env: Env
  207. new env
  208. env.x = x
  209. result = (anon, env)
  210. var add2 = add(2)
  211. let tmp = if add2.data == nil: add2.prc(5) else: add2.prc(5, add2.data)
  212. echo tmp
  213. Beware of nesting:
  214. .. code-block:: nim
  215. proc add(x: int): proc (y: int): proc (z: int): int {.closure.} {.closure.} =
  216. return lambda (y: int): proc (z: int): int {.closure.} =
  217. return lambda (z: int): int =
  218. return x + y + z
  219. var add24 = add(2)(4)
  220. echo add24(5) #OUT 11
  221. This should produce roughly this code:
  222. .. code-block:: nim
  223. type
  224. EnvX = ref object
  225. x: int # data
  226. EnvY = ref object
  227. y: int
  228. ex: EnvX
  229. proc lambdaZ(z: int, ey: EnvY): int =
  230. return ey.ex.x + ey.y + z
  231. proc lambdaY(y: int, ex: EnvX): tuple[prc, data: EnvY] =
  232. var ey: EnvY
  233. new ey
  234. ey.y = y
  235. ey.ex = ex
  236. result = (lambdaZ, ey)
  237. proc add(x: int): tuple[prc, data: EnvX] =
  238. var ex: EnvX
  239. ex.x = x
  240. result = (labmdaY, ex)
  241. var tmp = add(2)
  242. var tmp2 = tmp.fn(4, tmp.data)
  243. var add24 = tmp2.fn(4, tmp2.data)
  244. echo add24(5)
  245. We could get rid of nesting environments by always inlining inner anon procs.
  246. More useful is escape analysis and stack allocation of the environment,
  247. however.
  248. Accumulator
  249. -----------
  250. .. code-block:: nim
  251. proc getAccumulator(start: int): proc (): int {.closure} =
  252. var i = start
  253. return lambda: int =
  254. inc i
  255. return i
  256. proc p =
  257. var delta = 7
  258. proc accumulator(start: int): proc(): int =
  259. var x = start-1
  260. result = proc (): int =
  261. x = x + delta
  262. inc delta
  263. return x
  264. var a = accumulator(3)
  265. var b = accumulator(4)
  266. echo a() + b()
  267. Internals
  268. ---------
  269. Lambda lifting is implemented as part of the `transf` pass. The `transf`
  270. pass generates code to setup the environment and to pass it around. However,
  271. this pass does not change the types! So we have some kind of mismatch here; on
  272. the one hand the proc expression becomes an explicit tuple, on the other hand
  273. the tyProc(ccClosure) type is not changed. For C code generation it's also
  274. important the hidden formal param is `void*`:c: and not something more
  275. specialized. However the more specialized env type needs to passed to the
  276. backend somehow. We deal with this by modifying `s.ast[paramPos]` to contain
  277. the formal hidden parameter, but not `s.typ`!
  278. Notes on type and AST representation
  279. ====================================
  280. To be expanded.
  281. Integer literals
  282. ----------------
  283. In Nim, there is a redundant way to specify the type of an
  284. integer literal. First of all, it should be unsurprising that every
  285. node has a node kind. The node of an integer literal can be any of the
  286. following values::
  287. nkIntLit, nkInt8Lit, nkInt16Lit, nkInt32Lit, nkInt64Lit,
  288. nkUIntLit, nkUInt8Lit, nkUInt16Lit, nkUInt32Lit, nkUInt64Lit
  289. On top of that, there is also the `typ` field for the type. It the
  290. kind of the `typ` field can be one of the following ones, and it
  291. should be matching the literal kind::
  292. tyInt, tyInt8, tyInt16, tyInt32, tyInt64, tyUInt, tyUInt8,
  293. tyUInt16, tyUInt32, tyUInt64
  294. Then there is also the integer literal type. This is a specific type
  295. that is implicitly convertible into the requested type if the
  296. requested type can hold the value. For this to work, the type needs to
  297. know the concrete value of the literal. For example an expression
  298. `321` will be of type `int literal(321)`. This type is implicitly
  299. convertible to all integer types and ranges that contain the value
  300. `321`. That would be all builtin integer types except `uint8` and
  301. `int8` where `321` would be out of range. When this literal type is
  302. assigned to a new `var` or `let` variable, it's type will be resolved
  303. to just `int`, not `int literal(321)` unlike constants. A constant
  304. keeps the full `int literal(321)` type. Here is an example where that
  305. difference matters.
  306. .. code-block:: nim
  307. proc foo(arg: int8) =
  308. echo "def"
  309. const tmp1 = 123
  310. foo(tmp1) # OK
  311. let tmp2 = 123
  312. foo(tmp2) # Error
  313. In a context with multiple overloads, the integer literal kind will
  314. always prefer the `int` type over all other types. If none of the
  315. overloads is of type `int`, then there will be an error because of
  316. ambiguity.
  317. .. code-block:: nim
  318. proc foo(arg: int) =
  319. echo "abc"
  320. proc foo(arg: int8) =
  321. echo "def"
  322. foo(123) # output: abc
  323. proc bar(arg: int16) =
  324. echo "abc"
  325. proc bar(arg: int8) =
  326. echo "def"
  327. bar(123) # Error ambiguous call
  328. In the compiler these integer literal types are represented with the
  329. node kind `nkIntLit`, type kind `tyInt` and the member `n` of the type
  330. pointing back to the integer literal node in the ast containing the
  331. integer value. These are the properties that hold true for integer
  332. literal types.
  333. ::
  334. n.kind == nkIntLit
  335. n.typ.kind == tyInt
  336. n.typ.n == n
  337. Other literal types, such as `uint literal(123)` that would
  338. automatically convert to other integer types, but prefers to
  339. become a `uint` are not part of the Nim language.
  340. In an unchecked AST, the `typ` field is nil. The type checker will set
  341. the `typ` field accordingly to the node kind. Nodes of kind `nkIntLit`
  342. will get the integer literal type (e.g. `int literal(123)`). Nodes of
  343. kind `nkUIntLit` will get type `uint` (kind `tyUint`), etc.
  344. This also means that it is not possible to write a literal in an
  345. unchecked AST that will after sem checking just be of type `int` and
  346. not implicitly convertible to other integer types. This only works for
  347. all integer types that are not `int`.