intern.rst 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672
  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. Debugging the compiler
  54. ======================
  55. Bisecting for regressions
  56. -------------------------
  57. There are often times when there is a bug that is caused by a regression in the
  58. compiler or stdlib. Bisecting the Nim repo commits is a usefull tool to identify
  59. what commit introduced the regression.
  60. Even if it's not known whether a bug is caused by a regression, bisection can reduce
  61. debugging time by ruling it out. If the bug is found to be a regression, then you
  62. focus on the changes introduced by that one specific commit.
  63. `koch temp`:cmd: returns 125 as the exit code in case the compiler
  64. compilation fails. This exit code tells `git bisect`:cmd: to skip the
  65. current commit:
  66. .. code:: cmd
  67. git bisect start bad-commit good-commit
  68. git bisect run ./koch temp -r c test-source.nim
  69. You can also bisect using custom options to build the compiler, for example if
  70. you don't need a debug version of the compiler (which runs slower), you can replace
  71. `./koch temp`:cmd: by explicit compilation command, see `Bootstrapping the compiler`_.
  72. Building an instrumented compiler
  73. ---------------------------------
  74. Considering that a useful method of debugging the compiler is inserting debug
  75. logging, or changing code and then observing the outcome of a testcase, it is
  76. fastest to build a compiler that is instrumented for debugging from an
  77. existing release build. `koch temp`:cmd: provides a convenient method of doing
  78. just that.
  79. By default running `koch temp`:cmd: will build a lean version of the compiler
  80. with `-d:debug`:option: enabled. The compiler is written to `bin/nim_temp` by
  81. default. A lean version of the compiler lacks JS and documentation generation.
  82. `bin/nim_temp` can be directly used to run testcases, or used with testament
  83. with `testament --nim:bin/nim_temp r tests/category/tsometest`:cmd:.
  84. `koch temp`:cmd: will build the temporary compiler with the `-d:debug`:option:
  85. enabled. Here are compiler options that are of interest for debugging:
  86. * `-d:debug`:option:\: enables `assert` statements and stacktraces and all
  87. runtime checks
  88. * `--opt:speed`:option:\: build with optimizations enabled
  89. * `--debugger:native`:option:\: enables `--debuginfo --lineDir:on`:option: for using
  90. a native debugger like GDB, LLDB or CDB
  91. * `-d:nimDebug`:option: cause calls to `quit` to raise an assertion exception
  92. * `-d:nimDebugUtils`:option:\: enables various debugging utilities;
  93. see `compiler/debugutils`
  94. * `-d:stacktraceMsgs -d:nimCompilerStacktraceHints`:option:\: adds some additional
  95. stacktrace hints; see https://github.com/nim-lang/Nim/pull/13351
  96. * `-u:leanCompiler`:option:\: enable JS and doc generation
  97. Another method to build and run the compiler is directly through `koch`:cmd:\:
  98. .. code:: cmd
  99. koch temp [options] c test.nim
  100. # (will build with js support)
  101. koch temp [options] js test.nim
  102. # (will build with doc support)
  103. koch temp [options] doc test.nim
  104. Debug logging
  105. -------------
  106. "Printf debugging" is still the most appropriate way to debug many problems
  107. arising in compiler development. The typical usage of breakpoints to debug
  108. the code is often less practical, because almost all of the code paths in the
  109. compiler will be executed hundreds of times before a particular section of the
  110. tested program is reached where the newly developed code must be activated.
  111. To work-around this problem, you'll typically introduce an if statement in the
  112. compiler code detecting more precisely the conditions where the tested feature
  113. is being used. One very common way to achieve this is to use the `mdbg` condition,
  114. which will be true only in contexts, processing expressions and statements from
  115. the currently compiled main module:
  116. .. code-block:: nim
  117. # inside some compiler module
  118. if mdbg:
  119. debug someAstNode
  120. Using the `isCompilerDebug`:nim: condition along with inserting some statements
  121. into the testcase provides more granular logging:
  122. .. code-block:: nim
  123. # compilermodule.nim
  124. if isCompilerDebug():
  125. debug someAstNode
  126. # testcase.nim
  127. proc main =
  128. {.define(nimCompilerDebug).}
  129. let a = 2.5 * 3
  130. {.undef(nimCompilerDebug).}
  131. Logging can also be scoped to a specific filename as well. This will of course
  132. match against every module with that name.
  133. .. code-block:: nim
  134. if `??`(conf, n.info, "module.nim"):
  135. debug(n)
  136. The above examples also makes use of the `debug`:nim: proc, which is able to
  137. print a human-readable form of an arbitrary AST tree. Other common ways to print
  138. information about the internal compiler types include:
  139. .. code-block:: nim
  140. # pretty print PNode
  141. # pretty prints the Nim ast
  142. echo renderTree(someNode)
  143. # pretty prints the Nim ast, but annotates symbol IDs
  144. echo renderTree(someNode, {renderIds})
  145. # pretty print ast as JSON
  146. debug(someNode)
  147. # print as YAML
  148. echo treeToYaml(config, someNode)
  149. # pretty print PType
  150. # print type name
  151. echo typeToString(someType)
  152. # pretty print as JSON
  153. debug(someType)
  154. # print as YAML
  155. echo typeToYaml(config, someType)
  156. # pretty print PSym
  157. # print the symbol's name
  158. echo symbol.name.s
  159. # pretty print as JSON
  160. debug(symbol)
  161. # print as YAML
  162. echo symToYaml(config, symbol)
  163. # pretty print TLineInfo
  164. lineInfoToStr(lineInfo)
  165. # print the structure of any type
  166. repr(someVar)
  167. Here are some other helpful utilities:
  168. .. code-block:: nim
  169. # how did execution reach this location?
  170. writeStackTrace()
  171. These procs may not already be imported by the module you're editing.
  172. You can import them directly for debugging:
  173. .. code-block:: nim
  174. from astalgo import debug
  175. from types import typeToString
  176. from renderer import renderTree
  177. from msgs import `??`
  178. Native debugging
  179. ----------------
  180. Stepping through the compiler with a native debugger is a very powerful tool to
  181. both learn and debug it. However, there is still the need to constrain when
  182. breakpoints are triggered. The same methods as in `Debug logging`_ can be applied
  183. here when combined with calls to the debug helpers `enteringDebugSection()`:nim:
  184. and `exitingDebugSection()`:nim:.
  185. #. Compile the temp compiler with `--debugger:native -d:nimDebugUtils`:option:
  186. #. Set your desired breakpoints or watchpoints.
  187. #. Configure your debugger:
  188. * GDB: execute `source tools/compiler.gdb` at startup
  189. * LLDB execute `command source tools/compiler.lldb` at startup
  190. #. Use one of the scoping helpers like so:
  191. .. code-block:: nim
  192. if isCompilerDebug():
  193. enteringDebugSection()
  194. else:
  195. exitingDebugSection()
  196. A caveat of this method is that all breakpoints and watchpoints are enabled or
  197. disabled. Also, due to a bug, only breakpoints can be constrained for LLDB.
  198. The compiler's architecture
  199. ===========================
  200. Nim uses the classic compiler architecture: A lexer/scanner feeds tokens to a
  201. parser. The parser builds a syntax tree that is used by the code generators.
  202. This syntax tree is the interface between the parser and the code generator.
  203. It is essential to understand most of the compiler's code.
  204. Semantic analysis is separated from parsing.
  205. .. include:: filelist.txt
  206. The syntax tree
  207. ---------------
  208. The syntax tree consists of nodes which may have an arbitrary number of
  209. children. Types and symbols are represented by other nodes, because they
  210. may contain cycles. The AST changes its shape after semantic checking. This
  211. is needed to make life easier for the code generators. See the "ast" module
  212. for the type definitions. The `macros <macros.html>`_ module contains many
  213. examples how the AST represents each syntactic structure.
  214. Runtimes
  215. ========
  216. Nim has two different runtimes, the "old runtime" and the "new runtime". The old
  217. runtime supports the old GCs (markAndSweep, refc, Boehm), the new runtime supports
  218. ARC/ORC. The new runtime is active `when defined(nimV2)`.
  219. Coding Guidelines
  220. =================
  221. * We follow Nim's official style guide, see `<nep1.html>`_.
  222. * Max line length is 100 characters.
  223. * Provide spaces around binary operators if that enhances readability.
  224. * Use a space after a colon, but not before it.
  225. * [deprecated] Start types with a capital `T`, unless they are
  226. pointers/references which start with `P`.
  227. * Prefer `import package`:nim: over `from package import symbol`:nim:.
  228. See also the `API naming design <apis.html>`_ document.
  229. Porting to new platforms
  230. ========================
  231. Porting Nim to a new architecture is pretty easy, since C is the most
  232. portable programming language (within certain limits) and Nim generates
  233. C code, porting the code generator is not necessary.
  234. POSIX-compliant systems on conventional hardware are usually pretty easy to
  235. port: Add the platform to `platform` (if it is not already listed there),
  236. check that the OS, System modules work and recompile Nim.
  237. The only case where things aren't as easy is when old runtime's garbage
  238. collectors need some assembler tweaking to work. The default
  239. implementation uses C's `setjmp`:c: function to store all registers
  240. on the hardware stack. It may be necessary that the new platform needs to
  241. replace this generic code by some assembler code.
  242. Files that may need changed for your platform include:
  243. * `compiler/platform.nim`
  244. Add os/cpu properties.
  245. * `lib/system.nim`
  246. Add os/cpu to the documentation for `system.hostOS` and `system.hostCPU`.
  247. * `compiler/options.nim`
  248. Add special os/cpu property checks in `isDefined`.
  249. * `compiler/installer.ini`
  250. Add os/cpu to `Project.Platforms` field.
  251. * `lib/system/platforms.nim`
  252. Add os/cpu.
  253. * `lib/pure/include/osseps.nim`
  254. Add os specializations.
  255. * `lib/pure/distros.nim`
  256. Add os, package handler.
  257. * `tools/niminst/makefile.nimf`
  258. Add os/cpu compiler/linker flags.
  259. * `tools/niminst/buildsh.nimf`
  260. Add os/cpu compiler/linker flags.
  261. If the `--os` or `--cpu` options aren't passed to the compiler, then Nim will
  262. determine the current host os, cpu and endianess from `system.cpuEndian`,
  263. `system.hostOS` and `system.hostCPU`. Those values are derived from
  264. `compiler/platform.nim`.
  265. In order for the new platform to be bootstrapped from the `csources`, it must:
  266. * have `compiler/platform.nim` updated
  267. * have `compiler/installer.ini` updated
  268. * have `tools/niminst/buildsh.nimf` updated
  269. * have `tools/niminst/makefile.nimf` updated
  270. * be backported to the Nim version used by the `csources`
  271. * the new `csources` must be pushed
  272. * the new `csources` revision must be updated in `config/build_config.txt`
  273. Runtime type information
  274. ========================
  275. **Note**: This section describes the "old runtime".
  276. *Runtime type information* (RTTI) is needed for several aspects of the Nim
  277. programming language:
  278. Garbage collection
  279. The old GCs use the RTTI for traversing abitrary Nim types, but usually
  280. only the `marker` field which contains a proc that does the traversal.
  281. Complex assignments
  282. Sequences and strings are implemented as
  283. pointers to resizeable buffers, but Nim requires copying for
  284. assignments. Apart from RTTI the compiler also generates copy procedures
  285. as a specialization.
  286. We already know the type information as a graph in the compiler.
  287. Thus we need to serialize this graph as RTTI for C code generation.
  288. Look at the file ``lib/system/hti.nim`` for more information.
  289. Magics and compilerProcs
  290. ========================
  291. The `system` module contains the part of the RTL which needs support by
  292. compiler magic. The C code generator generates the C code for it, just like any other
  293. module. However, calls to some procedures like `addInt` are inserted by
  294. the generator. Therefore there is a table (`compilerprocs`)
  295. with all symbols that are marked as `compilerproc`. `compilerprocs` are
  296. needed by the code generator. A `magic` proc is not the same as a
  297. `compilerproc`: A `magic` is a proc that needs compiler magic for its
  298. semantic checking, a `compilerproc` is a proc that is used by the code
  299. generator.
  300. Code generation for closures
  301. ============================
  302. Code generation for closures is implemented by `lambda lifting`:idx:.
  303. Design
  304. ------
  305. A `closure` proc var can call ordinary procs of the default Nim calling
  306. convention. But not the other way round! A closure is implemented as a
  307. `tuple[prc, env]`. `env` can be nil implying a call without a closure.
  308. This means that a call through a closure generates an `if` but the
  309. interoperability is worth the cost of the `if`. Thunk generation would be
  310. possible too, but it's slightly more effort to implement.
  311. Tests with GCC on Amd64 showed that it's really beneficial if the
  312. 'environment' pointer is passed as the last argument, not as the first argument.
  313. Proper thunk generation is harder because the proc that is to wrap
  314. could stem from a complex expression:
  315. .. code-block:: nim
  316. receivesClosure(returnsDefaultCC[i])
  317. A thunk would need to call 'returnsDefaultCC[i]' somehow and that would require
  318. an *additional* closure generation... Ok, not really, but it requires to pass
  319. the function to call. So we'd end up with 2 indirect calls instead of one.
  320. Another much more severe problem which this solution is that it's not GC-safe
  321. to pass a proc pointer around via a generic `ref` type.
  322. Example code:
  323. .. code-block:: nim
  324. proc add(x: int): proc (y: int): int {.closure.} =
  325. return proc (y: int): int =
  326. return x + y
  327. var add2 = add(2)
  328. echo add2(5) #OUT 7
  329. This should produce roughly this code:
  330. .. code-block:: nim
  331. type
  332. Env = ref object
  333. x: int # data
  334. proc anon(y: int, c: Env): int =
  335. return y + c.x
  336. proc add(x: int): tuple[prc, data] =
  337. var env: Env
  338. new env
  339. env.x = x
  340. result = (anon, env)
  341. var add2 = add(2)
  342. let tmp = if add2.data == nil: add2.prc(5) else: add2.prc(5, add2.data)
  343. echo tmp
  344. Beware of nesting:
  345. .. code-block:: nim
  346. proc add(x: int): proc (y: int): proc (z: int): int {.closure.} {.closure.} =
  347. return lambda (y: int): proc (z: int): int {.closure.} =
  348. return lambda (z: int): int =
  349. return x + y + z
  350. var add24 = add(2)(4)
  351. echo add24(5) #OUT 11
  352. This should produce roughly this code:
  353. .. code-block:: nim
  354. type
  355. EnvX = ref object
  356. x: int # data
  357. EnvY = ref object
  358. y: int
  359. ex: EnvX
  360. proc lambdaZ(z: int, ey: EnvY): int =
  361. return ey.ex.x + ey.y + z
  362. proc lambdaY(y: int, ex: EnvX): tuple[prc, data: EnvY] =
  363. var ey: EnvY
  364. new ey
  365. ey.y = y
  366. ey.ex = ex
  367. result = (lambdaZ, ey)
  368. proc add(x: int): tuple[prc, data: EnvX] =
  369. var ex: EnvX
  370. ex.x = x
  371. result = (labmdaY, ex)
  372. var tmp = add(2)
  373. var tmp2 = tmp.fn(4, tmp.data)
  374. var add24 = tmp2.fn(4, tmp2.data)
  375. echo add24(5)
  376. We could get rid of nesting environments by always inlining inner anon procs.
  377. More useful is escape analysis and stack allocation of the environment,
  378. however.
  379. Accumulator
  380. -----------
  381. .. code-block:: nim
  382. proc getAccumulator(start: int): proc (): int {.closure} =
  383. var i = start
  384. return lambda: int =
  385. inc i
  386. return i
  387. proc p =
  388. var delta = 7
  389. proc accumulator(start: int): proc(): int =
  390. var x = start-1
  391. result = proc (): int =
  392. x = x + delta
  393. inc delta
  394. return x
  395. var a = accumulator(3)
  396. var b = accumulator(4)
  397. echo a() + b()
  398. Internals
  399. ---------
  400. Lambda lifting is implemented as part of the `transf` pass. The `transf`
  401. pass generates code to setup the environment and to pass it around. However,
  402. this pass does not change the types! So we have some kind of mismatch here; on
  403. the one hand the proc expression becomes an explicit tuple, on the other hand
  404. the tyProc(ccClosure) type is not changed. For C code generation it's also
  405. important the hidden formal param is `void*`:c: and not something more
  406. specialized. However the more specialized env type needs to passed to the
  407. backend somehow. We deal with this by modifying `s.ast[paramPos]` to contain
  408. the formal hidden parameter, but not `s.typ`!
  409. Notes on type and AST representation
  410. ====================================
  411. To be expanded.
  412. Integer literals
  413. ----------------
  414. In Nim, there is a redundant way to specify the type of an
  415. integer literal. First of all, it should be unsurprising that every
  416. node has a node kind. The node of an integer literal can be any of the
  417. following values::
  418. nkIntLit, nkInt8Lit, nkInt16Lit, nkInt32Lit, nkInt64Lit,
  419. nkUIntLit, nkUInt8Lit, nkUInt16Lit, nkUInt32Lit, nkUInt64Lit
  420. On top of that, there is also the `typ` field for the type. It the
  421. kind of the `typ` field can be one of the following ones, and it
  422. should be matching the literal kind::
  423. tyInt, tyInt8, tyInt16, tyInt32, tyInt64, tyUInt, tyUInt8,
  424. tyUInt16, tyUInt32, tyUInt64
  425. Then there is also the integer literal type. This is a specific type
  426. that is implicitly convertible into the requested type if the
  427. requested type can hold the value. For this to work, the type needs to
  428. know the concrete value of the literal. For example an expression
  429. `321` will be of type `int literal(321)`. This type is implicitly
  430. convertible to all integer types and ranges that contain the value
  431. `321`. That would be all builtin integer types except `uint8` and
  432. `int8` where `321` would be out of range. When this literal type is
  433. assigned to a new `var` or `let` variable, it's type will be resolved
  434. to just `int`, not `int literal(321)` unlike constants. A constant
  435. keeps the full `int literal(321)` type. Here is an example where that
  436. difference matters.
  437. .. code-block:: nim
  438. proc foo(arg: int8) =
  439. echo "def"
  440. const tmp1 = 123
  441. foo(tmp1) # OK
  442. let tmp2 = 123
  443. foo(tmp2) # Error
  444. In a context with multiple overloads, the integer literal kind will
  445. always prefer the `int` type over all other types. If none of the
  446. overloads is of type `int`, then there will be an error because of
  447. ambiguity.
  448. .. code-block:: nim
  449. proc foo(arg: int) =
  450. echo "abc"
  451. proc foo(arg: int8) =
  452. echo "def"
  453. foo(123) # output: abc
  454. proc bar(arg: int16) =
  455. echo "abc"
  456. proc bar(arg: int8) =
  457. echo "def"
  458. bar(123) # Error ambiguous call
  459. In the compiler these integer literal types are represented with the
  460. node kind `nkIntLit`, type kind `tyInt` and the member `n` of the type
  461. pointing back to the integer literal node in the ast containing the
  462. integer value. These are the properties that hold true for integer
  463. literal types.
  464. ::
  465. n.kind == nkIntLit
  466. n.typ.kind == tyInt
  467. n.typ.n == n
  468. Other literal types, such as `uint literal(123)` that would
  469. automatically convert to other integer types, but prefers to
  470. become a `uint` are not part of the Nim language.
  471. In an unchecked AST, the `typ` field is nil. The type checker will set
  472. the `typ` field accordingly to the node kind. Nodes of kind `nkIntLit`
  473. will get the integer literal type (e.g. `int literal(123)`). Nodes of
  474. kind `nkUIntLit` will get type `uint` (kind `tyUint`), etc.
  475. This also means that it is not possible to write a literal in an
  476. unchecked AST that will after sem checking just be of type `int` and
  477. not implicitly convertible to other integer types. This only works for
  478. all integer types that are not `int`.