1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
|
package scala.tools.nsc.interactive
import scala.collection.mutable.{LinkedHashSet, LinkedHashMap, SynchronizedMap}
import scala.concurrent.SyncVar
import scala.tools.nsc.io.AbstractFile
import scala.tools.nsc.util.{SourceFile, Position, RangePosition, OffsetPosition, NoPosition, WorkScheduler}
import scala.tools.nsc.reporters._
import scala.tools.nsc.symtab._
import scala.tools.nsc.ast._
/** The main class of the presentation compiler in an interactive environment such as an IDE
*/
class Global(_settings: Settings, _reporter: Reporter)
extends nsc.Global(_settings, _reporter)
with ContextTrees {
self =>
/** A list indicating in which order some units should be typechecked.
* All units in firsts are typechecked before any unit not in this list
* Modified by askToDoFirst
*/
var firsts: List[AbstractFile] = List()
/** Is there a loaded unit not up-to-date wrt typechecking?
*/
var outOfDate: Boolean = false
/** A map of all loaded units to the id of the last compiler run that typechecked them
* @see NotLoaded, JustParsed
*/
val unitOfFile = new LinkedHashMap[AbstractFile, RichCompilationUnit] with
SynchronizedMap[AbstractFile, RichCompilationUnit]
/** The status value of a unit that has not yet been loaded */
final val NotLoaded = -1
/** The status value of a unit that has not yet been typechecked */
final val JustParsed = 0
/** The currently active typer run */
var currentTyperRun: TyperRun = _
/** Is a background compiler currently running? */
var compiling = false
// ----------- Overriding hooks in nsc.Global -----------------------
/** Make rangePos return a RangePosition */
override def rangePos(source: SourceFile, start: Int, mid: Int, end: Int) =
new RangePosition(source, start, mid, end)
/** Called from typechecker */
override def signalDone(context: Context, old: Tree, result: Tree) {
def integrateNew() {
context.unit.body = new TreeReplacer(old, result) transform context.unit.body
}
if (context.unit.targetPos includes result.pos) {
integrateNew()
throw new TyperResult(result)
}
pollForWork()
if (outOfDate) {
integrateNew()
throw new FreshRunReq
}
}
override def registerContext(c: Context) = c.unit match {
case u: RichCompilationUnit => addContext(u.contexts, c)
case _ =>
}
// ----------------- Polling ---------------------------------------
private var pollingEnabled = false
/** Called from runner thread and singnalDone */
def pollForWork() {
if (pollingEnabled)
scheduler.nextWorkItem() match {
case Some(action) =>
pollingEnabled = false
try {
action()
} catch {
case ex: CancelActionReq =>
} finally {
scheduler.doneWorkItem()
}
pollingEnabled = true
case None =>
}
else
scheduler.pollException()
}
// ----------------- The Background Runner Thread -----------------------
/** The current presentation compiler runner */
private var compileRunner = newRunnerThread
compileRunner.start()
/** Create a new presentation compiler runner */
def newRunnerThread: Thread = new Thread("Scala Presentation Compiler") {
override def run() {
try {
while (true) {
scheduler.waitForMoreWork()
pollForWork()
while (outOfDate) {
outOfDate = false
try {
compiling = true
backgroundCompile()
} catch {
case ex: FreshRunReq =>
} finally {
compiling = false
}
}
}
} catch {
case ex: ShutdownReq =>
;
case ex =>
ex.printStackTrace()
inform("Fatal Error: "+ex)
compileRunner = newRunnerThread
compileRunner.start()
}
}
}
/** Compile all given units
*/
private def backgroundCompile() {
inform("Starting new presentation compiler type checking pass")
val unitsToCompile = new LinkedHashSet[RichCompilationUnit] ++= unitOfFile.values
var rest = firsts
def getUnit(): RichCompilationUnit = rest match {
case List() =>
unitsToCompile.head
case f :: fs =>
unitsToCompile.find(_.source.file == f) match {
case Some(unit) => unit
case None => rest = fs; getUnit()
}
}
while (unitsToCompile.nonEmpty) {
val unit = getUnit()
recompile(unit)
unitsToCompile -= unit
}
}
/** Reset unit to just-parsed state */
def reset(unit: RichCompilationUnit): Unit =
if (unit.status > JustParsed) {
unit.depends.clear()
unit.defined.clear()
unit.synthetics.clear()
unit.toCheck.clear()
unit.targetPos = NoPosition
unit.contexts.clear()
ResetAttrs.traverse(unit.body)
currentTyperRun.enterNames(unit)
unit.status = JustParsed
}
/** Make sure symbol and type attributes are reset and recompile unit.
*/
def recompile(unit: RichCompilationUnit) {
assert(unit.status != NotLoaded)
reset(unit)
inform("type checking: "+unit)
currentTyperRun.typeCheck(unit)
unit.status = currentRunId
}
/** Move list of files to front of firsts */
def moveToFront(fs: List[AbstractFile]) {
firsts = fs ::: (firsts diff fs)
}
// ----------------- Implementations of client commmands -----------------------
/** Make sure a set of compilation units is loaded and parsed */
def reload(sources: Set[SourceFile]) = {
currentTyperRun = new TyperRun()
for (source <- sources) {
val unit = new RichCompilationUnit(source)
unitOfFile(source.file) = unit
currentTyperRun.compileLate(unit)
unit.status = JustParsed
}
outOfDate = true
moveToFront(sources.toList map (_.file))
if (compiling) throw new FreshRunReq
}
/** Set sync var `result` to a fully attributed tree located at position `pos` */
def typedTreeAt(pos: Position, result: SyncVar[Tree]) {
val unit = unitOf(pos)
assert(unit.status != NotLoaded)
moveToFront(List(unit.source.file))
result set currentTyperRun.typedTreeAt(pos)
}
// ---------------- Helper classes ---------------------------
/** A locator for trees with given positions.
* Given a position `pos`, locator.apply returns
* the smallest tree that encloses `pos`.
*/
class Locator(pos: Position) extends Traverser {
var last: Tree = _
def locateIn(root: Tree): Tree = {
this.last = EmptyTree
traverse(root)
this.last
}
override def traverse(t: Tree) {
if (t.pos includes pos) {
last = t
super.traverse(t)
}
}
}
/** A transformer that replaces tree `from` with tree `to` in a given tree */
class TreeReplacer(from: Tree, to: Tree) extends Transformer {
override def transform(t: Tree): Tree = {
if (t.pos includes from.pos)
if (t == from) to
else super.transform(t)
else
t
}
}
/** A traverser that resets all type and symbol attributes in a tree */
object ResetAttrs extends Traverser {
override def traverse(t: Tree) {
if (t.hasSymbol) t.symbol = NoSymbol
t.tpe = null
super.traverse(t)
}
}
/** The typer run */
class TyperRun extends Run {
// units is always empty
// symSource, symData are ignored
override def compiles(sym: Symbol) = false
def typeCheck(unit: CompilationUnit) {
applyPhase(typerPhase, unit)
}
def enterNames(unit: CompilationUnit) {
applyPhase(namerPhase, unit)
}
/** Return fully attributed tree at given position
* (i.e. largest tree that's contained by position)
*/
def typedTreeAt(pos: Position): Tree = {
val tree = locateTree(pos)
if (tree.tpe ne null) tree
else {
val unit = unitOf(pos)
assert(unit.status >= JustParsed)
unit.targetPos = pos
try {
typeCheck(unit)
throw new FatalError("tree not found")
} catch {
case ex: TyperResult => ex.tree
}
}
}
/** Apply a phase to a compilation unit */
private def applyPhase(phase: Phase, unit: CompilationUnit) {
val oldSource = reporter.getSource
try {
reporter.setSource(unit.source)
atPhase(phase) { phase.asInstanceOf[GlobalPhase] applyPhase unit }
} finally {
reporter setSource oldSource
}
}
}
class TyperResult(val tree: Tree) extends Exception
class RichCompilationUnit(source: SourceFile) extends CompilationUnit(source) {
var status: Int = NotLoaded
/** the current edit point offset */
var editPoint: Int = -1
/** The position of a targeted type check
* If this is different from NoPosition, the type checking
* will stop once a tree that contains this position range
* is fully attributed.
*/
var _targetPos: Position = NoPosition
override def targetPos: Position = _targetPos
def targetPos_=(p: Position) { _targetPos = p }
var contexts: Contexts = new Contexts
}
assert(globalPhase.id == 0)
// ----------------- interface to IDE ------------------------------------
private val scheduler = new WorkScheduler
/** The compilation unit corresponding to a source file */
def unitOf(s: SourceFile): RichCompilationUnit = unitOfFile get s.file match {
case Some(unit) =>
unit
case None =>
val unit = new RichCompilationUnit(s)
unitOfFile(s.file) = unit
unit
}
/** The compilation unit corresponding to a position */
def unitOf(pos: Position): RichCompilationUnit = unitOf(pos.source.get)
/** Locate smallest tree that encloses position */
def locateTree(pos: Position): Tree =
new Locator(pos) locateIn unitOf(pos).body
/** Locate smallest context that encloses position */
def locateContext(pos: Position): Option[Context] =
locateContext(unitOf(pos).contexts, pos)
/** Make sure a set of compilation units is loaded and parsed */
def askReload(sources: Set[SourceFile]) =
scheduler.postWorkItem(() => reload(sources))
/** Set sync var `result` to a fully attributed tree located at position `pos` */
def askTypeAt(pos: Position, result: SyncVar[Tree]) =
scheduler.postWorkItem(() => self.typedTreeAt(pos, result))
/** Ask to do unit first on present and subsequent type checking passes */
def askToDoFirst(f: AbstractFile) = {
scheduler.postWorkItem { () => moveToFront(List(f)) }
}
/** Cancel currently pending high-priority jobs */
def askCancel() =
scheduler.raise(new CancelActionReq)
/** Cancel current compiler run and start a fresh one where everything will be re-typechecked
* (but not re-loaded).
*/
def askReset() =
scheduler.raise(new FreshRunReq)
/** Tell the compile server to shutdown, and do not restart again */
def askShutdown() =
scheduler.raise(new ShutdownReq)
class CancelActionReq extends Exception
class FreshRunReq extends Exception
class ShutdownReq extends Exception
}
|