summaryrefslogtreecommitdiff
path: root/sources/scala/tools/nsc/Global.scala
blob: 45a9ee2f999b5b549611b680b2d797d6e279e1a8 (plain) (blame)
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
/* NSC -- new scala compiler
 * Copyright 2005 LAMP/EPFL
 * @author  Martin Odersky
 */
// $Id$
package scala.tools.nsc;

import java.io._;
import java.nio.charset._;
import scala.tools.util.{SourceReader,ClassPath,AbstractFile};
import scala.tools.nsc.util.{Position,SourceFile};
import scala.tools.nsc.reporters._;

import scala.collection.mutable.{HashSet,HashMap}

import symtab._;
import symtab.classfile.{PickleBuffer, Pickler};
import util.{ListBuffer, Statistics};
import ast._;
import ast.parser._;
import typechecker._;
import matching.TransMatcher;
import transform._;
import backend.icode.{ICodes, GenICode, Checkers};
import backend.ScalaPrimitives;
import backend.jvm.GenJVM;

class Global(val settings: Settings, val reporter: Reporter) extends SymbolTable
                                                             with Trees
                                                             with CompilationUnits
{

  // sub-components --------------------------------------------------

  object treePrinters extends TreePrinters {
    val global: Global.this.type = Global.this
  }
  val treePrinter = treePrinters.create();

  object treeBrowsers extends TreeBrowsers {
    val global: Global.this.type = Global.this
  }
  val treeBrowser = treeBrowsers.create();

  object treeInfo extends TreeInfo {
    val global: Global.this.type = Global.this
  }

  object gen extends TreeGen {
    val global: Global.this.type = Global.this
  }

  object constfold extends ConstantFolder {
    val global: Global.this.type = Global.this
  }

  object checker extends TreeCheckers {
    val global: Global.this.type = Global.this
  }

  object icodes extends ICodes {
    val global: Global.this.type = Global.this
  }

  object checkers extends Checkers {
    val global: Global.this.type = Global.this
  }

  object statistics extends Statistics {
    val global: Global.this.type = Global.this
  }

  object overridingPairs extends OverridingPairs {
    val global: Global.this.type = Global.this
  }

  val copy = new LazyTreeCopier();

// reporting -------------------------------------------------------

  def error(msg: String) = reporter.error(null, msg);
  def warning(msg: String) = reporter.warning(null, msg);
  def inform(msg: String) = System.err.println(msg);

    //reporter.info(null, msg, true);

  def informProgress(msg: String) =
    if (settings.verbose.value) inform("[" + msg + "]");

  def informTime(msg: String, start: long) =
    informProgress(msg + " in " + (System.currentTimeMillis() - start) + "ms");

  def log(msg: Object): unit =
    if (settings.log contains phase.name) inform("[log " + phase + "] " + msg);

  def abort(msg: String) = throw new Error(msg);

// file interface -------------------------------------------------------

  private val reader: SourceReader = {
    def stdCharset: Charset = {
      settings.encoding.value = "ISO-8859-1"; // A mandatory charset
      Charset.forName(settings.encoding.value);
    }
    val charset =
      try {
        Charset.forName(settings.encoding.value);
      } catch {
        case _: IllegalCharsetNameException =>
          error("illegal charset name '" + settings.encoding.value + "'");
          stdCharset
        case _: UnsupportedCharsetException =>
          error("unsupported charset '" + settings.encoding.value + "'");
          stdCharset
      }
    new SourceReader(charset.newDecoder());
  }

  val classPath = new ClassPath(
    settings.classpath.value,
    settings.sourcepath.value,
    settings.bootclasspath.value,
    settings.extdirs.value);

  if (settings.verbose.value) {
    System.err.println("classpath = " + classPath);
  }

  def getSourceFile(f: AbstractFile): SourceFile =
    new SourceFile(f, reader.read(f));

  def getSourceFile(name: String): SourceFile = {
    val f = AbstractFile.getFile(name);
    if (f == null) throw new FileNotFoundException(
      "source file '" + name + "' could not be found");
    getSourceFile(f)
  }

  def getSourceFile(clazz: Symbol): SourceFile = {
    val f = classPath.getRoot().lookupPath(
      clazz.fullNameString(File.separatorChar) + ".scala", false);
    if (f == null) throw new FileNotFoundException(
      "source file for " + clazz + " could not be found");
    getSourceFile(f)
  }

  object loaders extends SymbolLoaders {
    val global: Global.this.type = Global.this
  }

  def rootLoader: LazyType = new loaders.PackageLoader(classPath.getRoot());

// Phases ------------------------------------------------------------

  var globalPhase: Phase = NoPhase;

  val MaxPhases = 64;

  val phaseWithId = new Array[Phase](MaxPhases);
  { for (val i <- List.range(0, MaxPhases)) phaseWithId(i) = NoPhase }

  abstract class GlobalPhase(prev: Phase) extends Phase(prev) {
    phaseWithId(id) = this;
    def run: unit = currentRun.units foreach applyPhase;

    def apply(unit: CompilationUnit): unit;
    private val isErased = prev.name == "erasure" || prev.erasedTypes;
    override def erasedTypes: boolean = isErased;
    private val isFlat = prev.name == "flatten" || prev.flatClasses;
    override def flatClasses: boolean = isFlat;
    final def applyPhase(unit: CompilationUnit): unit = {
      if (settings.debug.value) inform("[running phase " + name + " on " + unit + "]");
      val unit0 = currentRun.currentUnit;
      currentRun.currentUnit = unit;
      apply(unit);
      currentRun.advanceUnit;
      assert(currentRun.currentUnit == unit);
      currentRun.currentUnit = unit0;
    }
  }

  object syntaxAnalyzer extends SyntaxAnalyzer {
    val global: Global.this.type = Global.this
  }

  object analyzer extends Analyzer {
    val global: Global.this.type = Global.this;
  }

  object superAccessors extends SuperAccessors {
    val global: Global.this.type = Global.this
  }

  object pickler extends Pickler {
    val global: Global.this.type = Global.this
  }

  object refchecks extends RefChecks {
    val global: Global.this.type = Global.this;
  }

  object uncurry extends UnCurry {
    val global: Global.this.type = Global.this;
  }

  object tailCalls extends TailCalls {
    val global: Global.this.type = Global.this;
  }

  object transMatcher extends TransMatcher {
    val global: Global.this.type = Global.this;
  }

  object explicitOuter extends ExplicitOuter {
    val global: Global.this.type = Global.this;
  }

  object erasure extends Erasure {
    val global: Global.this.type = Global.this;
  }

  object lambdaLift extends LambdaLift {
    val global: Global.this.type = Global.this;
  }

  object constructors extends Constructors {
    val global: Global.this.type = Global.this;
  }

  object flatten extends Flatten {
    val global: Global.this.type = Global.this;
  }

  object mixin extends Mixin {
    val global: Global.this.type = Global.this;
  }

  object sampleTransform extends SampleTransform {
    val global: Global.this.type = Global.this;
  }

  object genicode extends GenICode {
    val global: Global.this.type = Global.this;
  }

  object icodePrinter extends backend.icode.Printers {
    val global: Global.this.type = Global.this;
  }

  object scalaPrimitives extends ScalaPrimitives {
    val global: Global.this.type = Global.this;
  }

  object genJVM extends GenJVM {
    val global: Global.this.type = Global.this;
  }

  object icodeChecker extends checkers.ICodeChecker();

  object typer extends analyzer.Typer(
    analyzer.NoContext.make(EmptyTree, Global.this.definitions.RootClass, new Scope()));

  def phaseDescriptors: List[SubComponent] = List(
    analyzer.namerFactory,
    analyzer.typerFactory,
    superAccessors,
    pickler,
    refchecks,
    uncurry,
    tailCalls,
    transMatcher,
    explicitOuter,
    erasure,
    lambdaLift,
    constructors,
    flatten,
    mixin,
    genicode,
    genJVM,
    sampleTransform);

  private var curRun: Run = NoRun;
  override def currentRun: Run = curRun;

  class TyperRun extends Run {
    override val terminalPhase : Phase = typerPhase.next.next;
    //override val terminalPhase : Phase = superAccessors.next;
  }



  class Run extends CompilerRun {
    var currentUnit : CompilationUnit = _;
    curRun = this;
    override val firstPhase = syntaxAnalyzer.newPhase(NoPhase);
    phase = firstPhase;
    definitions.init; // needs firstPhase and phase to be defined != NoPhase,
                      // that's why it is placed here.

    private var p: Phase = firstPhase;
    private var stopped = false;
    for (val pd <- phaseDescriptors) {
      if (!stopped) {
        if (!(settings.skip contains pd.phaseName)) p = pd.newPhase(p);
        stopped = settings.stop contains pd.phaseName;
      }
    }

    // progress tracking
    def progress(current : Int, total : Int) : Unit = {}
    private var phasec : Int = 0;
    private var unitc  : Int = 0;
    def advancePhase : Unit = {
      unitc = 0;
      phasec = phasec + 1;
      refreshProgress;
    }
    def advanceUnit : Unit = {
      unitc = unitc + 1;
      refreshProgress;
    }
    private def refreshProgress = if (fileset.size > 0)
      progress((phasec * fileset.size) + unitc,
	       (phaseDescriptors.length+1) * fileset.size);



    override val terminalPhase : Phase = new GlobalPhase(p) {
      def name = "terminal";
      def apply(unit: CompilationUnit): unit = {}
    }
    override def phaseNamed(name: String): Phase = {
      var p: Phase = firstPhase;
      while (p.next != p && p.name != name) p = p.next;
      if (p.name != name) NoPhase else p
    }

    override val namerPhase = phaseNamed("namer");
    override val typerPhase = phaseNamed("typer");
    override val refchecksPhase = phaseNamed("refchecks");
    override val explicitOuterPhase = phaseNamed("explicitouter");
    override val erasurePhase = phaseNamed("erasure");
    override val flattenPhase = phaseNamed("flatten");
    override val mixinPhase = phaseNamed("mixin");

    private var unitbuf = new ListBuffer[CompilationUnit];
    private var fileset = new HashSet[AbstractFile];

    private def addUnit(unit: CompilationUnit): unit = {
      unitbuf += unit;
      fileset += unit.source.getFile();
    }

    def units: Iterator[CompilationUnit] = unitbuf.elements;

    /** A map from compiled top-level symbols to their source files */
    val symSource = new HashMap[Symbol, AbstractFile];

    /** A map from compiled top-level symbols to their picklers */
    val symData = new HashMap[Symbol, PickleBuffer];



    def compileSources(sources: List[SourceFile]): unit = {
      val startTime = System.currentTimeMillis();
      reporter.reset;
      for (val source <- sources)
	addUnit(new CompilationUnit(source));

      globalPhase = firstPhase;
      while (globalPhase != terminalPhase && reporter.errors == 0) {
	val startTime = System.currentTimeMillis();
	phase = globalPhase;
	globalPhase.run;
	if (settings.print contains globalPhase.name) treePrinter.printAll();
	if (settings.browse contains globalPhase.name) treeBrowser.browse(units);
	informTime(globalPhase.description, startTime);
	globalPhase = globalPhase.next;
	if (settings.check contains globalPhase.name) {
          phase = globalPhase;
          if (globalPhase.name == "jvm") icodeChecker.checkICodes;
          else checker.checkTrees;
	}
	if (settings.statistics.value) statistics.print(phase);
	advancePhase;
      }

      if (settings.Xshowcls.value != "") showDef(newTermName(settings.Xshowcls.value), false);
      if (settings.Xshowobj.value != "") showDef(newTermName(settings.Xshowobj.value), true);
      if (settings.Xshowicode.value) writeICode();

      if (reporter.errors == 0) {
/*
	for (val Pair(sym, pickled) <- symData.elements.toList) {
	  sym setPos Position.NOPOS;
//	  if (symData contains sym) {
//	    symData -= sym;
//	    symData -= sym.linkedSym;
//	    writeSymblFile(sym, pickled)
//	  }
//        }
*/
	for (val Pair(sym, file) <- symSource.elements) {
          sym setPos Position.NOPOS;
          if (sym.isTerm) sym.moduleClass setPos Position.NOPOS;
	  resetPackageClass(sym.owner);
	}
      } else {
	for (val Pair(sym, file) <- symSource.elements) {
	  sym.reset(new loaders.SourcefileLoader(file));
	  if (sym.isTerm) sym.moduleClass.reset(loaders.moduleClassLoader);
	}
      }
      informTime("total", startTime);
    }

    def compileLate(file: AbstractFile): unit =
      if (fileset == null)
	throw new FatalError("No class file for " + file + " was found\n(This file cannot be loaded as a source file)");
      else if (!(fileset contains file)) {
	val unit = new CompilationUnit(getSourceFile(file));
	addUnit(unit);
	var localPhase = firstPhase.asInstanceOf[GlobalPhase];
	while (localPhase.id < globalPhase.id || localPhase.id <= namerPhase.id) {
	  atPhase(localPhase)(localPhase.applyPhase(unit));
	  localPhase = localPhase.next.asInstanceOf[GlobalPhase];
	}
	refreshProgress;
      }

    def compileFiles(files: List[AbstractFile]): unit =
      try {
	compileSources(files map getSourceFile)
      } catch {
	case ex: IOException => error(ex.getMessage());
      }

    def compile(filenames: List[String]): unit =
      try {
	compileSources(filenames map getSourceFile)
      } catch {
	case ex: IOException => error(ex.getMessage());
      }

    private def resetPackageClass(pclazz: Symbol): unit = {
      assert(pclazz.isPackageClass, pclazz);
      atPhase(firstPhase) {
	pclazz.setInfo(atPhase(typerPhase)(pclazz.info))
      }
      if (!pclazz.isRoot) resetPackageClass(pclazz.owner);
    }
  }

  def showDef(name: Name, module: boolean): unit = {
    def getSym(name: Name, module: boolean): Symbol = {
      var i = name.length - 1;
      while (i != 0 && name(i) != '#' && name(i) != '.') i = i - 1;
      if (i == 0)
        definitions.getModule(name)
      else {
        val root = getSym(name.subName(0, i), name(i) == '.');
        var selector = name.subName(i+1, name.length);
        if (module) selector = selector.toTypeName;
        root.info.member(selector)
      }
    }
    val sym = getSym(name, module);
    System.err.println("" + sym.name + ":" +
		       (if (module) sym.tpe.symbol.info else sym.info))
  }

  /** Returns the file with the given suffix for the given class. */
  def getFile(clazz: Symbol, suffix: String) = {
    val outdirname = settings.outdir.value;
    var outdir = new File(if (outdirname == "") "." else outdirname);
    val filename = clazz.fullNameString('.');
    var start = 0;
    var end = filename.indexOf('.', start);
    while (end >= start) {
      outdir = new File(outdir, filename.substring(start, end));
      if (!outdir.exists()) outdir.mkdir();
      start = end + 1;
      end = filename.indexOf('.', start);
    }
    new File(outdir, filename.substring(start) + suffix)
  }

  private def writeSymblFile(clazz: Symbol, pickled: PickleBuffer) = {
    val file = getFile(clazz, ".symbl");
    try {
      val stream = new FileOutputStream(file);
      stream.write(pickled.bytes, 0, pickled.writeIndex);
      stream.close();
      informProgress("wrote " + file);
    } catch {
      case ex: IOException =>
      if (settings.debug.value) ex.printStackTrace();
      error("could not write file " + file);
    }
  }

  private def writeICode(): Unit = {
    val printer = new icodePrinter.TextPrinter(null);
    icodes.classes.foreach((cls) => {
      val file = getFile(cls.symbol, ".icode");
      try {
        val stream = new FileOutputStream(file);
        printer.setWriter(new PrintWriter(stream, true));
        printer.printClass(cls);
        informProgress("wrote " + file);
      } catch {
        case ex: IOException =>
          if (settings.debug.value) ex.printStackTrace();
        error("could not write file " + file);
      }
    });
  }
}