|
| 1 | +--- |
| 2 | +layout: doc-page |
| 3 | +title: Contexts |
| 4 | +--- |
| 5 | + |
| 6 | +`dotc` has almost no global state (with the exception of the name table, |
| 7 | +which hashes strings into unique names). Instead, all |
| 8 | +essential bits of information that can vary over a compiler [run](./lifecycle.md) are collected |
| 9 | +in a `Context` (defined in [Contexts]). |
| 10 | + |
| 11 | +Most methods in the compiler depend on an implicit anonymous `Context` parameter, |
| 12 | +and a typical definition looks like the following: |
| 13 | +```scala |
| 14 | +import dotty.tools.dotc.Contexts.{Context, ctx} |
| 15 | + |
| 16 | +def doFoo(using Context): Unit = |
| 17 | + val current = ctx.run // access the Context parameter with `ctx` |
| 18 | +``` |
| 19 | + |
| 20 | +## Memory Leaks |
| 21 | +> **Careful:** Contexts can be heavy so beware of memory leaks |
| 22 | +
|
| 23 | +It is good practice to ensure that implicit contexts are not |
| 24 | +captured in closures or other long-lived objects, in order to avoid space leaks |
| 25 | +in the case where a closure can survive several compiler runs (e.g. a |
| 26 | +lazy completer for a library class that is never required). In that case, the |
| 27 | +convention is that the `Context` be an explicit parameter, to track its usage. |
| 28 | + |
| 29 | +## Context Properties |
| 30 | + |
| 31 | +| Context property | description | |
| 32 | +|-------------------|----------------------------------------| |
| 33 | +| `compilationUnit` | current compilation unit | |
| 34 | +| `phase` | current phase | |
| 35 | +| `run` | current run | |
| 36 | +| `period` | current period | |
| 37 | +| `settings` | the config passed to the compiler | |
| 38 | +| `reporter` | operations for logging errors/warnings | |
| 39 | +| `definitions` | the standard built in definitions | |
| 40 | +| `platform` | operations for the underlying platform | |
| 41 | +| `tree` | current tree | |
| 42 | +| `scope` | current scope | |
| 43 | +| `typer` | current typer | |
| 44 | +| `owner` | current owner symbol | |
| 45 | +| `outer` | outer Context | |
| 46 | +| `mode` | type checking mode | |
| 47 | +| `typerState` | | |
| 48 | +| `searchHistory` | | |
| 49 | +| `implicits` | | |
| 50 | +| ... | and so on | |
| 51 | + |
| 52 | + |
| 53 | +[Contexts]: https://github.com/lampepfl/dotty/blob/master/compiler/src/dotty/tools/dotc/core/Contexts.scala |
0 commit comments