intern.rst 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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. Files that may need changed for your platform include:
  143. * `compiler/platform.nim`
  144. Add os/cpu properties.
  145. * `lib/system.nim`
  146. Add os/cpu to the documentation for `system.hostOS` and `system.hostCPU`.
  147. * `compiler/options.nim`
  148. Add special os/cpu property checks in `isDefined`.
  149. * `compiler/installer.ini`
  150. Add os/cpu to `Project.Platforms` field.
  151. * `lib/system/platforms.nim`
  152. Add os/cpu.
  153. * `lib/pure/include/osseps.nim`
  154. Add os specializations.
  155. * `lib/pure/distros.nim`
  156. Add os, package handler.
  157. * `tools/niminst/makefile.nimf`
  158. Add os/cpu compiler/linker flags.
  159. * `tools/niminst/buildsh.nimf`
  160. Add os/cpu compiler/linker flags.
  161. If the `--os` or `--cpu` options aren't passed to the compiler, then Nim will
  162. determine the current host os, cpu and endianess from `system.cpuEndian`,
  163. `system.hostOS` and `system.hostCPU`. Those values are derived from
  164. `compiler/platform.nim`.
  165. In order for the new platform to be bootstrapped from the `csources`, it must:
  166. * have `compiler/platform.nim` updated
  167. * have `compiler/installer.ini` updated
  168. * have `tools/niminst/buildsh.nimf` updated
  169. * have `tools/niminst/makefile.nimf` updated
  170. * be backported to the Nim version used by the `csources`
  171. * the new `csources` must be pushed
  172. * the new `csources` revision must be updated in `config/build_config.txt`
  173. Runtime type information
  174. ========================
  175. **Note**: This section describes the "old runtime".
  176. *Runtime type information* (RTTI) is needed for several aspects of the Nim
  177. programming language:
  178. Garbage collection
  179. The old GCs use the RTTI for traversing abitrary Nim types, but usually
  180. only the `marker` field which contains a proc that does the traversal.
  181. Complex assignments
  182. Sequences and strings are implemented as
  183. pointers to resizeable buffers, but Nim requires copying for
  184. assignments. Apart from RTTI the compiler also generates copy procedures
  185. as a specialization.
  186. We already know the type information as a graph in the compiler.
  187. Thus we need to serialize this graph as RTTI for C code generation.
  188. Look at the file ``lib/system/hti.nim`` for more information.
  189. Magics and compilerProcs
  190. ========================
  191. The `system` module contains the part of the RTL which needs support by
  192. compiler magic. The C code generator generates the C code for it, just like any other
  193. module. However, calls to some procedures like `addInt` are inserted by
  194. the generator. Therefore there is a table (`compilerprocs`)
  195. with all symbols that are marked as `compilerproc`. `compilerprocs` are
  196. needed by the code generator. A `magic` proc is not the same as a
  197. `compilerproc`: A `magic` is a proc that needs compiler magic for its
  198. semantic checking, a `compilerproc` is a proc that is used by the code
  199. generator.
  200. Code generation for closures
  201. ============================
  202. Code generation for closures is implemented by `lambda lifting`:idx:.
  203. Design
  204. ------
  205. A `closure` proc var can call ordinary procs of the default Nim calling
  206. convention. But not the other way round! A closure is implemented as a
  207. `tuple[prc, env]`. `env` can be nil implying a call without a closure.
  208. This means that a call through a closure generates an `if` but the
  209. interoperability is worth the cost of the `if`. Thunk generation would be
  210. possible too, but it's slightly more effort to implement.
  211. Tests with GCC on Amd64 showed that it's really beneficial if the
  212. 'environment' pointer is passed as the last argument, not as the first argument.
  213. Proper thunk generation is harder because the proc that is to wrap
  214. could stem from a complex expression:
  215. .. code-block:: nim
  216. receivesClosure(returnsDefaultCC[i])
  217. A thunk would need to call 'returnsDefaultCC[i]' somehow and that would require
  218. an *additional* closure generation... Ok, not really, but it requires to pass
  219. the function to call. So we'd end up with 2 indirect calls instead of one.
  220. Another much more severe problem which this solution is that it's not GC-safe
  221. to pass a proc pointer around via a generic `ref` type.
  222. Example code:
  223. .. code-block:: nim
  224. proc add(x: int): proc (y: int): int {.closure.} =
  225. return proc (y: int): int =
  226. return x + y
  227. var add2 = add(2)
  228. echo add2(5) #OUT 7
  229. This should produce roughly this code:
  230. .. code-block:: nim
  231. type
  232. Env = ref object
  233. x: int # data
  234. proc anon(y: int, c: Env): int =
  235. return y + c.x
  236. proc add(x: int): tuple[prc, data] =
  237. var env: Env
  238. new env
  239. env.x = x
  240. result = (anon, env)
  241. var add2 = add(2)
  242. let tmp = if add2.data == nil: add2.prc(5) else: add2.prc(5, add2.data)
  243. echo tmp
  244. Beware of nesting:
  245. .. code-block:: nim
  246. proc add(x: int): proc (y: int): proc (z: int): int {.closure.} {.closure.} =
  247. return lambda (y: int): proc (z: int): int {.closure.} =
  248. return lambda (z: int): int =
  249. return x + y + z
  250. var add24 = add(2)(4)
  251. echo add24(5) #OUT 11
  252. This should produce roughly this code:
  253. .. code-block:: nim
  254. type
  255. EnvX = ref object
  256. x: int # data
  257. EnvY = ref object
  258. y: int
  259. ex: EnvX
  260. proc lambdaZ(z: int, ey: EnvY): int =
  261. return ey.ex.x + ey.y + z
  262. proc lambdaY(y: int, ex: EnvX): tuple[prc, data: EnvY] =
  263. var ey: EnvY
  264. new ey
  265. ey.y = y
  266. ey.ex = ex
  267. result = (lambdaZ, ey)
  268. proc add(x: int): tuple[prc, data: EnvX] =
  269. var ex: EnvX
  270. ex.x = x
  271. result = (labmdaY, ex)
  272. var tmp = add(2)
  273. var tmp2 = tmp.fn(4, tmp.data)
  274. var add24 = tmp2.fn(4, tmp2.data)
  275. echo add24(5)
  276. We could get rid of nesting environments by always inlining inner anon procs.
  277. More useful is escape analysis and stack allocation of the environment,
  278. however.
  279. Accumulator
  280. -----------
  281. .. code-block:: nim
  282. proc getAccumulator(start: int): proc (): int {.closure} =
  283. var i = start
  284. return lambda: int =
  285. inc i
  286. return i
  287. proc p =
  288. var delta = 7
  289. proc accumulator(start: int): proc(): int =
  290. var x = start-1
  291. result = proc (): int =
  292. x = x + delta
  293. inc delta
  294. return x
  295. var a = accumulator(3)
  296. var b = accumulator(4)
  297. echo a() + b()
  298. Internals
  299. ---------
  300. Lambda lifting is implemented as part of the `transf` pass. The `transf`
  301. pass generates code to setup the environment and to pass it around. However,
  302. this pass does not change the types! So we have some kind of mismatch here; on
  303. the one hand the proc expression becomes an explicit tuple, on the other hand
  304. the tyProc(ccClosure) type is not changed. For C code generation it's also
  305. important the hidden formal param is `void*`:c: and not something more
  306. specialized. However the more specialized env type needs to passed to the
  307. backend somehow. We deal with this by modifying `s.ast[paramPos]` to contain
  308. the formal hidden parameter, but not `s.typ`!
  309. Notes on type and AST representation
  310. ====================================
  311. To be expanded.
  312. Integer literals
  313. ----------------
  314. In Nim, there is a redundant way to specify the type of an
  315. integer literal. First of all, it should be unsurprising that every
  316. node has a node kind. The node of an integer literal can be any of the
  317. following values::
  318. nkIntLit, nkInt8Lit, nkInt16Lit, nkInt32Lit, nkInt64Lit,
  319. nkUIntLit, nkUInt8Lit, nkUInt16Lit, nkUInt32Lit, nkUInt64Lit
  320. On top of that, there is also the `typ` field for the type. It the
  321. kind of the `typ` field can be one of the following ones, and it
  322. should be matching the literal kind::
  323. tyInt, tyInt8, tyInt16, tyInt32, tyInt64, tyUInt, tyUInt8,
  324. tyUInt16, tyUInt32, tyUInt64
  325. Then there is also the integer literal type. This is a specific type
  326. that is implicitly convertible into the requested type if the
  327. requested type can hold the value. For this to work, the type needs to
  328. know the concrete value of the literal. For example an expression
  329. `321` will be of type `int literal(321)`. This type is implicitly
  330. convertible to all integer types and ranges that contain the value
  331. `321`. That would be all builtin integer types except `uint8` and
  332. `int8` where `321` would be out of range. When this literal type is
  333. assigned to a new `var` or `let` variable, it's type will be resolved
  334. to just `int`, not `int literal(321)` unlike constants. A constant
  335. keeps the full `int literal(321)` type. Here is an example where that
  336. difference matters.
  337. .. code-block:: nim
  338. proc foo(arg: int8) =
  339. echo "def"
  340. const tmp1 = 123
  341. foo(tmp1) # OK
  342. let tmp2 = 123
  343. foo(tmp2) # Error
  344. In a context with multiple overloads, the integer literal kind will
  345. always prefer the `int` type over all other types. If none of the
  346. overloads is of type `int`, then there will be an error because of
  347. ambiguity.
  348. .. code-block:: nim
  349. proc foo(arg: int) =
  350. echo "abc"
  351. proc foo(arg: int8) =
  352. echo "def"
  353. foo(123) # output: abc
  354. proc bar(arg: int16) =
  355. echo "abc"
  356. proc bar(arg: int8) =
  357. echo "def"
  358. bar(123) # Error ambiguous call
  359. In the compiler these integer literal types are represented with the
  360. node kind `nkIntLit`, type kind `tyInt` and the member `n` of the type
  361. pointing back to the integer literal node in the ast containing the
  362. integer value. These are the properties that hold true for integer
  363. literal types.
  364. ::
  365. n.kind == nkIntLit
  366. n.typ.kind == tyInt
  367. n.typ.n == n
  368. Other literal types, such as `uint literal(123)` that would
  369. automatically convert to other integer types, but prefers to
  370. become a `uint` are not part of the Nim language.
  371. In an unchecked AST, the `typ` field is nil. The type checker will set
  372. the `typ` field accordingly to the node kind. Nodes of kind `nkIntLit`
  373. will get the integer literal type (e.g. `int literal(123)`). Nodes of
  374. kind `nkUIntLit` will get type `uint` (kind `tyUint`), etc.
  375. This also means that it is not possible to write a literal in an
  376. unchecked AST that will after sem checking just be of type `int` and
  377. not implicitly convertible to other integer types. This only works for
  378. all integer types that are not `int`.