0
# Context Management
1
2
Context system providing compilation state management, phase execution control, and configuration handling throughout the Scala 3 compilation pipeline.
3
4
## Capabilities
5
6
### Context Core API
7
8
Central context management providing access to compilation state, settings, and execution control.
9
10
```scala { .api }
11
/**
12
* Context management for compilation phases
13
* Provides access to compilation state, settings, and phase information
14
*/
15
object Contexts {
16
/**
17
* Get current compilation context
18
* Implicit context parameter pattern for context threading
19
* @param ctx Implicit context parameter
20
* @return The provided context (identity function for context threading)
21
*/
22
def ctx(using ctx: Context): Context
23
24
/**
25
* Run operation with given context
26
* Executes the provided operation with a specific context in scope
27
* @param c Context to use for the operation
28
* @param op Operation to execute with the context
29
* @return Result of the operation
30
*/
31
def inContext[T](c: Context)(inline op: Context ?=> T): T
32
33
/**
34
* Execute operation at specific compilation phase
35
* Temporarily switches to the specified phase for the duration of the operation
36
* @param phase Target compilation phase
37
* @param op Operation to execute at the specified phase
38
* @param ctx Current compilation context
39
* @return Result of the operation executed at the target phase
40
*/
41
def atPhase[T](phase: Phase)(inline op: Context ?=> T)(using Context): T
42
43
/**
44
* Execute operation with fresh context
45
* Creates a new context with modified settings for the operation
46
* @param modifications Context modifications to apply
47
* @param op Operation to execute with fresh context
48
* @param ctx Base context to derive from
49
* @return Result of the operation
50
*/
51
def freshContext[T](modifications: Context => Context)(op: Context ?=> T)(using Context): T
52
}
53
```
54
55
**Usage Examples:**
56
57
```scala
58
import dotty.tools.dotc.core.Contexts._
59
import dotty.tools.dotc.core.Phases.Phase
60
61
// Basic context usage
62
def analyzeTree(tree: Tree)(using Context): Unit = {
63
val currentPhase = ctx.phase
64
println(s"Analyzing tree in phase: ${currentPhase.phaseName}")
65
}
66
67
// Execute at specific phase
68
def getTypeAtPhase(tree: Tree, targetPhase: Phase)(using Context): Type = {
69
atPhase(targetPhase) {
70
tree.tpe // Get type as it exists at target phase
71
}
72
}
73
74
// Create fresh context with modifications
75
def compileWithWarnings(source: SourceFile)(using Context): Unit = {
76
freshContext(_.fresh.setSetting(ctx.settings.Xfatal_warnings, true)) {
77
// Compile with fatal warnings enabled
78
compile(source)
79
}
80
}
81
```
82
83
### Context Creation and Management
84
85
Context lifecycle management and creation utilities for different compilation scenarios.
86
87
```scala { .api }
88
/**
89
* Context creation and initialization utilities
90
*/
91
object ContextOps {
92
/**
93
* Create initial context for compilation
94
* Sets up base context with default settings and definitions
95
* @return Freshly initialized compilation context
96
*/
97
def initialContext(): Context
98
99
/**
100
* Create context for specific compilation unit
101
* @param unit Compilation unit to create context for
102
* @param base Base context to derive from
103
* @return Context configured for the compilation unit
104
*/
105
def contextFor(unit: CompilationUnit, base: Context): Context
106
107
/**
108
* Create child context with modified phase
109
* @param parent Parent context
110
* @param newPhase Phase to set in child context
111
* @return Child context with updated phase
112
*/
113
def withPhase(parent: Context, newPhase: Phase): Context
114
115
/**
116
* Create context with additional imports
117
* @param base Base context
118
* @param imports Additional imports to add to scope
119
* @return Context with expanded import scope
120
*/
121
def withImports(base: Context, imports: List[Symbol]): Context
122
}
123
```
124
125
### Context Properties
126
127
Access to context properties including settings, definitions, and phase information.
128
129
```scala { .api }
130
/**
131
* Compilation context containing settings, symbols, and phase information
132
* Central state container for compilation process
133
*/
134
abstract class Context {
135
/**
136
* Current compilation settings
137
* @return Settings object containing all compiler configuration
138
*/
139
def settings: Settings
140
141
/**
142
* Built-in definitions and standard library symbols
143
* @return Definitions object providing access to standard symbols
144
*/
145
def definitions: Definitions
146
147
/**
148
* Current compilation phase
149
* @return Phase object representing current compilation stage
150
*/
151
def phase: Phase
152
153
/**
154
* Current compilation run
155
* @return Run object managing current compilation execution
156
*/
157
def run: Run
158
159
/**
160
* Symbol table and scope information
161
* @return Current scope containing visible symbols
162
*/
163
def scope: Scope
164
165
/**
166
* Reporter for diagnostic messages
167
* @return Reporter instance for this context
168
*/
169
def reporter: Reporter
170
171
/**
172
* Source file being compiled (if applicable)
173
* @return Optional source file for contexts associated with specific files
174
*/
175
def source: Option[SourceFile]
176
177
/**
178
* Compilation unit being processed (if applicable)
179
* @return Optional compilation unit for contexts associated with specific units
180
*/
181
def compilationUnit: Option[CompilationUnit]
182
183
/**
184
* Create fresh child context
185
* @return New context derived from this context
186
*/
187
def fresh: Context
188
189
/**
190
* Check if context is in given phase
191
* @param phase Phase to check against
192
* @return True if context is currently in the specified phase
193
*/
194
def isAfterPhase(phase: Phase): Boolean
195
196
/**
197
* Get symbol at current scope
198
* @param name Name to lookup
199
* @return Symbol matching the name, or NoSymbol if not found
200
*/
201
def lookupSymbol(name: Name): Symbol
202
}
203
```
204
205
### Settings Management
206
207
Compiler settings access and modification within contexts.
208
209
```scala { .api }
210
/**
211
* Compiler settings and configuration
212
* Provides access to all compilation parameters and flags
213
*/
214
abstract class Settings {
215
/**
216
* Output directory for generated class files
217
*/
218
def outputDir: String
219
220
/**
221
* Compilation classpath
222
*/
223
def classpath: List[String]
224
225
/**
226
* Source path for finding source files
227
*/
228
def sourcepath: List[String]
229
230
/**
231
* Scala language version
232
*/
233
def scalaVersion: String
234
235
/**
236
* Enable verbose output
237
*/
238
def verbose: Boolean
239
240
/**
241
* Treat warnings as errors
242
*/
243
def Xfatal_warnings: Boolean
244
245
/**
246
* Enable experimental features
247
*/
248
def experimental: Boolean
249
250
/**
251
* Target JVM version
252
*/
253
def target: String
254
255
/**
256
* Enable specific language features
257
*/
258
def feature: Boolean
259
260
/**
261
* Show deprecation warnings
262
*/
263
def deprecation: Boolean
264
265
/**
266
* Enable unchecked warnings
267
*/
268
def unchecked: Boolean
269
}
270
```
271
272
### Phase Context Operations
273
274
Specialized operations for working with phase-specific contexts.
275
276
```scala { .api }
277
/**
278
* Phase-specific context operations
279
*/
280
object PhaseContext {
281
/**
282
* Execute operation in all phases
283
* Runs the operation once for each compilation phase
284
* @param op Operation to execute in each phase
285
* @param ctx Base context
286
* @return List of results from each phase
287
*/
288
def inAllPhases[T](op: Context ?=> T)(using Context): List[T]
289
290
/**
291
* Execute operation from current phase to end
292
* @param op Operation to execute
293
* @param ctx Current context
294
* @return List of results from current phase onwards
295
*/
296
def fromCurrentPhase[T](op: Context ?=> T)(using Context): List[T]
297
298
/**
299
* Execute operation in phase range
300
* @param startPhase Starting phase (inclusive)
301
* @param endPhase Ending phase (inclusive)
302
* @param op Operation to execute
303
* @param ctx Current context
304
* @return List of results from the phase range
305
*/
306
def inPhaseRange[T](startPhase: Phase, endPhase: Phase)(op: Context ?=> T)(using Context): List[T]
307
308
/**
309
* Get previous phase context
310
* @param ctx Current context
311
* @return Context for the previous phase, or None if at first phase
312
*/
313
def previousPhase(using Context): Option[Context]
314
315
/**
316
* Get next phase context
317
* @param ctx Current context
318
* @return Context for the next phase, or None if at last phase
319
*/
320
def nextPhase(using Context): Option[Context]
321
}
322
```
323
324
**Usage Examples:**
325
326
```scala
327
import dotty.tools.dotc.core.Contexts._
328
import dotty.tools.dotc.core.Phases._
329
330
// Execute in multiple phases
331
def analyzeAcrossPhases(tree: Tree)(using Context): Unit = {
332
val results = PhaseContext.inAllPhases {
333
(tree.symbol.name.toString, ctx.phase.phaseName, tree.tpe.toString)
334
}
335
results.foreach { case (name, phase, tpe) =>
336
println(s"$name in $phase: $tpe")
337
}
338
}
339
340
// Check phase-specific conditions
341
def isAfterTyper(using Context): Boolean = {
342
ctx.isAfterPhase(typerPhase)
343
}
344
345
// Context-dependent symbol lookup
346
def findSymbolInCurrentScope(name: String)(using Context): Symbol = {
347
val termName = name.toTermName
348
ctx.lookupSymbol(termName)
349
}
350
```
351
352
## Types
353
354
### Phase
355
356
```scala { .api }
357
/**
358
* Compilation phase with name and execution logic
359
*/
360
abstract class Phase {
361
def phaseName: String
362
def run(using Context): Unit
363
def isRunnable(using Context): Boolean
364
def description: String
365
}
366
```
367
368
### Symbol
369
370
```scala { .api }
371
/**
372
* Symbol representing a definition (class, method, value, etc.)
373
*/
374
abstract class Symbol {
375
def name: Name
376
def fullName: String
377
def pos: Position
378
def flags: FlagSet
379
def info: Type
380
def owner: Symbol
381
}
382
```
383
384
### Scope
385
386
```scala { .api }
387
/**
388
* Symbol scope for name resolution
389
*/
390
abstract class Scope {
391
def lookup(name: Name): Symbol
392
def enter(sym: Symbol): Unit
393
def symbols: List[Symbol]
394
def isEmpty: Boolean
395
}
396
```
397
398
### Name
399
400
```scala { .api }
401
/**
402
* Name representation for symbols
403
*/
404
abstract class Name {
405
def toString: String
406
def length: Int
407
def isEmpty: Boolean
408
}
409
410
/**
411
* Term name (for values, methods, objects)
412
*/
413
abstract class TermName extends Name
414
415
/**
416
* Type name (for classes, traits, type aliases)
417
*/
418
abstract class TypeName extends Name
419
```
420
421
### Type
422
423
```scala { .api }
424
/**
425
* Type representation in the type system
426
*/
427
abstract class Type {
428
def show: String
429
def widen: Type
430
def dealias: Type
431
def symbol: Symbol
432
}
433
```