diff options
author | Paul Phillips <paulp@improving.org> | 2012-05-15 10:21:26 -0700 |
---|---|---|
committer | Paul Phillips <paulp@improving.org> | 2012-05-15 11:12:40 -0700 |
commit | 317a1056cd8062331964d1bc65f1bfd945538551 (patch) | |
tree | d3682713ea5fd99579eb7240ec587cdc92bf2fed /src | |
parent | 8a3ed4cc955dd85f37cc148265e920435b009a29 (diff) | |
download | scala-317a1056cd8062331964d1bc65f1bfd945538551.tar.gz scala-317a1056cd8062331964d1bc65f1bfd945538551.tar.bz2 scala-317a1056cd8062331964d1bc65f1bfd945538551.zip |
Removing extraneous files.
Culling accumulated unnecessary code.
Diffstat (limited to 'src')
71 files changed, 56 insertions, 5380 deletions
diff --git a/src/attic/README b/src/attic/README deleted file mode 100644 index 9fb600ae57..0000000000 --- a/src/attic/README +++ /dev/null @@ -1,2 +0,0 @@ -This is a holding area for source files which aren't used in -trunk anymore but which we're keeping available for a time.
\ No newline at end of file diff --git a/src/attic/scala/tools/nsc/models/SemanticTokens.scala b/src/attic/scala/tools/nsc/models/SemanticTokens.scala deleted file mode 100644 index a94188a3c1..0000000000 --- a/src/attic/scala/tools/nsc/models/SemanticTokens.scala +++ /dev/null @@ -1,701 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Martin Odersky - */ - -package scala.tools.nsc -package models - -import java.lang.Character.isJavaIdentifierPart -import java.lang.Thread - -import scala.collection.mutable.{HashMap, HashSet} -import scala.tools.nsc.Global -import scala.tools.nsc.symtab.{Flags, Names} -import scala.tools.nsc.symtab.Flags.DEFERRED -import scala.tools.nsc.util.{BatchSourceFile, SourceFile} - -class SemanticTokens(val compiler: Global) { - import compiler._ - object walker extends symtab.SymbolWalker { - lazy val global : compiler.type = compiler - } - - abstract class Kind {} - object OBJECT extends Kind - object CLASS extends Kind - object TRAIT extends Kind - object DEF extends Kind - object VAL extends Kind - object VAR extends Kind - object ARG extends Kind - object TPARAM extends Kind - - type AnyClass = Class[_] - - // static constants here - - abstract class Token { - def length: Int - def prev: HasNext - def next: HasPrev - } - - def eatKeyword(source: BatchSourceFile, pos: Int, keywords: List[String]) : Int = { - if (keywords.isEmpty) - pos - else if (pos == source.length) - -1 - else if (source.beginsWith(pos, " ")) - eatKeywords(source, pos + 1) - else if (source.beginsWith(pos, keywords.head + " ")) - eatKeywords(source, pos + keywords.head.length + 1) - else - eatKeyword(source, pos, keywords.tail) - } - - def eatKeywords(source: BatchSourceFile, pos: Int): Int = { - val keywords = - "package" :: "val" :: "var" :: "def" :: "class" :: "trait" :: "override" :: "case" :: - "object" :: "sealed" :: "private" :: "protected" :: Nil - if (pos != -1) eatKeyword(source, pos, keywords) - else pos - } - - trait HasNext extends Token { - var next0: HasPrev = _ - def next = next0 - } - - trait HasPrev extends Token { - var prev0: HasNext = _ - def prev = prev0 - } - - abstract class Actual extends HasNext with HasPrev { - def convertToGap: (Int, Actual) = { - val nextGap = next.isInstanceOf[Gap] - val prevGap = prev.isInstanceOf[Gap] - - if (prevGap) { - val ret = prev.length - val gap = prev.asInstanceOf[Gap] - gap.setLength(gap.length + length) - if (nextGap) { - gap.setLength(gap.length + next.length) - gap.next0 = next.next - next.next.prev0 = gap - } else { - gap.next0 = next - next.prev0 = gap - } - (ret, gap) - } - else if (nextGap) { - val gap = next.asInstanceOf[Gap] - gap.setLength(gap.length + length) - gap.prev0 = prev - prev.next0 = gap - (0, gap) - } - else { - prev.next0 = next - next.prev0 = prev - val gap = new Gap(prev) - gap.setLength(length) - (0, gap) - } - - } - def insert(prev1: HasNext) { - next0 = prev1.next - prev0 = prev1 - prev0.next0 = this - next0.prev0 = this - } - - } // Actual - - final class Gap extends Actual { - def this(prev1: HasNext) = { - this() - insert(prev1) - } - override def toString() = "gap-" + length - - var length0: Int = -1 - def length: Int = length0 - def setLength(length1: Int) = length0 = length1 - - // already gap - override def convertToGap: (Int, Actual) = (0, this) - } - - def Process(unit: CompilationUnit) = new Process(unit) - class Process(val unit: CompilationUnit) { - private var doLog = true - def source = unit.source - - def dbg(tree: Tree) = { - def treePos: Position = if (tree ne null) tree.pos else NoPosition; - ( - "TREE=" + tree + - (if (tree ne null) (" CLASS=" + tree.getClass()) else "") + - " SYM=" + tree.symbol + - " POS=" + - treePos.dbgString - )} - - val symbols = new HashMap[Symbol, Info] - - class Info(val symbol: Symbol) { - var defined : Def = _ - val uses = new HashSet[Use] - symbols.update(symbol, this) - } - - def info(symbol: Symbol): Info = - if (symbols.contains(symbol)) symbols(symbol) - else new Info(symbol) - - abstract class Semantic(val symbol: Symbol) extends Actual { - val name = symbol.name.decode.toString.trim - assert(symbol != NoSymbol) - def myOuter = Process.this - - def tpe: Type = symbol.tpe - - def length = name.length() - def info: Info = if (symbols.contains(symbol)) symbols(symbol) else new Info(symbol) - - def kind = { - val term0 = symbol - if (false) null - else if (term0.isVariable) VAR - else if (term0.isValueParameter) ARG - else if (term0.isMethod) DEF - else if (term0.isClass) CLASS - else if (term0.isModule) OBJECT - else if (term0.isValue) VAL - else if (term0.isTypeParameter) TPARAM - else if (term0.isType ) TPARAM - else { - // Console.err.println("UNRECOGNIZED SYMBOL: " + term0 + " " + name); - null - } - } - } - - class Def(symbol0: Symbol) extends Semantic(symbol0) { - info.defined = this - override def toString() = "def-" + name + "-" + symbol.getClass() - } - class Use(symbol0: Symbol, tpe0: Type) extends Semantic(symbol0) { - info.uses += this - - override def tpe : Type = if (tpe0 ne null) tpe0 else super.tpe; - override def toString() = "use-" + name + "-" + symbol.getClass(); - } - val list = new TokenList - - //build(unit.body) - val map = new scala.collection.mutable.LinkedHashMap[Int,Symbol] - map.clear // populate the map. - class visitor extends walker.Visitor { - def contains(pos : Position) = map.contains(pos.point) - def apply(pos : Position) = map(pos.point) - def update(pos : Position, sym : Symbol) : Unit = if (pos.isDefined) { - val offset = pos.point - map(offset) = sym - val isDef = pos.point == sym.pos.point - list.put(offset, (if (isDef) new Def(sym) else new Use(sym, NoType))); - } - } - walker.walk(unit.body, new visitor)(offset => unit.source.identifier(offset, compiler)) - - - // ok start building.... - def build[T <: Tree](trees: List[T]) { - for (tree <- trees) build(tree) - } - - def build(tree0: Tree): Unit = try { - /* if (tree0.pos != NoPosition) */ tree0 match { - case tree: ImplDef => - val pos = eatKeywords(unit.source.asInstanceOf[BatchSourceFile], tree.pos.point) - if (pos == -1) { - - } else buildDef(tree.symbol, eatKeywords(unit.source.asInstanceOf[BatchSourceFile], tree.pos.point)); - tree match { - case cdef: ClassDef => build(cdef.tparams) - case _ => ; - } - build(tree.impl.parents) - build(tree.impl.body) - case tree: ValOrDefDef => - if (!tree.symbol.hasAccessorFlag || tree.symbol.isDeferred) { - // MO: I added !tree.symbol.hasFlag(DEFERRED) in a refactoring where - // getters now can be abstract whereas before they could not. - // Adding the condition thus keeps the old behavior. - // todo: review whether this is correct, or whether abstract getters should be included. - { - val pos : Int = if (tree.name.toString().equals("<init>")) -1 else - eatKeywords(unit.source.asInstanceOf[BatchSourceFile], tree.pos.point); - if (false) Console.err.println("VALDEF: tree=" + tree + " sym=" + tree.symbol + " pos0=" + - tree.symbol.pos + " alias=" + tree.symbol.alias + " pos1=" + - pos + " pos2=" + tree.pos.dbgString + " " + tree.symbol.isSynthetic); - - if (pos != -1 && !tree.isSynthetic) - buildDef(tree.symbol, pos); - } - - if (tree.isInstanceOf[DefDef]) { - val ddef = tree.asInstanceOf[DefDef]; - build(ddef.tparams); - - for (l0 <- ddef.vparamss; arg <- l0) { - val pos0 : Int = if (!unit.source.beginsWith(arg.pos.point, "val ")) arg.pos.point; - else unit.source.skipWhitespace(arg.pos.point + ("val ").length()); - buildDef(arg.symbol, pos0); - build(arg.tpt); - } - } - //TPT=scala.Iterator[DocGenerator.this.compiler0.CompilationUnit] 260 class scala.tools.nsc.ast.Trees$TypeTree scala.Iterator[DocGenerator.this.compiler0.CompilationUnit] class scala.tools.nsc.symtab.Types$$anon$5 - if ((tree.tpt eq null) || (tree.tpt.tpe eq null)) { - //Console.err.println("BAD: " + tree.tpt + " in " + tree); - } else { - //Console.err.println("TPT=" + tree.tpt + " " + tree.tpt.pos + " " + tree.tpt.getClass() + " " + tree.tpt.tpe + " " + tree.tpt.tpe.getClass() + " " + tree.tpt.tpe.getClass().getSuperclass()); - build(tree.tpt); - } - //Console.err.println("RHS: " + tree.rhs + " " + tree.rhs.getClass() + " " + tree.rhs.getClass().getSuperclass()); - build(tree.rhs); - } - case tree: PackageDef => - //Console.err.println("PACKAGE: " + tree.name); - if (false) { - val pos = eatKeywords(unit.source.asInstanceOf[BatchSourceFile], tree.pos.pointOrElse(-1)) - if (pos != -1) - buildDef(tree.symbol, pos) - } - build(tree.stats) - case tree: Function => - for (arg <- tree.vparams if arg.pos != NoPosition) { - val name = arg.name.toString().trim() - val pos: Int = - if (unit.source.beginsWith(arg.pos.pointOrElse(-1), "val ")) - unit.source.skipWhitespace(arg.pos.pointOrElse(-1) + ("val ").length()) - else if (unit.source.asInstanceOf[BatchSourceFile].content(arg.pos.point) == ':') { - var posx : Int = arg.pos.point - while (unit.source.asInstanceOf[BatchSourceFile].content(posx - 1).isWhitespace) posx = posx - 1 - posx - name.length() - } else arg.pos.point - buildDef(arg.symbol, pos) - build(arg.tpt) - } - build(tree.body) - case tree : TypeTree => - val treex = tree - val tree1 = if (tree.original ne null) tree.original else tree - def classes(clazz: AnyClass): List[AnyClass] = - if (clazz eq null) Nil - else clazz :: classes(clazz.getSuperclass()) - if (tree.original eq null) { - if (false) Console.err.println("NO_ORIGINAL: " + tree + " " + tree.tpe + " " + classes(tree.tpe.getClass())); - } - if (tree.tpe ne null) buildT(tree1, tree.tpe); - def buildT( tree : Tree, tpe : Type) : Unit = if (tree.pos != NoPosition) tpe match { - case tpe0 : TypeRef => tree match { - case apt : AppliedTypeTree => - buildUse(tpe.typeSymbol, apt.tpt.pos.pointOrElse(-1), tpe0); - //Console.err.println("APT: " + treex + " vs. " + treex.original); - //Console.err.println("APT: " + treex.pos + " vs. " + treex.original.pos + " " + unit.source.dbg(treex.original.pos)); - //Console.err.println("APT: " + apt.tpt + " sym0=" + apt.tpt.symbol + " sym1=" + tpe0.sym + " apt.args=" + apt.args + " tpe0.args=" + tpe0.args); - - buildTs (apt.args, tpe0.args); - case ident : Ident => buildUse(tpe0.sym, ident.pos.pointOrElse(-1), tpe0); - case select : Select => - if (select.symbol == NoSymbol) - try { - // build(select); - buildUse(tpe0.typeSymbol, selectPos(select), tpe0); - //Console.err.println("QUALIFIER: " + select.qualifier + " " + unit.source.dbg(select.qualifier.pos) + " " + tpe0.prefix + " " + tpe0.prefix.getClass() + " " + tpe0.prefix.getClass().getSuperclass() +" " + tpe0.prefix.widen + " " + tpe0.prefix.toLongString); - buildT(select.qualifier, tpe0.prefix); - } catch { - case e : Error => - Console.err.println("BUILD_SELECT: " + select + " @ " + tpe0 + " " + (select.pos).dbgString); - throw e; - } - case tpt : TypeTree => - if (tpt.symbol ne null) { - Console.err.println("SYM0 " + tpt.symbol + " " + (tpt.pos).dbgString); - buildUse(tpt.symbol, tpt.pos.pointOrElse(-1), tpe0); - } else if (tpe0.typeSymbol ne null) { - //Console.err.println("TYPE_SYM1 " + tpe0.symbol + " " + unit.source.dbg(tpt.pos)); - buildUse(tpe0.typeSymbol, tpt.pos.pointOrElse(-1), tpe0); - } else { - Console.err.println("UNKNOWN TPT0: " + (tpt.pos).dbgString + " tpt=" + tpt + " " + tpt.symbol + " tpe0="+ tpe0 + " " + tpe0.typeSymbol + " tpe0.args=" + tpe0.args); - } - case sft : SelectFromTypeTree => - build(sft.qualifier); // XXX: broken - if (false) Console.err.println("SFTT: " + sft + " sym=" + sft.symbol + " name=" + sft.name + " qual=" + sft.qualifier + " qual.sym=" + - sft.qualifier.symbol + - " qual.pos=" + (sft.qualifier.pos).dbgString + " symbol=" + sft.symbol + " type=" + tpe0 + - " type.sym=" + tpe0.typeSymbol); - case _ => Console.err.println("UNKNOWN TPT2: " + tree + " vs. " + tpe0 + " " + tree.getClass() + " " + (tree.pos).dbgString); - } - case tpe0 : MethodType => tree match { - case tpt: TypeTree => - if (tpt.original ne null) buildT(tpt.original, tpe); - else { - Console.err.println("UNKNOWN TPT3: " + tree + " vs. " + tpe0 + " " + (tree.pos).dbgString); - } - case ident : Ident => buildT(ident, tpe0.resultType); - case select : Select => buildT(select, tpe0.resultType); - case _ => Console.err.println("UNKNOWN TPE: " + tree + " vs. " + tpe0 + " " + tree.getClass()); - } - case tpe0 : RefinedType => tree match { - case cpt : CompoundTypeTree => - buildTs(cpt.templ.parents, tpe0.parents); - - case _ : TypeTree => - // Console.err.println("UNKNOWN TPE13: " + dbg(tree) + " tpe0=" + tpe0 + " " + tpe0.parents); - case _ => - if (false) Console.err.println("UNKNOWN TPE5: " + dbg(tree) + " tpe0=" + tpe0 + " " + tpe0.parents); - } - case tpe0 : ThisType => tree match { - case stt : SingletonTypeTree => stt.ref match { - case ths : This => build(ths); - - case _ => Console.err.println("UNKNOWN TPE11: " + tpe0 + " " + stt + " " + stt.ref + " " + stt.ref.getClass() + " " + (tree.pos).dbgString); - } - case tt : This => - case _ : Ident => - case _ : Select => - case tt : TypeTree => - if (false) Console.err.println("UNKNOWN TPE12: " + tpe0 + " " + tree + " " + tree.getClass() + " " + (tree.pos).dbgString); - case _ => - if (false) Console.err.println("UNKNOWN TPE10: " + tpe0 + " " + tree + " " + tree.getClass() + " " + (tree.pos).dbgString); - } - case tpe0 : SingleType => tree match { - case ident : Ident => buildUse(tpe0.sym, ident.pos.pointOrElse(-1), tpe0); - case select : Select => - buildUse(tpe0.termSymbol, selectPos(select), tpe0); - //Console.err.println("QUALIFIER-0: " + select.qualifier + " " + unit.source.dbg(select.qualifier.pos) + " " + tpe0.prefix + " " + tpe0.prefix.getClass() + " " + tpe0.prefix.getClass().getSuperclass() +" " + tpe0.prefix.widen + " " + tpe0.prefix.toLongString); - buildT(select.qualifier, tpe0.prefix); - - case _ => - if (false) Console.err.println("UNKNOWN TPE8: " + tree + " " + (tree.pos).dbgString + " TPE=" + tpe0 + " PRE=" + tpe0.pre + " SYM=" + tpe0.sym); - - } - case ctype : ConstantType => - case ErrorType => - case _ => { - if (false) Console.err.println("UNKNOWN TPE4: " + tree + " " + tpe + " " + tpe.getClass() + " " + (tree.pos).dbgString); - } - }; - def buildTs(trees : List[Tree], types : List[Type]): Unit = if (!trees.isEmpty && !types.isEmpty) { - buildT (trees.head, types.head); - buildTs(trees.tail, types.tail); - } else if (trees.isEmpty != types.isEmpty) { - if (false && doLog) { - Console.println("" + treex + " vs. " + treex.original); - if (treex.original ne null) - Console.println("" + treex.tpe + " vs. " + treex.original.tpe); - logError("Tree vs. Type mismatch: " + trees + " " + types + " " + (tree.pos).dbgString, null); - doLog = false; - } - }; - case tree: Bind => - buildDef(tree.symbol, tree.pos.pointOrElse(-1)) - build(tree.body) - case tree: Ident => - buildUse(tree.symbol, tree.pos.pointOrElse(-1), tree.tpe) - case tree: Select => - try { - build(tree.qualifier) - } catch { - case e : Error => Console.err.println("SELECTQ: " + tree + " " + tree.qualifier + " " + (tree.qualifier.pos).dbgString); throw e; - } - try { - if (tree.pos.isDefined && tree.pos.point >= unit.source.length) { - if (false) Console.err.println("BAD_SELECT_QUALIFIER " + tree + " @ " + (tree.pos).dbgString); - - } else { - //Console.err.println("SELECT-0: " + tree.symbol + " " + tree.pos.dbgString + " " + (tree.pos - selectPos(tree))); - buildUse(tree.symbol, selectPos(tree), tree.tpe); - } - } catch { - case e : Error => Console.err.println("SELECTU: " + tree + " " + tree.symbol + " " + tree.pos.dbgString); throw e; - } - case tree: TypeApply => - //Console.err.println("TYPE_APPLY: " + tree + " " + tree.pos.dbgString); - if (!tree.args.isEmpty) { - //Console.err.println("ARGS: " + unit.source.dbg(tree.args0.head.pos)); - } - build(tree.fun) - build(tree.args) - case tree: Apply => - - build(tree.fun) - build(tree.args) - case tree: GenericApply => - - build(tree.fun) - build(tree.args) - case tree: Typed => - build(tree.expr) - build(tree.tpt) - case tree: Block => - if (false) { - if (!tree.stats.isEmpty) - Console.err.println("BLOCKS: " + tree.stats.head + " " + tree.stats.head.getClass()); - Console.err.println("BLOCKE: " + tree.expr + " " + tree.expr.getClass()) - } - build(tree.stats) - build(tree.expr) - case tree: CaseDef => - build(tree.pat) - build(tree.guard) - build(tree.body) - case tree : Assign => build(tree.lhs); build(tree.rhs); - case tree : If => build(tree.cond); build(tree.thenp); build(tree.elsep); - case tree : New => - //Console.err.println("NEW: " + tree.tpt + " " + tree.tpt.getClass()); - build(tree.tpt); - case tree : Match => build(tree.selector); build(tree.cases); - case tree : Return => build(tree.expr); - case tree : LabelDef => build(tree.rhs); - case tree : Throw => build(tree.expr); - case tree : Try => build(tree.block); build(tree.catches); build(tree.finalizer); - case tree : Alternative => build(tree.trees); - case tree : This => - - if (tree.symbol ne null) buildUse(tree.symbol, tree.pos.pointOrElse(-1), tree.tpe); - //Thread.dumpStack(); - case tree : TypeDef => - //Console.err.println("ALIAS: " + tree); - build(tree.rhs); build(tree.tparams); buildDef(tree.symbol, tree.pos.pointOrElse(-1)); - case tree : DocDef => build(tree.definition); - case tree: Import => build(tree.expr) - case tree: AppliedTypeTree => ; - case tree: Annotated => ; - case tree: SingletonTypeTree => ; - case tree: Super => ; - case tree: Literal => ; - case EmptyTree => ; - case _ => ; - Console.err.println("BAIL: " + (tree0.pos) + " " + tree0 + " " + tree0.getClass()); - } - } catch { - case t: Throwable => - logError("Error occured at " + (tree0.pos), t) - } - - def buildUse(term: Symbol, pos: Int, tpe: Type) = buildSym(term, pos, false, tpe) - def buildDef(term: Symbol, pos: Int) = buildSym(term, pos, true, null) - - def buildSym(term: Symbol, pos: Int, isDef: Boolean, tpe: Type): Unit = - if (term.hasAccessorFlag) - buildSym(analyzer.underlying(term), pos, isDef, tpe) - else if (pos == -1) { - //Console.err.println("NOPOS: " + term) - //Thread.dumpStack() - } - else if (term != NoSymbol) { - val name = term.name.decode.toString.trim - val buf = unit.source.asInstanceOf[BatchSourceFile].content - val cs = name.toChars - var idx = 0 - if (cs.length + pos > buf.length) return - else while (idx < cs.length) { - if (buf(pos + idx) != cs(idx)) { - //Console.err.println("MISMATCH: " + name + "[" + idx + "] " + unit.source.dbg(pos)); - //Thread.dumpStack(); - return; - } - else idx = idx + 1; - } - if (cs.length + pos + 1 < buf.length) { - if (isJavaIdentifierPart(buf(pos + cs.length))) { - //Console.err.println("MISMATCH: " + name + "[last] " + unit.source.dbg(pos)); - return; - } - } - try { - list.put(pos, (if (isDef) new Def(term) else new Use(term, tpe))); - } catch { - case e : Error => e.printStackTrace(); - } - } - - def selectPos(tree: Select): Int = if (tree.pos == NoPosition) -1 else { - val buf = unit.source.asInstanceOf[BatchSourceFile].content - if (tree.pos.point >= buf.length) { - if (false) { - Console.err.println("" + tree + "@" + tree.pos + " not in " + - unit.source.file.name + "[" + buf.length + "]"); - Thread.dumpStack() - abort() - } - return 0 - } - - val pos : Int = - if (buf(tree.pos.point) != '.') tree.pos.point - else { - def f(x : Int) : Int = { - if (buf(x).isWhitespace) f(x + 1) - else x - } - f(tree.pos.point + 1) - } - pos - }; - - class TokenList { - object begin extends HasNext { - def prev = this - def length = 0 - } - object end extends HasPrev { - def next = this - def length = 0 - } - // initialize - begin.next0 = end - end.prev0 = begin - - def tokenAt(offset: Int) = { - cursor.seek(offset) - if (cursor.token.isInstanceOf[Semantic]) cursor.token.asInstanceOf[Semantic] - else null - } - - def put(offset: Int, tok: Actual): Unit = tok match { - case tok0: Semantic => put(offset, tok0) - case gap: Gap => - } - - def put(offset: Int, tok: Semantic) { - cursor.seek(offset); - if (cursor.token == end) { - assert(offset >= cursor.offset); - if (offset > cursor.offset) { - // add a gap. - val gap = new Gap(end.prev); - gap.setLength(offset - cursor.offset); - cursor.offset = offset; - } - // append. - tok.insert(end.prev); - cursor.offset = cursor.offset + tok.length; - } else if (!cursor.token.isInstanceOf[Gap]) { - val sem = cursor.token.asInstanceOf[Semantic]; - if (sem.symbol == tok.symbol) return; - if (sem.symbol != tok.symbol && - sem.symbol.getClass() == tok.symbol.getClass() && - sem.symbol.pos == tok.symbol.pos) return; - } else { - val gap = cursor.token.asInstanceOf[Gap]; - if (!(offset - cursor.offset + tok.length <= gap.length)) { - Console.err.println("LIST =" + this); - Console.err.println("OFFSET=" + offset + " " + tok + " " + tok.length); - Console.err.println(" " + cursor.offset + " " + gap.length); - gap.length0 = offset - cursor.offset + tok.length - //abort(); - } - if (offset == cursor.offset) { - // replace or prepend - tok.prev0 = gap.prev0; - if (tok.length == gap.length) { // replace gap - tok.next0 = gap.next0; - } else { - gap.setLength(gap.length - tok.length); - tok.next0 = gap; - } - tok.next0.prev0 = tok; - tok.prev0.next0 = tok; - cursor.token = tok; - } else { - // append - val diff = (cursor.offset + gap.length) - (offset + tok.length); - - gap.setLength(gap.length - tok.length - diff); - tok.prev0 = gap; - tok.next0 = gap.next; - tok.next0.prev0 = tok; - tok.prev0.next0 = tok; - if (diff != 0) { - val gap0 = new Gap(tok); - gap0.setLength(diff); - } - } - } - } - - override def toString(): String = { - var node = begin.next - var str = "" - while (node != end) { - str = str + " " + node - node = node.next - } - str - } - - object cursor { - var token: Token = end - var offset: Int = 0 - - def next(): Unit = if (token == end) end else { - offset = offset + token.length - token = token.next - } - def prev(): Unit = if (token.prev == begin) token else { - offset = offset - token.prev.length - token = token.prev - } - def seek(soffset: Int): Unit = if (soffset == 0) { - token = begin.next - offset = 0 - } else { - assert(soffset > 0) - while (offset > soffset) prev; - while (offset + token.length <= soffset && token != end) { - val len0 = offset; - next; - } - } - def convertToGap = if (token.isInstanceOf[Actual]) { - val ret = token.asInstanceOf[Actual].convertToGap; - offset = offset - ret._1; - token = ret._2; - } - } - - // add or delete characters - def adjust(offset: Int, /* where */ - length: Int, /* how many characters are modified */ - to : Int /* length of new string */) = { - cursor.seek(offset) - if (cursor.token != end) { - cursor.convertToGap - while (cursor.offset + cursor.token.length < offset + length && cursor.token.next != end) { - val save = cursor.offset - cursor.next - cursor.convertToGap - assert(cursor.offset == save) - } - if (length != to && cursor.token != end) { - val diff = to - length; - val gap = cursor.token.asInstanceOf[Gap]; - gap.setLength(gap.length + diff); - }; - } - } - - } // TokenList - - } -} - diff --git a/src/attic/scala/tools/nsc/models/Signatures.scala b/src/attic/scala/tools/nsc/models/Signatures.scala deleted file mode 100644 index a5dfce6c56..0000000000 --- a/src/attic/scala/tools/nsc/models/Signatures.scala +++ /dev/null @@ -1,84 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Martin Odersky - */ - -package scala.tools.nsc -package models - -import scala.collection.mutable.{HashMap, HashSet} -import scala.tools.nsc.{Global => Compiler} -import scala.tools.nsc.symtab.{Flags, Names} -import scala.tools.nsc.util.{ Position, SourceFile } - -/** This class ... - * - * @author Sean McDirmid - * @version 1.0 - */ -class Signatures(val compiler: Compiler) { - import compiler._ - - class Signature(val name: String, val children: List[Signature]) { - def asString: String = name + "[" + asString0(children) + "]" - } - - def sort(sigs: List[Signature]) = sigs sortBy (_.name) reverse - - def asString0(sigs: List[Signature]): String = - sort(sigs) map (_.asString) mkString - - def signature(unit: CompilationUnit): String = - asString0(signature(unit.body, Nil)) - - def signature(trees: List[Tree]): List[Signature] = { - var ret : List[Signature] = Nil - for (tree <- trees) ret = signature(tree, ret) - ret - } - - /** - * @param tree0 ... - * @param rest ... - * @return ... - */ - def signature(tree0: Tree, rest: List[Signature]): List[Signature] = tree0 match { - case tree: MemberDef => if (!tree.mods.isPrivate) { - val name = "" + tree.name + "::" + - (tree.mods &~ Flags.SYNTHETIC) - - val children: List[Signature] = tree match { - case impl: ImplDef - //if (!impl.name.toString.contains("$anonfun$")) => - if (impl.name.pos("$anonfun$") == name.length) => - val supers = new Signature("$$supers", signature(impl.impl.parents)) - val body = new Signature("$$body", signature(impl.impl.body)) - val ret = supers :: body :: Nil - impl match { - case cdef: ClassDef => - new Signature("$$tparams", signature(cdef.tparams)) :: ret - case _ => - ret - } - case vdef: ValOrDefDef => - val ret = signature(vdef.tpt, Nil) - vdef match { - case ddef : DefDef => - val tparams = new Signature("$$tparams", signature(ddef.tparams)) - var vparamss : List[Signature] = Nil - for (list <- ddef.vparamss) - vparamss = signature(list) ::: vparamss - new Signature("$$ret", ret) :: tparams :: vparamss - case _ => - ret - } - case pdef: PackageDef => signature(pdef.stats) - case _ => Nil - } - new Signature(name, children) :: rest - - } else rest - case tree: TypeTree => new Signature("" + tree.tpe, Nil) :: rest - case _ => rest - } -} diff --git a/src/attic/scala/tools/nsc/symtab/SymbolWalker.scala b/src/attic/scala/tools/nsc/symtab/SymbolWalker.scala deleted file mode 100644 index 01b5c76cdc..0000000000 --- a/src/attic/scala/tools/nsc/symtab/SymbolWalker.scala +++ /dev/null @@ -1,252 +0,0 @@ -package scala.tools.nsc -package symtab - -trait SymbolWalker { - val global : Global - import global._ - import scala.collection.mutable.LinkedHashSet - trait Visitor { - def update(pos : Position, sym : Symbol) : Unit - def contains(pos : Position) : Boolean - def apply(pos : Position) : Symbol - def putDef(sym : Symbol, pos : Position) : Unit = () - } - /* - implicit def map2use(map : Map[Position,Symbol]) = new Visitor { - def update(pos : Position, sym : Symbol) : Unit = map.update(pos, sym) - def contains(pos : Position) : Boolean = map.contains(pos) - def apply(pos : Position) : Symbol = map.apply(pos) - } - */ - private def validSym(t: Tree) = t.symbol != NoSymbol && t.symbol != null - private def validSym(tp: Type) = tp != null && tp.typeSymbol != NoSymbol && tp.typeSymbol != null - private def notNull(tp: Type) = tp.typeSymbol != null - private def isNoSymbol(t: Tree) = t.symbol eq NoSymbol - - def walk(tree: Tree, visitor : Visitor)(fid : (util.Position) => Option[String]) : Unit = { - val visited = new LinkedHashSet[Tree] - def f(t : Tree) : Unit = { - if (visited.add(t)) return - - def fs(l: List[Tree]) = l foreach f - def fss(l: List[List[Tree]]) = l foreach fs - - val sym = (t, t.tpe) match { - case (Super(_,_),SuperType(_,supertp)) if validSym(supertp) => supertp.typeSymbol - case _ if validSym(t) => t.symbol - case (t: TypeTree, tp) if validSym(tp) => tp.typeSymbol - case (t: TypeTree, tp) if validSym(tp.resultType) => tp.resultType.typeSymbol - case (t, tpe: Type) if isNoSymbol(t) && tpe.termSymbol != null => - if (t.isTerm) tpe.termSymbol - else t.tpe match { - case x: TypeRef => x.sym // XXX: looks like a bug - case _ => tpe.typeSymbol - } - case _ => NoSymbol - } - - if (sym != null && sym != NoSymbol /* && !sym.hasFlag(SYNTHETIC) */) { - var id = fid(t.pos) - val doAdd = if (id.isDefined) { - if (id.get.charAt(0) == '`') id = Some(id.get.substring(1, id.get.length - 1)) - val name = sym.name.decode.trim - if ((name startsWith id.get) || (id.get startsWith name)) true - else { - false - } - } else false - if (doAdd) { - - if (!visitor.contains(t.pos)) { - visitor(t.pos) = sym - } else { - val existing = visitor(t.pos) - if (sym.sourceFile != existing.sourceFile || sym.pos != existing.pos) { - (sym,existing) match { - case (sym,existing) if sym.pos == existing.pos => - case (sym : TypeSymbol ,_ : ClassSymbol) => visitor(t.pos) = sym - case (_ : ClassSymbol,_ : TypeSymbol) => // nothing - case _ if sym.isModule && existing.isValue => // nothing - case _ if sym.isClass && existing.isMethod => // nothing - case _ => - assert(true) - } - } - }} - } - t match { - case t : DefTree if t.symbol != NoSymbol => - if (t.pos != NoPosition) - visitor.putDef(t.symbol, t.pos) - if (t.symbol.isClass) { - val factory = NoSymbol // XXX: t.symbol.caseFactory - if (factory != NoSymbol) { - visitor.putDef(factory, t.pos) - } - } - case t : TypeBoundsTree => f(t.lo); f(t.hi) - case t : TypeTree if t.original != null => - def h(original : Tree, tpe : Type): Unit = try { - if (original.tpe == null) - original.tpe = tpe - (original) match { - case (AppliedTypeTree(_,trees)) if tpe.isInstanceOf[TypeRef] => - val types = tpe.asInstanceOf[TypeRef].args - trees.zip(types).foreach{ - case (tree,tpe) => assert(tree != null && tpe != null); h(tree, tpe) - } - case _ => - } - } - if (t.original.tpe == null) { - val dup = t.original.duplicate - h(dup,t.tpe) - f(dup) - } else f(t.original) - () - case _ => - } - (t) match { - case (t : MemberDef) if t.symbol != null && t.symbol != NoSymbol => - val annotated = if (sym.isModule) sym.moduleClass else sym - val i = t.mods.annotations.iterator - val j = annotated.annotations.iterator - while (i.hasNext && j.hasNext) { - val tree = i.next - val ainfo = j.next - val sym = ainfo.atp.typeSymbol - tree.setType(ainfo.atp) - tree.setSymbol(sym) - f(tree) - } - - case _ => - } - t match { - case tree: ImplDef => - fs(tree.impl.parents); f(tree.impl.self); fs(tree.impl.body) - tree match { - case tree : ClassDef => fs(tree.tparams) - case _ => - } - case tree: PackageDef => fs(tree.stats) - case tree: ValOrDefDef => - f(tree.rhs); - if (tree.tpt != null) { - f(tree.tpt) - } - tree match { - case tree : DefDef => fs(tree.tparams); fss(tree.vparamss) - case _ => - } - case tree: Function => fs(tree.vparams); f(tree.body) - case tree : Bind => f(tree.body) - case tree : Select => - val qualifier = if (tree.tpe != null && tree.qualifier.tpe == null) { - val pre = tree.tpe.prefix - val qualifier = tree.qualifier.duplicate - qualifier.tpe = pre - qualifier - } else tree.qualifier - - f(qualifier) - case tree : Annotated => f(tree.annot); f(tree.arg) - case tree : GenericApply => f(tree.fun); fs(tree.args) - case tree : UnApply => f(tree.fun); fs(tree.args) - case tree : AppliedTypeTree => - if (tree.tpe != null) { - val i = tree.tpe.typeArgs.iterator - val j = tree.args.iterator - while (i.hasNext && j.hasNext) { - val tpe = i.next - val arg = j.next - if (arg.tpe == null) { - arg.tpe = tpe - } - } - if (tree.tpt.tpe == null) { - tree.tpt.tpe = tree.tpe - } - - } - f(tree.tpt); fs(tree.args) - - case tree : ExistentialTypeTree=> - if (tree.tpt.tpe == null) { - tree.tpt.tpe = tree.tpe - } - - f(tree.tpt) - fs(tree.whereClauses) - case tree : SingletonTypeTree => - if (tree.ref.tpe == null) { - val dup = tree.ref.duplicate - dup.tpe = tree.tpe - f(dup) - } else f(tree.ref) - case tree : CompoundTypeTree => - if (tree.tpe != null && tree.tpe.typeSymbol != null && tree.tpe.typeSymbol.isRefinementClass) tree.tpe.typeSymbol.info match { - case tpe : RefinedType => - tpe.parents.zip(tree.templ.parents).foreach{ - case (tpe,tree) => - if (tree.hasSymbol && (tree.symbol == NoSymbol || tree.symbol == null)) { - tree.symbol = tpe.typeSymbol - } - } - - case _ => - } - - f(tree.templ) - case tree : Template => fs(tree.parents); f(tree.self); fs(tree.body) - case tree : SelectFromTypeTree => { - if (tree.qualifier.tpe == null) tree.tpe match { - case tpe : TypeRef => - // give it a type! - tree.qualifier.tpe = tpe.prefix - case _ => - // tree.tpe.pre - } - f(tree.qualifier) - } - case tree : Literal => - /* - if (tree.tpe != null && tree.tpe.typeSymbol == definitions.ClassClass) { - // nothing we can do without original tree. - } - */ - - case tree : Typed => f(tree.expr); f(tree.tpt) - case tree : Block => fs(tree.stats); f(tree.expr) - case tree: CaseDef => f(tree.pat);f(tree.guard);f(tree.body) - case tree : Assign => f(tree.lhs); f(tree.rhs); - case tree : If => f(tree.cond); f(tree.thenp); f(tree.elsep); - case tree : New => f(tree.tpt); - case tree : Match => f(tree.selector); fs(tree.cases); - case tree : Return => f(tree.expr); - case tree : LabelDef => f(tree.rhs); - case tree : Throw => f(tree.expr); - case tree : Try => f(tree.block); fs(tree.catches); f(tree.finalizer); - case tree : Alternative => fs(tree.trees); - case tree : TypeDef => - (tree.tpe,sym) match { - case (null,sym : TypeSymbol) if (sym.rawInfo.isComplete) => - if (tree.tparams.isEmpty) { - if (tree.rhs.tpe == null) tree.rhs.tpe = sym.info - f(tree.rhs) - } else { - val tree0 = AppliedTypeTree(tree.rhs, tree.tparams) - tree0.tpe = sym.info - f(tree0) - } - case _ => f(tree.rhs); fs(tree.tparams) - } - case tree : DocDef => f(tree.definition); - case tree: Import => f(tree.expr) - case _ => - } - } - f(tree) - } - -} diff --git a/src/compiler/scala/reflect/internal/ClassfileModel.scala b/src/compiler/scala/reflect/internal/ClassfileModel.scala deleted file mode 100644 index c96459037f..0000000000 --- a/src/compiler/scala/reflect/internal/ClassfileModel.scala +++ /dev/null @@ -1,169 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.reflect.internal - -import java.io.DataInput -import ConstantPool._ -import ClassfileConstants._ - -trait ClassfileModel { - type Result - type Entry - type InterfaceInfo - type MemberInfo - type AttributeInfo - type InnerClassInfo - - protected implicit def EntryArrayTag: ArrayTag[Entry] - protected implicit def InterfaceInfoArrayTag: ArrayTag[InterfaceInfo] - protected implicit def MemberInfoArrayTag: ArrayTag[MemberInfo] - protected implicit def AttributeInfoArrayTag: ArrayTag[AttributeInfo] - protected implicit def InnerClassInfoArrayTag: ArrayTag[InnerClassInfo] - - // These could be implemented to jump forward in the stream if the - // result is not wanted. - def readConstantPoolEntry(): Entry - def readInterface(): InterfaceInfo - def readMember(): MemberInfo - def readAttribute(): AttributeInfo - def readInnerClass(): InnerClassInfo - - def createInfo( - version: JvmVersion, - entries: Array[Entry], - flags: Int, - name: String, - superName: String, - interfaces: Array[InterfaceInfo], - fields: Array[MemberInfo], - methods: Array[MemberInfo], - attributes: Array[AttributeInfo] - ): Result -} - -abstract class StreamingClassfileModel extends ClassfileModel { - protected[this] val in: DataInput - private[this] var name: String = _ - private[this] var entries: Array[PoolEntry] = _ - - type Entry = PoolEntry - - // These translate null into "", it's less troublesome. - protected def nameAt(idx: Int) = entries(idx) match { - case x: Name_Info => stringAt(x.name_index).replace('/', '.') - case _ => "" - } - protected def stringAt(idx: Int) = entries(idx) match { - case x: Utf8_info => x.stringValue - case _ => "" - } - - protected def u4 = in.readInt - protected def u2 = in.readUnsignedShort.toChar - protected def u1 = in.readUnsignedByte - - // The constant_pool table is indexed from 1 to constant_pool_count−1. - protected def readConstantPool(): Array[Entry] = { - val count = u2 - val entries = new Array[Entry](count) - var i = 1 - while (i < count) { - val entry = readConstantPoolEntry() - entries(i) = entry - i += entry.width - } - entries - } - protected def readInterfaces() = { - val count = u2 - val interfaces = new Array[InterfaceInfo](count) - var i = 0 - while (i < count) { - interfaces(i) = readInterface() - i += 1 - } - interfaces - } - protected def readMembers() = { - val count = u2 - val arr = new Array[MemberInfo](count) - var i = 0 - while (i < count) { - arr(i) = readMember() - i += 1 - } - arr - } - protected def readAttributes(): Array[AttributeInfo] = { - val count = u2 - val arr = new Array[AttributeInfo](count) - var i = 0 - while (i < count) { - arr(i) = readAttribute() - i += 1 - } - arr - } - protected def readInnerClasses() = { - val count = u2 - val arr = new Array[InnerClassInfo](count) - var i = 0 - while (i < count) { - arr(i) = readInnerClass() - i += 1 - } - arr - } - protected def thisClass = name - - def parse() = { - assert(u4 == JAVA_MAGIC, "Bad magic number") - val version = JvmVersion(u2, u2) - this.entries = readConstantPool() - val flags = u2.toShort - this.name = nameAt(u2) - val superName = nameAt(u2) - val interfaces = readInterfaces() - val fields = readMembers() - val methods = readMembers() - val attributes = readAttributes() - - try createInfo(version, entries, flags, name, superName, interfaces, fields, methods, attributes) - finally entries = null - } -} - -abstract class ScalacClassfileModel extends StreamingClassfileModel { - type Result = JvmClassInfo - type InterfaceInfo = String - type MemberInfo = JvmMemberInfo - type AttributeInfo = JvmAttributeInfo - type InnerClassInfo = JvmInnerClassInfo - - protected implicit def EntryArrayTag = arrayTag[PoolEntry] - protected implicit def InterfaceInfoArrayTag = arrayTag[InterfaceInfo] - protected implicit def MemberInfoArrayTag = arrayTag[MemberInfo] - protected implicit def AttributeInfoArrayTag = arrayTag[AttributeInfo] - protected implicit def InnerClassInfoArrayTag = arrayTag[InnerClassInfo] - - def readConstantPoolEntry(): PoolEntry - def readInterface(): String - def readMember(): JvmMemberInfo - def readAttribute(): JvmAttributeInfo - def readInnerClass(): JvmInnerClassInfo - - def createInfo( - version: JvmVersion, - entries: Array[PoolEntry], - flags: Int, - name: String, - superName: String, - interfaces: Array[String], - fields: Array[JvmMemberInfo], - methods: Array[JvmMemberInfo], - attributes: Array[JvmAttributeInfo] - ): JvmClassInfo = new JvmClassInfo(name, superName, interfaces, fields, methods, attributes) -} diff --git a/src/compiler/scala/reflect/internal/ConstantPool.scala b/src/compiler/scala/reflect/internal/ConstantPool.scala deleted file mode 100644 index f8dd7b9845..0000000000 --- a/src/compiler/scala/reflect/internal/ConstantPool.scala +++ /dev/null @@ -1,78 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.reflect.internal - -import ClassfileConstants._ - -object ConstantPool { - final case class JvmVersion(minorVersion: Int, majorVersion: Int) - - type UShort = Char - - final val CONSTANT_Utf8 = 1 - final val CONSTANT_Integer = 3 - final val CONSTANT_Float = 4 - final val CONSTANT_Long = 5 - final val CONSTANT_Double = 6 - final val CONSTANT_Class = 7 - final val CONSTANT_String = 8 - final val CONSTANT_Fieldref = 9 - final val CONSTANT_Methodref = 10 - final val CONSTANT_InterfaceMethodref = 11 - final val CONSTANT_NameAndType = 12 - - /* - 4.2.2 Unqualified Names - Names of methods, fields and local variables are stored as unqualified - names. Unqualified names must not contain the characters '.', ';', '[' - or '/'. Method names are further constrained so that, with the exception - of the special method names <init> and <clinit> (§3.9), they must not - contain the characters '<' or '>'. - - 4.3 Descriptors and Signatures - A descriptor is a string representing the type of a field or method. - Descriptors are represented in the class file format using modified - UTF-8 strings (§4.4.7) and thus may be drawn, where not further - constrained, from the entire Unicode character set. A signature is a - string representing the generic type of a field or method, or generic - type information for a class declaration. - */ - abstract class Name_Info(tag: Byte) extends PoolEntry(tag) { - def name_index: UShort - } - abstract class Ref_Info(tag: Byte) extends PoolEntry(tag) { - def class_index: UShort - def name_and_type_index: UShort - } - class Class_info(val name_index: UShort) extends Name_Info(CONSTANT_Class) { } - class Double_info(val value: Double) extends PoolEntry(CONSTANT_Double) { - override def width = 2 - } - class Fieldref_info(val class_index: UShort, val name_and_type_index: UShort) extends Ref_Info(CONSTANT_Fieldref) - class Float_info(val value: Float) extends PoolEntry(CONSTANT_Float) - class Integer_info(val value: Int) extends PoolEntry(CONSTANT_Integer) - class InterfaceMethodref_info(val class_index: UShort, val name_and_type_index: UShort) extends Ref_Info(CONSTANT_InterfaceMethodref) - class Long_info(val value: Long) extends PoolEntry(CONSTANT_Long) { - override def width = 2 - } - class Methodref_info(val class_index: UShort, val name_and_type_index: UShort) extends Ref_Info(CONSTANT_Methodref) - class NameAndType_info(val name_index: UShort, val descriptor_index: UShort) extends Name_Info(CONSTANT_NameAndType) { - override def toString = "NameAndType #%s:#%s;".format(name_index, descriptor_index) - } - class String_info(val string_index: UShort) extends PoolEntry(CONSTANT_String) { } - class Utf8_info(override val stringValue: String) extends PoolEntry(CONSTANT_Utf8) { - override def toString = ("Asciz " + stringValue).trim - } - - abstract class PoolEntry(tag: Byte) { - def width = 1 - def stringValue: String = sys.error("Not a String-valued constant pool entry: " + this) - override def toString = ( - getClass.getName.split("[.$]").last + "/" + tag - ) - } - object NoEntry extends PoolEntry(-1) { } -} diff --git a/src/compiler/scala/reflect/internal/JvmClassInfo.scala b/src/compiler/scala/reflect/internal/JvmClassInfo.scala deleted file mode 100644 index 80d868f666..0000000000 --- a/src/compiler/scala/reflect/internal/JvmClassInfo.scala +++ /dev/null @@ -1,220 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.reflect.internal - -import java.io.{ DataInput, InputStream, DataInputStream, ByteArrayInputStream, BufferedInputStream, FileInputStream } -import scala.tools.nsc.io.{ Directory } -import scala.reflect.NameTransformer.decode -import scala.tools.util.StringOps.trimTrailingSpace -import ConstantPool._ -import ClassfileConstants._ - -abstract class JvmInfo(attributes: Array[JvmAttributeInfo]) { - // def flags: Short - def name: String - - val signature = attributes collectFirst { case x: SignatureAttr => x.value } getOrElse "" - val innerClasses = attributes collectFirst { case x: InnerClassesAttr => x.value } getOrElse Array() -} -abstract class JvmAttributeInfo { - // attribute_info { - // u2 attribute_name_index; - // u4 attribute_length; - // u1 info[attribute_length]; - // } - def name: String - def value: Any -} - -class JvmClassInfo( - val name: String, - val superName: String, - val interfaces: Array[String], - val fields: Array[JvmMemberInfo], - val methods: Array[JvmMemberInfo], - attributes: Array[JvmAttributeInfo] -) extends JvmInfo(attributes) { - - def members = fields ++ methods sortBy (_.decodedName) - def memberDescriptors = members map (_.toErasedString) - def memberSignatures = members filter (_.hasSignature) map (_.toGenericString) - def descriptorsString = if (memberDescriptors.nonEmpty) memberDescriptors.mkString("\n-- Member Descriptors --\n", "\n", "\n") else "" - def signaturesString = if (memberSignatures.nonEmpty) memberSignatures.mkString("\n-- Member Signatures --\n", "\n", "\n") else "" - def innersString = if (innerClasses.isEmpty) "" else innerClasses.mkString("\n-- Inner Classes --\n", "\n", "\n") - def membersString = descriptorsString + signaturesString - def extendsString = if (superName == "") "" else " extends " + superName - def implementsString = if (interfaces.isEmpty) "" else interfaces.mkString("Implements: ", ", ", "") - - private def group(label: String, xs: Traversable[(String, String)]) = - xs map { case (name, value) => line(label, name, value) } mkString "\n" - - private def line(label: String, name: String, data: String) = - trimTrailingSpace(" %-15s %30s %s".format(label, name, data)) - - override def toString = ( - List( - "class " + name + extendsString, - if (signature == "") "" else line("class sig", "", signature), - group("interface", interfaces map (x => (("", x)))), - (innerClasses map (ic => line(ic.kind, ic.innerName, ic.nestString))).sorted.mkString("\n"), - group("descriptor", members map (x => (x.name, x.descriptor))), - group("signature", members filter (_.hasSignature) map (x => (x.name, x.signature))) - ) map trimTrailingSpace filterNot (_ == "") mkString ("", "\n", "\n") - ) -} - -// method_info or field_info { -// u2 access_flags; -// u2 name_index; -// u2 descriptor_index; -// u2 attributes_count; -// attribute_info attributes[attributes_count]; -// } -class JvmMemberInfo( - val flags: Short, - val name: String, - val descriptor: String, - attributes: Array[JvmAttributeInfo] -) extends JvmInfo(attributes) { - - final def isAbstract = (flags & JAVA_ACC_ABSTRACT) != 0 - final def isAnnotated = (flags & JAVA_ACC_ANNOTATION) != 0 - final def isFinal = (flags & JAVA_ACC_FINAL) != 0 - final def isPrivate = (flags & JAVA_ACC_PRIVATE) != 0 - final def isProtected = (flags & JAVA_ACC_PROTECTED) != 0 - final def isPublic = (flags & JAVA_ACC_PUBLIC) != 0 - final def isStatic = (flags & JAVA_ACC_STATIC) != 0 - final def isSynthetic = (flags & JAVA_ACC_SYNTHETIC) != 0 - final def isVarargs = (flags & JAVA_ACC_VARARGS) != 0 - - // method only - final def isBridge = (flags & JAVA_ACC_BRIDGE) != 0 - - // field only - final def isEnum = (flags & JAVA_ACC_ENUM) != 0 - final def isTransient = (flags & JAVA_ACC_TRANSIENT) != 0 - - def isMethod = descriptor startsWith "(" // ) - def isField = !isMethod - def scalaFlags = toScalaMethodFlags(flags) - def decodedName = decode(name) - def hasSignature = signature != "" - def toErasedString = "%-30s %s".format(decodedName, descriptor) - def toGenericString = "%-30s %s".format(decodedName, signature) - - override def toString = ( - if (hasSignature) toGenericString else toErasedString - ) -} -class GenericAttr(val name: String, val value: Array[Byte]) extends JvmAttributeInfo { } -class SignatureAttr(val value: String) extends JvmAttributeInfo { def name = "Signature" } -class InnerClassesAttr(val value: Array[JvmInnerClassInfo]) extends JvmAttributeInfo { def name = "InnerClasses" } - -// package foo { class Foo { class Bar } } -// -// javap would say -// Bar = class foo.Foo$Bar of class foo.Foo -// which is translated as -// innerClass = foo.Foo$Bar -// outerClass = foo.Foo -// innerName = Bar - -class JvmInnerClassInfo( - thisClass: String, // classfile which is being parsed - val innerClass: String, // the full name of the inner/nested class - val outerClass: String, // the full name of the outer class - must be a prefix of innerClass - val innerName: String, // the simple name of the inner class - should (?) be a suffix of innerClass - val flags: Short // flags -) { - val isEntryOfEnclosingClass = !isAnonymousClass && (innerClass == thisClass) - val isEntryOfNestedClass = !isAnonymousClass && (outerClass == thisClass) - - def isTopLevelClass = outerClass == "" - def isAnonymousClass = innerName == "" - def isMemberClass = !isTopLevelClass - - def kind = ( - if (isEntryOfEnclosingClass) "inner/enclosing" - else if (isEntryOfNestedClass) "inner/nested" - else if (isAnonymousClass) "inner/anon" - else "inner" - ) - def nestString = ( - if (isEntryOfEnclosingClass) "enclosing class: " + outerClass - else if (isEntryOfNestedClass) "member class: " + innerClass - else if (isAnonymousClass) "anonymous class: " + innerClass - else innerClass + " in " + outerClass - ) - override def toString = innerName + "=" + nestString -} - -object JvmClassInfo { - class Builder(protected[this] val in: DataInput) extends ScalacClassfileModel { - def readInterface(): InterfaceInfo = nameAt(u2) - def readMember(): JvmMemberInfo = new JvmMemberInfo(u2.toShort, stringAt(u2), stringAt(u2), readAttributes()) - def readInnerClass(): JvmInnerClassInfo = new JvmInnerClassInfo(thisClass, nameAt(u2), nameAt(u2), stringAt(u2), u2.toShort) - - def readConstantPoolEntry(): Entry = (u1: @annotation.switch) match { - case CONSTANT_Utf8 => new Utf8_info(in.readUTF) - case CONSTANT_Integer => new Integer_info(in.readInt) - case CONSTANT_Float => new Float_info(in.readFloat) - case CONSTANT_Long => new Long_info(in.readLong) - case CONSTANT_Double => new Double_info(in.readDouble) - case CONSTANT_Class => new Class_info(u2) - case CONSTANT_String => new String_info(u2) - case CONSTANT_Fieldref => new Fieldref_info(u2, u2) - case CONSTANT_Methodref => new Methodref_info(u2, u2) - case CONSTANT_InterfaceMethodref => new InterfaceMethodref_info(u2, u2) - case CONSTANT_NameAndType => new NameAndType_info(u2, u2) - } - - // field_info attributes: - // ConstantValue (§4.7.2), Synthetic (§4.7.8), Signature (§4.7.9), Deprecated (§4.7.15), - // RuntimeVisibleAnnotations (§4.7.16) and RuntimeInvisibleAnnotations (§4.7.17). - // - // method_info attributes: - // Code (§4.7.3), Exceptions (§4.7.5), Synthetic (§4.7.8), Signature (§4.7.9), Deprecated (§4.7.15), - // RuntimeVisibleAnnotations (§4.7.16), RuntimeInvisibleAnnotations (§4.7.17), RuntimeVisibleParameterAnnotations (§4.7.18), - // RuntimeInvisibleParameterAnnotations (§4.7.19) and AnnotationDefault (§4.7.20). - def readAttribute(): AttributeInfo = { - val name = stringAt(u2) - val len = u4 - name match { - case "Signature" => new SignatureAttr(stringAt(u2)) - case "InnerClasses" => new InnerClassesAttr(readInnerClasses()) - case name => val bytes = new Array[Byte](len) ; in.readFully(bytes) ; new GenericAttr(name, bytes) - } - } - } - - private def classFiles(path: String) = - Directory(path).deepFiles filter (_ hasExtension "class") - - def classInfoMap(path: String): Map[String, JvmClassInfo] = { - classFiles(path) map (f => (f.path, JvmClassInfo fromFile f.jfile)) toMap - } - def classInfoList(path: String): List[(String, JvmClassInfo)] = { - classInfoMap(path).toList sortBy (_._1) - } - - def fromFile(file: java.io.File) = - fromStream(new BufferedInputStream(new FileInputStream(file))) - - def fromBytes(bytes: Array[Byte]) = - fromStream(new ByteArrayInputStream(bytes)) - - def fromPath(path: String) = - fromStream(new BufferedInputStream(new FileInputStream(path))) - - def fromStream(in0: InputStream) = { - val in = new DataInputStream(in0) - try fromDataInput(in) finally in.close() - } - - def fromDataInput(in: DataInput): JvmClassInfo = { - new Builder(in) parse - } -} diff --git a/src/compiler/scala/reflect/internal/SymbolFlags.scala b/src/compiler/scala/reflect/internal/SymbolFlags.scala index 4ce8ac40df..e14c508fec 100644 --- a/src/compiler/scala/reflect/internal/SymbolFlags.scala +++ b/src/compiler/scala/reflect/internal/SymbolFlags.scala @@ -17,101 +17,6 @@ trait SymbolFlags { import definitions._ - /** Not mixed in under normal conditions; a powerful debugging aid. - */ - trait FlagVerifier extends Symbol { - private def assert0(cond: Boolean, message: => Any) { - if (!cond) { - Console.err.println("[flag verification failure]\n%s\n%s\n".format(atPhaseStackMessage, message)) - (new Throwable).getStackTrace.take(13).drop(3).foreach(println) - println("") - } - } - - protected def verifyChange(isAdd: Boolean, mask: Long, before: Long) { - val after = if (isAdd) before | mask else before & ~mask - val added = after & ~before - val removed = before & ~after - val ignored = mask & ~added & ~removed - val error = ( - (added & OverloadedFlagsMask) != 0 || (removed & OverloadedFlagsMask) != 0 - // || (ignored != 0) - ) - val addString = if (added == 0) "" else "+(" + flagsToString(added) + ")" - val removeString = if (removed == 0) "" else "-(" + flagsToString(removed) + ")" - val changeString = if (added == 0 && removed == 0) "no change" else addString + " " + removeString - - if (error) { - val templ = ( - """| symbol: %s %s in %s - | call: %s(%s) - | flags: %s - | result: %s""".stripMargin - ) - - assert0(false, templ.format( - shortSymbolClass, - name.decode, - owner, - if (isAdd) "+" else "-", - flagsToString(mask), - flagsToString(before), - changeString - )) - } - } - - protected def verifyFlags(what: String) { - assert0(this hasAllFlags alwaysHasFlags, symbolCreationString + "\n always=%s, what=%s\n".format(flagsToString(alwaysHasFlags), what)) - if (this hasFlag neverHasFlags) { - val hasRaw = (rawflags & neverHasFlags) != 0 - assert0(!hasRaw, symbolCreationString + "\n never=%s, what=%s".format(flagsToString(neverHasFlags), what)) - } - } - abstract override def initFlags(mask: Long): this.type = { - super.initFlags(mask) - verifyFlags("initFlags(" + flagsToString(mask) + ")") - this - } - abstract override def setFlag(mask: Long): this.type = { - verifyChange(true, mask, rawflags) - super.setFlag(mask) - verifyFlags("setFlag(" + flagsToString(mask) + ")") - this - } - abstract override def resetFlag(mask: Long): this.type = { - verifyChange(false, mask, rawflags) - super.resetFlag(mask) - verifyFlags("resetFlag(" + flagsToString(mask) + ")") - this - } - abstract override def flags_=(fs: Long) { - if ((fs & ~rawflags) != 0) - verifyChange(true, fs & ~rawflags, rawflags) - if ((rawflags & ~fs) != 0) - verifyChange(false, rawflags & ~fs, rawflags) - - super.flags_=(fs) - verifyFlags("flags_=(" + flagsToString(fs) + ")") - } - } - - /** Flags which should always be present on a particular class of - * Symbol, and never be present on any others. - */ - def AllDistinguishingFlags: Long = METHOD | MODULE | IMPLCLASS - - /** A distinguishing flag is one which the mixing class must always - * have, and which no other symbol class is allowed to have. - */ - trait DistinguishingFlag extends SymbolFlagLogic { - this: Symbol => - - def distinguishingFlag: Long - override protected def alwaysHasFlags = super.alwaysHasFlags | distinguishingFlag - override protected def neverHasFlags = super.neverHasFlags & ~distinguishingFlag - } - trait SymbolFlagLogic { this: Symbol => @@ -128,9 +33,6 @@ trait SymbolFlags { protected def resolveOverloadedFlag(flag: Long): String protected def calculateFlagString(basis: Long): String - protected def alwaysHasFlags: Long = 0L - protected def neverHasFlags: Long = AllDistinguishingFlags - def rawFlagString(mask: Long): String = calculateFlagString(rawflags & mask) def rawFlagString: String = rawFlagString(flagMask) def debugFlagString: String = flagString(AllFlags) diff --git a/src/compiler/scala/reflect/internal/SymbolTable.scala b/src/compiler/scala/reflect/internal/SymbolTable.scala index 76b4f5f53e..c2f90fff45 100644 --- a/src/compiler/scala/reflect/internal/SymbolTable.scala +++ b/src/compiler/scala/reflect/internal/SymbolTable.scala @@ -290,35 +290,14 @@ abstract class SymbolTable extends api.Universe // letting us know when a cache is really out of commission. private val caches = mutable.HashSet[WeakReference[Clearable]]() - private def dumpCaches() { - println(caches.size + " structures are in perRunCaches.") - caches.zipWithIndex foreach { case (ref, index) => - val cache = ref.get() - cache match { - case xs: Traversable[_] => - println("(" + index + ")" + ( - if (cache == null) " has been collected." - else " has " + xs.size + " entries:\n" + stringOf(xs) - )) - case _ => - } - } - } - // if (settings.debug.value) { - // println(Signallable("dump compiler caches")(dumpCaches())) - // } - def recordCache[T <: Clearable](cache: T): T = { caches += new WeakReference(cache) cache } def clearAll() = { - if (settings.debug.value) { - // val size = caches flatMap (ref => Option(ref.get)) map (_.size) sum; - log("Clearing " + caches.size + " caches.") - // totalling " + size + " entries.") - } + debuglog("Clearing " + caches.size + " caches.") + caches foreach { ref => val cache = ref.get() if (cache == null) @@ -334,11 +313,6 @@ abstract class SymbolTable extends api.Universe def newWeakSet[K <: AnyRef]() = recordCache(new WeakHashSet[K]()) } - /** Break into repl debugger if assertion is true. */ - // def breakIf(assertion: => Boolean, args: Any*): Unit = - // if (assertion) - // ILoop.break(args.toList) - /** The set of all installed infotransformers. */ var infoTransformers = new InfoTransformer { val pid = NoPhase.id diff --git a/src/compiler/scala/reflect/internal/Symbols.scala b/src/compiler/scala/reflect/internal/Symbols.scala index 240dedc658..4e12b96ca0 100644 --- a/src/compiler/scala/reflect/internal/Symbols.scala +++ b/src/compiler/scala/reflect/internal/Symbols.scala @@ -159,7 +159,6 @@ trait Symbols extends api.Symbols { self: SymbolTable => with HasFlags with SymbolFlagLogic with SymbolCreator - // with FlagVerifier // DEBUG with Annotatable[Symbol] { type AccessBoundaryType = Symbol @@ -628,7 +627,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => override def setFlag(mask: Long): this.type = { _rawflags |= mask ; this } override def resetFlag(mask: Long): this.type = { _rawflags &= ~mask ; this } - override def resetFlags() { rawflags &= (TopLevelCreationFlags | alwaysHasFlags) } + override def resetFlags() { rawflags &= TopLevelCreationFlags } /** Default implementation calls the generic string function, which * will print overloaded flags as <flag1/flag2/flag3>. Subclasses @@ -2434,8 +2433,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => /** A class for module symbols */ class ModuleSymbol protected[Symbols] (initOwner: Symbol, initPos: Position, initName: TermName) - extends TermSymbol(initOwner, initPos, initName) with DistinguishingFlag with ModuleSymbolApi { - def distinguishingFlag = MODULE + extends TermSymbol(initOwner, initPos, initName) with ModuleSymbolApi { private var flatname: TermName = null override def associatedFile = moduleClass.associatedFile @@ -2462,19 +2460,13 @@ trait Symbols extends api.Symbols { self: SymbolTable => } class PackageSymbol protected[Symbols] (owner0: Symbol, pos0: Position, name0: TermName) - extends ModuleSymbol(owner0, pos0, name0) with DistinguishingFlag with PackageSymbolApi { - override def distinguishingFlag = super.distinguishingFlag | PACKAGE + extends ModuleSymbol(owner0, pos0, name0) with PackageSymbolApi { override def isPackage = true } /** A class for method symbols */ class MethodSymbol protected[Symbols] (initOwner: Symbol, initPos: Position, initName: TermName) - extends TermSymbol(initOwner, initPos, initName) with DistinguishingFlag with MethodSymbolApi { - def distinguishingFlag = METHOD - // MethodSymbols pick up MODULE when trait-owned object accessors are cloned - // during mixin composition. - override protected def neverHasFlags = super.neverHasFlags & ~MODULE - + extends TermSymbol(initOwner, initPos, initName) with MethodSymbolApi { private[this] var mtpePeriod = NoPeriod private[this] var mtpePre: Type = _ private[this] var mtpeResult: Type = _ @@ -2743,9 +2735,6 @@ trait Symbols extends api.Symbols { self: SymbolTable => private[this] var thisTypeCache: Type = _ private[this] var thisTypePeriod = NoPeriod - override protected def alwaysHasFlags: Long = 0L - override protected def neverHasFlags: Long = 0L - override def resolveOverloadedFlag(flag: Long) = flag match { case INCONSTRUCTOR => "<inconstructor>" // INCONSTRUCTOR / CONTRAVARIANT / LABEL case EXISTENTIAL => "<existential>" // EXISTENTIAL / MIXEDIN @@ -2904,13 +2893,11 @@ trait Symbols extends api.Symbols { self: SymbolTable => * plain class symbols! */ class ModuleClassSymbol protected[Symbols] (owner: Symbol, pos: Position, name: TypeName) - extends ClassSymbol(owner, pos, name) with DistinguishingFlag { + extends ClassSymbol(owner, pos, name) { private[this] var module: Symbol = _ private[this] var typeOfThisCache: Type = _ private[this] var typeOfThisPeriod = NoPeriod - def distinguishingFlag = MODULE - private var implicitMembersCacheValue: List[Symbol] = Nil private var implicitMembersCacheKey1: Type = NoType private var implicitMembersCacheKey2: ScopeEntry = null @@ -2965,8 +2952,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => } class PackageClassSymbol protected[Symbols] (owner0: Symbol, pos0: Position, name0: TypeName) - extends ModuleClassSymbol(owner0, pos0, name0) with DistinguishingFlag { - override def distinguishingFlag = super.distinguishingFlag | PACKAGE + extends ModuleClassSymbol(owner0, pos0, name0) { override def sourceModule = companionModule override def enclClassChain = Nil override def isPackageClass = true diff --git a/src/compiler/scala/tools/cmd/program/DumpClass.scala b/src/compiler/scala/tools/cmd/program/DumpClass.scala deleted file mode 100644 index a583f1d3ea..0000000000 --- a/src/compiler/scala/tools/cmd/program/DumpClass.scala +++ /dev/null @@ -1,40 +0,0 @@ -/* NEST (New Scala Test) - * Copyright 2007-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools -package cmd -package program - -import scala.reflect.internal.JvmClassInfo -import scala.tools.nsc.io.Directory - -object DumpClass { - private val usage = """ - |Usage: dump-class [options] <path> <path> ... - | - |Parses and dumps the bytecode of all classes found at the given paths. - |""".stripMargin - - private val unaryOps = List( - "signatures" -> "dump signatures" - ) - private val info = Simple.scalaProgramInfo("dump-class", usage) - private val spec = Simple(info, unaryOps, Nil, null) - - def deepInfos(dir: String) = { - val files = Directory(dir).deepFiles.toList filter (_ hasExtension "class") - files.sortBy(_.path) map (f => (f.path, JvmClassInfo fromPath f.path)) - } - - def main(args: Array[String]): Unit = { - val runner = spec instance args - import runner._ - - if (args.isEmpty) - println(usage) - else - (residualArgs flatMap deepInfos) sortBy (_._1) map (_._2) foreach println - } -} diff --git a/src/compiler/scala/tools/cmd/program/Scmp.scala b/src/compiler/scala/tools/cmd/program/Scmp.scala deleted file mode 100644 index 6f39c29a77..0000000000 --- a/src/compiler/scala/tools/cmd/program/Scmp.scala +++ /dev/null @@ -1,60 +0,0 @@ -/* NEST (New Scala Test) - * Copyright 2007-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools -package cmd -package program - -import nsc.io._ -import scala.sys.process._ - -object Scmp { - private val scmpUsage = """ - |Usage: scmp [options] <cmd line> - |Example: scmp --p1 '-no-specialization -Ydebug' scalac src/library/scala/Function1.scala - | - |Note: the command line must start with a path to scalac. - |""".stripMargin - private val scmpOptions = List( - "p1" -> "options for the first run only", - "p2" -> "options for the second run only" - ) - private val scmpInfo = Simple.scalaProgramInfo("scmp", scmpUsage) - lazy val ScmpSpec = Simple(scmpInfo, Nil, scmpOptions, x => returning(x)(_.onlyKnownOptions = false)) - - def main(args0: Array[String]): Unit = { - if (args0.isEmpty) - return println(scmpUsage) - - val runner = ScmpSpec instance args0 - import runner._ - - val p1args = parsed.getOrElse("--p1", "") - val p2args = parsed.getOrElse("--p2", "") - - if (p1args.isEmpty && p2args.isEmpty) - return println("At least one of --p1 and --p2 must be given.") - if (residualArgs.isEmpty) - return println("There is no command to run.") - - def createCmd(extras: String) = - fromArgs(residualArgs.patch(1, toArgs(extras), 0)) - - def runCmd(cmd: String) = { - val tmpfile = File.makeTemp() - (cmd #> tmpfile.jfile !) - tmpfile - } - - val cmds = List(p1args, p2args) map createCmd - println(cmds.mkString("Running command lines:\n ", "\n ", "")) - - val files = cmds map runCmd map (_.path) - val diff = "diff %s %s".format(files: _*).!! - - if (diff.isEmpty) println("No differences.") - else println(diff) - } -} diff --git a/src/compiler/scala/tools/cmd/program/Simple.scala b/src/compiler/scala/tools/cmd/program/Simple.scala deleted file mode 100644 index f2095d64b8..0000000000 --- a/src/compiler/scala/tools/cmd/program/Simple.scala +++ /dev/null @@ -1,81 +0,0 @@ -/* NEST (New Scala Test) - * Copyright 2007-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools -package cmd -package program - -import Spec.Info - -/** A boilerplate reducer for commands with simple requirements. For examples, - * see Scmp and Tokens in this package. - */ -object Simple { - type CommandLineTransform = SimpleCommandLine => SimpleCommandLine - - abstract class SimpleSpec(val programInfo: Info) extends Spec with Meta.StdOpts with Interpolation - - trait SimpleInstance extends SimpleSpec with Instance { - val parsed: CommandLine - } - - class SimpleReference( - programInfo: Info, - unary: List[(String, String)] = Nil, - binary: List[(String, String)] = Nil, - postCreation: CommandLineTransform = null - ) extends SimpleSpec(programInfo) with Reference { - - spec => - - if (programInfo.usage != "") help(programInfo.usage) - unary foreach { case (option, help) => option / help --? } - binary foreach { case (option, help) => option / help --| } - - type ThisCommandLine = SimpleCommandLine - - def creator(args: List[String]) = new SimpleCommandLine(spec, args) - def instance(args: Array[String]): SimpleInstance = instance(args.toList) - def instance(args: List[String]): SimpleInstance = - new { - val parsed = spec(args: _*) - } with SimpleSpec(programInfo) with SimpleInstance { - lazy val referenceSpec = spec - } - - lazy val referenceSpec = spec - } - - def apply(info: Info, unary: List[(String, String)], binary: List[(String, String)], postCreation: CommandLineTransform): SimpleReference = { - new SimpleReference(info, unary, binary, postCreation) { - override def creator(args: List[String]) = { - val obj = super.creator(args) - if (postCreation == null) obj - else postCreation(obj) - } - } - } - - def scalaProgramInfo(name: String, help: String) = - Spec.Info(name, help, "scala.tools.cmd.program." + name.capitalize) - - /** You can't override a def with a var unless a setter exists. We cleverly - * sidestep this by mixing in a trait with dummy setters which will be - * inaccessible due to the overriding var. - */ - trait Ticket2338WontFixWorkaround { - def enforceArity_=(x: Boolean): Unit = sys.error("unreachable") - def onlyKnownOptions_=(x: Boolean): Unit = sys.error("unreachable") - } - - /** Configurability simplicity achieved by turning defs into vars and letting - * the spec creator apply a transformation. This way there's no need to create - * custom subclasses of CommandLine. - */ - class SimpleCommandLine(spec: Reference, args: List[String]) extends CommandLine(spec, args) with Ticket2338WontFixWorkaround { - override var enforceArity: Boolean = true - override var onlyKnownOptions: Boolean = true - } -} diff --git a/src/compiler/scala/tools/cmd/program/Tokens.scala b/src/compiler/scala/tools/cmd/program/Tokens.scala deleted file mode 100644 index be494bba3a..0000000000 --- a/src/compiler/scala/tools/cmd/program/Tokens.scala +++ /dev/null @@ -1,106 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools -package cmd -package program - -import nsc._ -import scala.reflect.internal.Chars.char2uescape -import io._ -import ast.parser.Tokens._ - -/** Given paths on the command line, tokenizes any scala files found - * and prints one token per line. - */ -object Tokens { - private val tokensUsage = "Usage: tokens [options] <path1 path2 ...>\n\nOptions:" - private val tokensUnary = List( - "verbose" -> "be more verbose", - "freq" -> "combine token lists and sort by frequency", - "stats" -> "output some stats" - ) - private val tokensBinary = List( - "sliding" -> "print tokens in groups of given size" - ) - private val tokensInfo = Simple.scalaProgramInfo("tokens", tokensUsage) - private lazy val TokensSpec = Simple(tokensInfo, tokensUnary, tokensBinary, null) - - def sanitize(x: Any): String = sanitize(x.toString) - def sanitize(str: String): String = str flatMap (x => if (x.isControl) char2uescape(x) else x.toString) - - def main(args0: Array[String]): Unit = { - if (args0.isEmpty) - return println(TokensSpec.helpMsg) - - val runner = TokensSpec instance args0 - import runner._ - - val files = (residualArgs flatMap walk).distinct - if (parsed isSet "--verbose") - println("Tokenizing: " + (files map (_.name) mkString " ")) - - if (parsed isSet "--stats") - println("Stats not yet implemented.") - - def raw = files flatMap fromScalaSource - def tokens: List[Any] = - if (parsed isSet "--sliding") raw sliding parsed("--sliding").toInt map (_ map sanitize mkString " ") toList - else raw - - def output = - if (parsed isSet "--freq") - (tokens groupBy (x => x) mapValues (_.length)).toList sortBy (-_._2) map (x => x._2 + " " + x._1) - else - tokens - - output foreach println - } - - def fromPaths(paths: String*): List[Any] = - (paths.toList flatMap walk).distinct flatMap fromScalaSource - - /** Given a path, returns all .scala files underneath it. - */ - private def walk(arg: String): List[File] = { - def traverse = Path(arg) ifDirectory (_.deepList()) getOrElse Iterator(File(arg)) - - Path onlyFiles traverse filter (_ hasExtension "scala") toList - } - - def fromScalaString(code: String): List[Any] = { - val f = File.makeTemp("tokens") - f writeAll code - fromScalaSource(f) - } - - /** Tokenizes a single scala file. - */ - def fromScalaSource(file: Path): List[Any] = fromScalaSource(file.path) - def fromScalaSource(file: String): List[Any] = { - val global = new Global(new Settings()) - import global._ - import syntaxAnalyzer.{ UnitScanner, token2string } - - val in = new UnitScanner(new CompilationUnit(getSourceFile(file))) - in.init() - - Iterator continually { - val token = in.token match { - case IDENTIFIER | BACKQUOTED_IDENT => in.name - case CHARLIT | INTLIT | LONGLIT => in.intVal - case DOUBLELIT | FLOATLIT => in.floatVal - case STRINGLIT => "\"" + in.strVal + "\"" - case SEMI | NEWLINE => ";" - case NEWLINES => ";;" - case COMMA => "," - case EOF => null - case x => token2string(x) - } - in.nextToken() - token - } takeWhile (_ != null) toList - } -} diff --git a/src/compiler/scala/tools/nsc/Global.scala b/src/compiler/scala/tools/nsc/Global.scala index bdc5384078..c917ec9984 100644 --- a/src/compiler/scala/tools/nsc/Global.scala +++ b/src/compiler/scala/tools/nsc/Global.scala @@ -8,11 +8,11 @@ package scala.tools.nsc import java.io.{ File, FileOutputStream, PrintWriter, IOException, FileNotFoundException } import java.nio.charset.{ Charset, CharsetDecoder, IllegalCharsetNameException, UnsupportedCharsetException } import compat.Platform.currentTime -import scala.tools.util.{ Profiling, PathResolver } +import scala.tools.util.PathResolver import scala.collection.{ mutable, immutable } import io.{ SourceReader, AbstractFile, Path } import reporters.{ Reporter, ConsoleReporter } -import util.{ NoPosition, Exceptional, ClassPath, SourceFile, NoSourceFile, Statistics, StatisticsInfo, BatchSourceFile, ScriptSourceFile, ShowPickled, ScalaClassLoader, returning } +import util.{ NoPosition, Exceptional, ClassPath, SourceFile, NoSourceFile, Statistics, StatisticsInfo, BatchSourceFile, ScriptSourceFile, ScalaClassLoader, returning } import scala.reflect.internal.pickling.{ PickleBuffer, PickleFormat } import settings.{ AestheticSettings } import symtab.{ Flags, SymbolTable, SymbolLoaders, SymbolTrackers } @@ -266,9 +266,7 @@ class Global(var currentSettings: Settings, var reporter: Reporter) extends Symb } def logThrowable(t: Throwable): Unit = globalError(throwableAsString(t)) - override def throwableAsString(t: Throwable): String = - if (opt.richExes) Exceptional(t).force().context() - else util.stackTraceString(t) + override def throwableAsString(t: Throwable) = util.stackTraceString(t) // ------------ File interface ----------------------------------------- @@ -356,19 +354,6 @@ class Global(var currentSettings: Settings, var reporter: Reporter) extends Symb def showTrees = settings.Xshowtrees.value || settings.XshowtreesCompact.value || settings.XshowtreesStringified.value val showClass = optSetting[String](settings.Xshowcls) map (x => splitClassAndPhase(x, false)) val showObject = optSetting[String](settings.Xshowobj) map (x => splitClassAndPhase(x, true)) - - // profiling - def profCPUPhase = isActive(settings.Yprofile) && !profileAll - def profileAll = settings.Yprofile.doAllPhases - def profileAny = !settings.Yprofile.isDefault || !settings.YprofileMem.isDefault - def profileClass = settings.YprofileClass.value - def profileMem = settings.YprofileMem.value - - // shortish-term property based options - def timings = (sys.props contains "scala.timings") - def inferDebug = (sys.props contains "scalac.debug.infer") || settings.Yinferdebug.value - def typerDebug = (sys.props contains "scalac.debug.typer") || settings.Ytyperdebug.value - def lubDebug = (sys.props contains "scalac.debug.lub") } // The current division between scala.reflect.* and scala.tools.nsc.* is pretty @@ -410,14 +395,7 @@ class Global(var currentSettings: Settings, var reporter: Reporter) extends Symb def run() { echoPhaseSummary(this) - currentRun.units foreach { unit => - if (opt.timings) { - val start = System.nanoTime - try applyPhase(unit) - finally unitTimings(unit) += (System.nanoTime - start) - } - else applyPhase(unit) - } + currentRun.units foreach applyPhase } def apply(unit: CompilationUnit): Unit @@ -461,8 +439,8 @@ class Global(var currentSettings: Settings, var reporter: Reporter) extends Symb } /** Switch to turn on detailed type logs */ - var printTypings = opt.typerDebug - var printInfers = opt.inferDebug + var printTypings = settings.Ytyperdebug.value + var printInfers = settings.Yinferdebug.value // phaseName = "parser" object syntaxAnalyzer extends { @@ -770,20 +748,6 @@ class Global(var currentSettings: Settings, var reporter: Reporter) extends Symb protected lazy val phasesSet = new mutable.HashSet[SubComponent] protected lazy val phasesDescMap = new mutable.HashMap[SubComponent, String] withDefaultValue "" private lazy val phaseTimings = new Phases.TimingModel // tracking phase stats - private lazy val unitTimings = mutable.HashMap[CompilationUnit, Long]() withDefaultValue 0L // tracking time spent per unit - private def unitTimingsFormatted(): String = { - def toMillis(nanos: Long) = "%.3f" format nanos / 1000000d - - val formatter = new util.TableDef[(String, String)] { - >> ("ms" -> (_._1)) >+ " " - << ("path" -> (_._2)) - } - "" + ( - new formatter.Table(unitTimings.toList sortBy (-_._2) map { - case (unit, nanos) => (toMillis(nanos), unit.source.path) - }) - ) - } protected def addToPhasesSet(sub: SubComponent, descr: String) { phasesSet += sub @@ -1292,14 +1256,7 @@ class Global(var currentSettings: Settings, var reporter: Reporter) extends Symb */ def units: Iterator[CompilationUnit] = unitbuf.iterator - def registerPickle(sym: Symbol): Unit = { - // Convert all names to the type name: objects don't store pickled data - if (opt.showPhase && (opt.showNames exists (x => findNamedMember(x.toTypeName, sym) != NoSymbol))) { - symData get sym foreach { pickle => - ShowPickled.show("\n<<-- " + sym.fullName + " -->>\n", pickle, false) - } - } - } + def registerPickle(sym: Symbol): Unit = () /** does this run compile given class, module, or case factory? */ def compiles(sym: Symbol): Boolean = @@ -1334,9 +1291,6 @@ class Global(var currentSettings: Settings, var reporter: Reporter) extends Symb private def showMembers() = opt.showNames foreach (x => showDef(x, opt.declsOnly, globalPhase)) - // If -Yprofile isn't given this will never be triggered. - lazy val profiler = Class.forName(opt.profileClass).newInstance().asInstanceOf[Profiling] - // Similarly, this will only be created under -Yshow-syms. object trackerFactory extends SymbolTrackers { val global: Global.this.type = Global.this @@ -1400,10 +1354,6 @@ class Global(var currentSettings: Settings, var reporter: Reporter) extends Symb private def compileUnitsInternal(units: List[CompilationUnit], fromPhase: Phase) { units foreach addUnit - if (opt.profileAll) { - inform("starting CPU profiling on compilation run") - profiler.startProfiling() - } val startTime = currentTime reporter.reset() @@ -1413,16 +1363,7 @@ class Global(var currentSettings: Settings, var reporter: Reporter) extends Symb while (globalPhase.hasNext && !reporter.hasErrors) { val startTime = currentTime phase = globalPhase - - if (opt.profCPUPhase) { - inform("starting CPU profiling on phase " + globalPhase.name) - profiler profile globalPhase.run - } - else globalPhase.run - - // Create a profiling generation for each phase's allocations - if (opt.profileAny) - profiler.advanceGeneration(globalPhase.name) + globalPhase.run // progress update informTime(globalPhase.description, startTime) @@ -1462,13 +1403,6 @@ class Global(var currentSettings: Settings, var reporter: Reporter) extends Symb advancePhase } - if (opt.profileAll) - profiler.stopProfiling() - - if (opt.timings) { - inform(phaseTimings.formatted) - inform(unitTimingsFormatted) - } if (traceSymbolActivity) units map (_.body) foreach (traceSymbols recordSymbolsInTree _) @@ -1481,15 +1415,6 @@ class Global(var currentSettings: Settings, var reporter: Reporter) extends Symb symSource.keys foreach (x => resetPackageClass(x.owner)) informTime("total", startTime) - // save heap snapshot if requested - if (opt.profileMem) { - inform("Saving heap snapshot, this could take a while...") - System.gc() - profiler.captureSnapshot() - inform("...done saving heap snapshot.") - specializeTypes.printSpecStats() - } - // record dependency data if (!dependencyAnalysis.off) dependencyAnalysis.saveDependencyAnalysis() @@ -1697,35 +1622,5 @@ class Global(var currentSettings: Settings, var reporter: Reporter) extends Symb } object Global { - /** If possible, instantiate the global specified via -Yglobal-class. - * This allows the use of a custom Global subclass with the software which - * wraps Globals, such as scalac, fsc, and the repl. - */ - def fromSettings(settings: Settings, reporter: Reporter): Global = { - // !!! The classpath isn't known until the Global is created, which is too - // late, so we have to duplicate it here. Classpath is too tightly coupled, - // it is a construct external to the compiler and should be treated as such. - val parentLoader = settings.explicitParentLoader getOrElse getClass.getClassLoader - val loader = ScalaClassLoader.fromURLs(new PathResolver(settings).result.asURLs, parentLoader) - val name = settings.globalClass.value - val clazz = Class.forName(name, true, loader) - val cons = clazz.getConstructor(classOf[Settings], classOf[Reporter]) - - cons.newInstance(settings, reporter).asInstanceOf[Global] - } - - /** A global instantiated this way honors -Yglobal-class setting, and - * falls back on calling the Global constructor directly. - */ - def apply(settings: Settings, reporter: Reporter): Global = { - val g = ( - if (settings.globalClass.isDefault) null - else try fromSettings(settings, reporter) catch { case x => - reporter.warning(NoPosition, "Failed to instantiate " + settings.globalClass.value + ": " + x) - null - } - ) - if (g != null) g - else new Global(settings, reporter) - } + def apply(settings: Settings, reporter: Reporter): Global = new Global(settings, reporter) } diff --git a/src/compiler/scala/tools/nsc/InterpreterCommand.scala b/src/compiler/scala/tools/nsc/InterpreterCommand.scala deleted file mode 100644 index e25a83e08b..0000000000 --- a/src/compiler/scala/tools/nsc/InterpreterCommand.scala +++ /dev/null @@ -1,8 +0,0 @@ -package scala.tools.nsc - -import interpreter._ - -/** A compatibility stub. - */ -@deprecated("Use a class in the scala.tools.nsc.interpreter package.", "2.9.0") -class InterpreterCommand(arguments: List[String], error: String => Unit) extends CommandLine(arguments, error) { }
\ No newline at end of file diff --git a/src/compiler/scala/tools/nsc/ast/NodePrinters.scala b/src/compiler/scala/tools/nsc/ast/NodePrinters.scala index 5d849b9622..ce3106ab29 100644 --- a/src/compiler/scala/tools/nsc/ast/NodePrinters.scala +++ b/src/compiler/scala/tools/nsc/ast/NodePrinters.scala @@ -25,43 +25,12 @@ abstract class NodePrinters { } var infolevel = InfoLevel.Quiet - def nodeToString: Tree => String = - if (sys.props contains "scala.colors") nodeToColorizedString - else nodeToRegularString + def nodeToString: Tree => String = nodeToRegularString object nodeToRegularString extends DefaultPrintAST with (Tree => String) { def apply(tree: Tree) = stringify(tree) } - object nodeToColorizedString extends ColorPrintAST with (Tree => String) { - def apply(tree: Tree) = stringify(tree) - } - - trait ColorPrintAST extends DefaultPrintAST { - import scala.tools.util.color._ - - def keywordColor = Cyan - def typeColor = Yellow - def termColor = Blue - def flagColor = Red - def literalColor = Green - - override def showFlags(tree: MemberDef) = - super.showFlags(tree) in flagColor.bright - - override def showDefTreeName(tree: DefTree) = - if (tree.name.isTermName) tree.name.decode in termColor.bright - else tree.name.decode in typeColor.bright - - override def showName(name: Name) = - if (name == nme.EMPTY || name == tpnme.EMPTY) "<empty>" in keywordColor - else if (name.isTermName) name.decode in termColor - else name.decode in typeColor - - override def showLiteral(lit: Literal) = - super.showLiteral(lit) in literalColor.bright - } - trait DefaultPrintAST extends PrintAST { val printPos = settings.Xprintpos.value || settings.Yposdebug.value @@ -133,7 +102,6 @@ abstract class NodePrinters { buf.clear() if (settings.XshowtreesStringified.value) buf.append(tree.toString + EOL) if (settings.XshowtreesCompact.value) { - // todo. colors for compact representation buf.append(showRaw(tree)) } else { level = 0 diff --git a/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala b/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala index 7f5b7aaf62..17c244ee82 100644 --- a/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala +++ b/src/compiler/scala/tools/nsc/backend/jvm/GenJVM.scala @@ -10,7 +10,6 @@ import java.io.{ByteArrayOutputStream, DataOutputStream, OutputStream } import java.nio.ByteBuffer import scala.collection.{ mutable, immutable } import scala.reflect.internal.pickling.{ PickleFormat, PickleBuffer } -import scala.tools.reflect.SigParser import scala.tools.nsc.symtab._ import scala.tools.nsc.util.{ SourceFile, NoSourceFile } import scala.reflect.internal.ClassfileConstants._ @@ -122,9 +121,6 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid with if (settings.debug.value) inform("[running phase " + name + " on icode]") - if (settings.Xverify.value && !SigParser.isParserAvailable) - global.warning("signature verification requested by signature parser unavailable: signatures not checked") - if (settings.Xdce.value) for ((sym, cls) <- icodes.classes if inliner.isClosureClass(sym) && !deadCode.liveClosures(sym)) icodes.classes -= sym @@ -722,14 +718,6 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid with nannots } - /** Run the signature parser to catch bogus signatures. - */ - def isValidSignature(sym: Symbol, sig: String) = ( - if (sym.isMethod) SigParser verifyMethod sig - else if (sym.isTerm) SigParser verifyType sig - else SigParser verifyClass sig - ) - // @M don't generate java generics sigs for (members of) implementation // classes, as they are monomorphic (TODO: ok?) private def needsGenericSignature(sym: Symbol) = !( @@ -751,19 +739,6 @@ abstract class GenJVM extends SubComponent with GenJVMUtil with GenAndroid with erasure.javaSig(sym, memberTpe) foreach { sig => // This seems useful enough in the general case. log(sig) - /** Since we're using a sun internal class for signature validation, - * we have to allow for it not existing or otherwise malfunctioning: - * in which case we treat every signature as valid. Medium term we - * should certainly write independent signature validation. - */ - if (settings.Xverify.value && SigParser.isParserAvailable && !isValidSignature(sym, sig)) { - clasz.cunit.warning(sym.pos, - """|compiler bug: created invalid generic signature for %s in %s - |signature: %s - |if this is reproducible, please report bug at https://issues.scala-lang.org/ - """.trim.stripMargin.format(sym, sym.owner.skipPackageObject.fullName, sig)) - return - } if (checkSignatures) { val normalizedTpe = beforeErasure(erasure.prepareSigMap(memberTpe)) val bytecodeTpe = owner.thisType.memberInfo(sym) diff --git a/src/compiler/scala/tools/nsc/interpreter/Dossiers.scala b/src/compiler/scala/tools/nsc/interpreter/Dossiers.scala deleted file mode 100644 index d889cadf47..0000000000 --- a/src/compiler/scala/tools/nsc/interpreter/Dossiers.scala +++ /dev/null @@ -1,54 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.nsc -package interpreter - -// Coming soon -trait Dossiers { - val intp: IMain - - import intp._ - import intp.global._ - import definitions._ - - trait Dossier { - def symbol: Symbol - def staticType: Type - - def id = name.toString - def name = symbol.name - def normalizedType = staticType.typeSymbolDirect.tpe.normalize - def simpleNameOfType = staticType.typeSymbol.simpleName - def staticTypeString = staticType.toString - - override def toString = "Dossier on %s:\n static type %s (normalized %s)".format( - symbol, staticType, normalizedType - ) - } - - class TypeDossier(val symbol: TypeSymbol, val staticType: Type) extends Dossier { - override def toString = super.toString - } - - class TermDossier(val symbol: TermSymbol, val staticType: Type, val value: AnyRef) extends Dossier { - def runtimeClass: JClass = value.getClass - def runtimeSymbol: Symbol = getClassIfDefined(runtimeClass.getName) - def runtimeType: Type = runtimeSymbol.tpe - def runtimeTypeString = TypeStrings.fromClazz(runtimeClass) - - def runtimeTypedParam = NamedParamClass(id, runtimeTypeString, value) - def staticTypedParam = NamedParamClass(id, staticTypeString, value) - - def isRuntimeTypeTighter = runtimeSymbol.ancestors contains normalizedType.typeSymbol - - override def toString = super.toString + ( - "\n runtime type %s/%s\n value %s".format( - runtimeType, runtimeTypeString, value - ) - ) - } -} - diff --git a/src/compiler/scala/tools/nsc/interpreter/ExprTyper.scala b/src/compiler/scala/tools/nsc/interpreter/ExprTyper.scala index 0cd918b6a5..4a36a4b6f3 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ExprTyper.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ExprTyper.scala @@ -13,7 +13,6 @@ trait ExprTyper { val repl: IMain import repl._ - import replTokens.{ Tokenizer } import global.{ reporter => _, Import => _, _ } import definitions._ import syntaxAnalyzer.{ UnitParser, UnitScanner, token2name } @@ -30,12 +29,6 @@ trait ExprTyper { result } - def tokens(code: String) = { - reporter.reset() - val in = newUnitScanner(code) - in.init() - new Tokenizer(in) tokenIterator - } def defns(code: String) = stmts(code) collect { case x: DefTree => x } def expr(code: String) = applyRule(code, _.expr()) @@ -111,13 +104,4 @@ trait ExprTyper { } finally typeOfExpressionDepth -= 1 } - - def tokens(line: String) = beQuietDuring(codeParser.tokens(line)) - - // In the todo column - // - // def compileAndTypeExpr(expr: String): Option[Typer] = { - // class TyperRun extends Run { - // override def stopPhase(name: String) = name == "superaccessors" - // } } diff --git a/src/compiler/scala/tools/nsc/interpreter/ILoop.scala b/src/compiler/scala/tools/nsc/interpreter/ILoop.scala index 297d6ad1b9..4badb90968 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ILoop.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ILoop.scala @@ -12,13 +12,13 @@ import java.util.concurrent.locks.ReentrantLock import scala.sys.process.Process import session._ import scala.util.Properties.{ jdkHome, javaVersion } -import scala.tools.util.{ Signallable, Javap } +import scala.tools.util.{ Javap } import scala.annotation.tailrec import scala.collection.mutable.ListBuffer import scala.concurrent.ops import util.{ ClassPath, Exceptional, stringFromWriter, stringFromStream } import interpreter._ -import io.{ File, Sources, Directory } +import io.{ File, Directory } import scala.reflect.NameTransformer._ import util.ScalaClassLoader import ScalaClassLoader._ @@ -118,12 +118,6 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) /** The context class loader at the time this object was created */ protected val originalClassLoader = Thread.currentThread.getContextClassLoader - // Install a signal handler so we can be prodded. - private val signallable = - if (isReplDebug) - Signallable("Dump repl state.")(dumpCommand()) - else null - // classpath entries added via :cp var addedClasspath: String = "" @@ -152,32 +146,15 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) if (intp ne null) { intp.close() intp = null - removeSigIntHandler() } } class ILoopInterpreter extends IMain(settings, out) { outer => - private class ThreadStoppingLineManager(classLoader: ClassLoader) extends Line.Manager(classLoader) { - override def onRunaway(line: Line[_]): Unit = { - val template = """ - |// She's gone rogue, captain! Have to take her out! - |// Calling Thread.stop on runaway %s with offending code: - |// scala> %s""".stripMargin - - echo(template.format(line.thread, line.code)) - // XXX no way to suppress the deprecation warning - line.thread.stop() - in.redrawLine() - } - } override lazy val formatting = new Formatting { def prompt = ILoop.this.prompt } - override protected def createLineManager(classLoader: ClassLoader): Line.Manager = - new ThreadStoppingLineManager(classLoader) - override protected def parentClassLoader = settings.explicitParentLoader.getOrElse( classOf[ILoop].getClassLoader ) } @@ -603,14 +580,6 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) private val crashRecovery: PartialFunction[Throwable, Boolean] = { case ex: Throwable => - if (settings.YrichExes.value) { - val sources = implicitly[Sources] - echo("\n" + ex.getMessage) - echo( - if (isReplDebug) "[searching " + sources.path + " for exception contexts...]" - else "[searching for exception contexts...]" - ) - } echo(intp.global.throwableAsString(ex)) ex match { diff --git a/src/compiler/scala/tools/nsc/interpreter/ILoopInit.scala b/src/compiler/scala/tools/nsc/interpreter/ILoopInit.scala index 6a9654732b..9072eaae46 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ILoopInit.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ILoopInit.scala @@ -7,7 +7,6 @@ package scala.tools.nsc package interpreter import util.Position -import scala.tools.util.SignalManager import scala.util.control.Exception.ignoring /** @@ -33,37 +32,6 @@ trait ILoopInit { echoAndRefresh(msg) } - /** Try to install sigint handler: ignore failure. Signal handler - * will interrupt current line execution if any is in progress. - * - * Attempting to protect the repl from accidental exit, we only honor - * a single ctrl-C if the current buffer is empty: otherwise we look - * for a second one within a short time. - */ - protected def installSigIntHandler() { - def onExit() { - Console.println("") // avoiding "shell prompt in middle of line" syndrome - sys.exit(1) - } - ignoring(classOf[Exception]) { - SignalManager("INT") = { - if (intp == null || intp.lineManager == null) - onExit() - else if (intp.lineManager.running) - intp.lineManager.cancel() - else if (in.currentLine != "") { - // non-empty buffer, so make them hit ctrl-C a second time - SignalManager("INT") = onExit() - io.timer(5)(installSigIntHandler()) // and restore original handler if they don't - } - else onExit() - } - } - } - protected def removeSigIntHandler() { - squashAndLog("removeSigIntHandler")(SignalManager("INT") = null) - } - private val initLock = new java.util.concurrent.locks.ReentrantLock() private val initCompilerCondition = initLock.newCondition() // signal the compiler is initialized private val initLoopCondition = initLock.newCondition() // signal the whole repl is initialized @@ -105,9 +73,7 @@ trait ILoopInit { protected def postInitThunks = List[Option[() => Unit]]( Some(intp.setContextClassLoader _), - if (isReplPower) Some(() => enablePowerMode(true)) else None, - // do this last to avoid annoying uninterruptible startups - Some(installSigIntHandler _) + if (isReplPower) Some(() => enablePowerMode(true)) else None ).flatten // ++ ( // warningsThunks diff --git a/src/compiler/scala/tools/nsc/interpreter/IMain.scala b/src/compiler/scala/tools/nsc/interpreter/IMain.scala index a9c2ce0d09..ce11712134 100644 --- a/src/compiler/scala/tools/nsc/interpreter/IMain.scala +++ b/src/compiler/scala/tools/nsc/interpreter/IMain.scala @@ -16,9 +16,9 @@ import reporters._ import symtab.Flags import scala.reflect.internal.Names import scala.tools.util.PathResolver -import scala.tools.nsc.util.{ ScalaClassLoader, Exceptional, Indenter } +import scala.tools.nsc.util.ScalaClassLoader import ScalaClassLoader.URLClassLoader -import Exceptional.unwrap +import scala.tools.nsc.util.Exceptional.unwrap import scala.collection.{ mutable, immutable } import scala.util.control.Exception.{ ultimately } import IMain._ @@ -92,7 +92,6 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends * on the future. */ private var _classLoader: AbstractFileClassLoader = null // active classloader - private var _lineManager: Line.Manager = null // logic for individual lines private val _compiler: Global = newCompiler(settings, reporter) // our private compiler private val nextReqId = { @@ -233,11 +232,6 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends val global: imain.global.type = imain.global } with StructuredTypeStrings - // object dossiers extends { - // val intp: imain.type = imain - // } with Dossiers { } - // import dossiers._ - lazy val memberHandlers = new { val intp: imain.type = imain } with MemberHandlers @@ -272,15 +266,10 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends def executionWrapper = _executionWrapper def setExecutionWrapper(code: String) = _executionWrapper = code def clearExecutionWrapper() = _executionWrapper = "" - def lineManager = _lineManager /** interpreter settings */ lazy val isettings = new ISettings(this) - /** Create a line manager. Overridable. */ - protected def noLineManager = ReplPropsKludge.noThreadCreation(settings) - protected def createLineManager(classLoader: ClassLoader): Line.Manager = new Line.Manager(classLoader) - /** Instantiate a compiler. Overridable. */ protected def newCompiler(settings: Settings, reporter: Reporter): ReplGlobal = { settings.outputDirs setSingleOutput virtualDirectory @@ -311,10 +300,8 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends ensureClassLoader() } final def ensureClassLoader() { - if (_classLoader == null) { + if (_classLoader == null) _classLoader = makeClassLoader() - _lineManager = if (noLineManager) null else createLineManager(_classLoader) - } } def classLoader: AbstractFileClassLoader = { ensureClassLoader() @@ -725,33 +712,14 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends val printName = sessionNames.print val resultName = sessionNames.result - class LineExceptional(ex: Throwable) extends Exceptional(ex) { - private def showReplInternal = isettings.showInternalStackTraces - - override def spanFn(frame: JavaStackFrame) = - if (showReplInternal) super.spanFn(frame) - else !(frame.className startsWith evalPath) - - override def contextPrelude = super.contextPrelude + ( - if (showReplInternal) "" - else "/* The repl internal portion of the stack trace is elided. */\n" - ) - } def bindError(t: Throwable) = { if (!bindExceptions) // avoid looping if already binding throw t val unwrapped = unwrap(t) withLastExceptionLock[String]({ - if (opt.richExes) { - val ex = new LineExceptional(unwrapped) - directBind[Exceptional]("lastException", ex) - ex.contextHead + "\n(access lastException for the full trace)" - } - else { - directBind[Throwable]("lastException", unwrapped) - util.stackTraceString(unwrapped) - } + directBind[Throwable]("lastException", unwrapped) + util.stackTraceString(unwrapped) }, util.stackTraceString(unwrapped)) } @@ -1027,24 +995,8 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends /** load and run the code using reflection */ def loadAndRun: (String, Boolean) = { - if (lineManager == null) return { - try { ("" + (lineRep call sessionNames.print), true) } - catch { case ex => (lineRep.bindError(ex), false) } - } - import interpreter.Line._ - - try { - val execution = lineManager.set(originalLine)(lineRep call sessionNames.print) - execution.await() - - execution.state match { - case Done => ("" + execution.get(), true) - case Threw => (lineRep.bindError(execution.caught()), false) - case Cancelled => ("Execution interrupted by signal.\n", false) - case Running => ("Execution still running! Seems impossible.", false) - } - } - finally lineManager.clear() + try { ("" + (lineRep call sessionNames.print), true) } + catch { case ex => (lineRep.bindError(ex), false) } } override def toString = "Request(line=%s, %s trees)".format(line, trees.size) @@ -1138,10 +1090,6 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends } } - object replTokens extends { - val global: imain.global.type = imain.global - } with ReplTokens { } - object exprTyper extends { val repl: IMain.this.type = imain } with ExprTyper { } @@ -1154,9 +1102,6 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends def typeOfExpression(expr: String, silent: Boolean = true): Type = exprTyper.typeOfExpression(expr, silent) - def prettyPrint(code: String) = - replTokens.prettyPrint(exprTyper tokens code) - protected def onlyTerms(xs: List[Name]) = xs collect { case x: TermName => x } protected def onlyTypes(xs: List[Name]) = xs collect { case x: TypeName => x } @@ -1238,12 +1183,6 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends def isShow = code.lines exists (_.trim endsWith "// show") def isShowRaw = code.lines exists (_.trim endsWith "// raw") - // checking for various debug signals - if (isShowRaw) - replTokens withRawTokens prettyPrint(code) - else if (repllog.isTrace || isShow) - prettyPrint(code) - // old style beSilentDuring(parse(code)) foreach { ts => ts foreach { t => diff --git a/src/compiler/scala/tools/nsc/interpreter/Line.scala b/src/compiler/scala/tools/nsc/interpreter/Line.scala deleted file mode 100644 index 3062c95dae..0000000000 --- a/src/compiler/scala/tools/nsc/interpreter/Line.scala +++ /dev/null @@ -1,107 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.nsc -package interpreter - -import java.util.concurrent.locks.ReentrantLock -import scala.tools.nsc.util.Exceptional -import Exceptional.unwrap -import Line._ - -/** Encapsulation of a single line in the repl. The concurrency - * infrastructure arose to deal with signals so SIGINT could be - * trapped without losing the repl session, but it will be useful - * in ways beyond that. Each line obtains a thread and the repl - * waits on a condition indicating that either the line has - * completed or failed. - */ -class Line[+T](val code: String, classLoader: ClassLoader, body: => T) { - private var _state: State = Running - private var _result: Option[Any] = None - private var _caught: Option[Throwable] = None - private val lock = new ReentrantLock() - private val finished = lock.newCondition() - - private def withLock[T](body: => T) = { - lock.lock() - try body - finally lock.unlock() - } - private def setState(state: State) = withLock { - _state = state - finished.signal() - } - // private because it should be called by the manager. - private def cancel() = if (running) setState(Cancelled) - - private def runAndSetState[T](body: => T) { - try { _result = Some(body) ; setState(Done) } - catch { case t => _caught = Some(t) ; setState(Threw) } - } - - // This is where the line thread is created and started. - private val _thread: Thread = - io.newThread(_ setContextClassLoader classLoader)(runAndSetState(body)) - - def state = _state - def thread = _thread - def alive = thread.isAlive - def runaway = !success && alive - def success = _state == Done - def running = _state == Running - - def caught() = { await() ; _caught.orNull } - def get() = { - await() - _result getOrElse sys.error("Called get with no result. Code: " + code) - } - def await() = withLock { while (running) finished.await() } -} - -object Line { - // seconds to let a runaway thread live before calling stop() - private val HUNTER_KILLER_DELAY = 5 - - // A line opens in state Running, and will eventually - // transition to Threw (an exception was caught), Cancelled - // (the line was explicitly cancelled, presumably by SIGINT) - // or Done (success). - sealed abstract class State - case object Running extends State - case object Threw extends State - case object Cancelled extends State - case object Done extends State - - class Manager(classLoader: ClassLoader) { - /** Override to add behavior for runaway lines. This method will - * be called if a line thread is still running five seconds after - * it has been cancelled. - */ - def onRunaway(line: Line[_]): Unit = () - - private var _current: Option[Line[_]] = None - def current = _current - - def clear() = { - _current foreach (_.cancel()) - _current = None - } - def set[T](code: String)(body: => T) = { - val line = new Line(code, classLoader, body) - _current = Some(line) - line - } - def running = _current.isDefined - def cancel() = { - current foreach { line => - line.thread.interrupt() - line.cancel() - if (line.runaway) - io.timer(HUNTER_KILLER_DELAY) { if (line.alive) onRunaway(line) } - } - } - } -} diff --git a/src/compiler/scala/tools/nsc/interpreter/Power.scala b/src/compiler/scala/tools/nsc/interpreter/Power.scala index 659caad1e1..9c4c05f1ee 100644 --- a/src/compiler/scala/tools/nsc/interpreter/Power.scala +++ b/src/compiler/scala/tools/nsc/interpreter/Power.scala @@ -321,8 +321,6 @@ class Power[ReplValsImpl <: ReplVals : TypeTag](val intp: IMain, replVals: ReplV } class RichReplString(s: String) { - // pretty print the string - def pp() { intp.prettyPrint(s) } // make an url out of the string def u: URL = ( if (s contains ":") new URL(s) @@ -337,7 +335,6 @@ class Power[ReplValsImpl <: ReplVals : TypeTag](val intp: IMain, replVals: ReplV } class RichReplURL(url: URL)(implicit codec: Codec) { def slurp(): String = io.Streamable.slurp(url) - def pp() { intp prettyPrint slurp() } } class RichSymbolList(syms: List[Symbol]) { def sigs = syms map (_.defString) diff --git a/src/compiler/scala/tools/nsc/interpreter/ReplProps.scala b/src/compiler/scala/tools/nsc/interpreter/ReplProps.scala index 99489b7c99..5eb1e0ae18 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ReplProps.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ReplProps.scala @@ -13,7 +13,6 @@ class ReplProps { val jlineDebug = bool("scala.tools.jline.internal.Log.debug") val jlineTrace = bool("scala.tools.jline.internal.Log.trace") - val noThreads = bool("scala.repl.no-threads") val info = bool("scala.repl.info") val debug = bool("scala.repl.debug") @@ -24,9 +23,3 @@ class ReplProps { val powerInitCode = Prop[JFile]("scala.repl.power.initcode") val powerBanner = Prop[JFile]("scala.repl.power.banner") } - -object ReplPropsKludge { - // !!! short term binary compatibility hack for 2.9.1 to put this - // here - needed a not previously existing object. - def noThreadCreation(settings: Settings) = replProps.noThreads || settings.Yreplsync.value -} diff --git a/src/compiler/scala/tools/nsc/interpreter/ReplTokens.scala b/src/compiler/scala/tools/nsc/interpreter/ReplTokens.scala deleted file mode 100644 index e63fabf151..0000000000 --- a/src/compiler/scala/tools/nsc/interpreter/ReplTokens.scala +++ /dev/null @@ -1,286 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.nsc -package interpreter - -import util.{ BatchSourceFile, Indenter } -import scala.tools.nsc.ast.parser.Tokens._ -import java.lang.Integer.toOctalString -import language.{implicitConversions, existentials} - -/** This began as an attempt at a completely minimal - * pretty printer for a token stream, but as it turns out - * it's "minimal, pretty, scala: pick any two." So - * now it's an unattractive hybrid between minimalism - * and other things. Still, it's a big improvement on the - * way I was printing source in the repl, so in it goes. - * - * @author Paul Phillips - */ -abstract class ReplTokens { - val global: Global - - import global._ - import syntaxAnalyzer.{ UnitScanner, token2name } - - // Mostly, this means print <NL> so we can see where - // semicolon inference took place. - private var rawTokens: Boolean = false - def withRawTokens[T](body: => T): T = { - rawTokens = true - try body - finally rawTokens = false - } - // There's the seed of a good idea in here, but you wouldn't - // know it from the current implementation. The objects are - // trying to depict what feelings of coziness a given token - // might have toward its immediate neighbors. But it lacks - // sufficient granularity and a good resolution mechanism. - sealed abstract class Cozy(l: => Boolean, r: => Boolean) { - def left = l - def right = r - } - object Cozy { - def unapply(x: Cozy) = Some((x.left, x.right)) - } - case object |--*--| extends Cozy(false, false) - case object <*--| extends Cozy(true, false) - case object |--*> extends Cozy(false, true) - case object <*> extends Cozy(true, true) - - @annotation.switch def escapedChar(ch: Char): String = ch match { - case '\b' => "\\b" - case '\t' => "\\t" - case '\n' => "\\n" - case '\f' => "\\f" - case '\r' => "\\r" - case '"' => "\\\"" - case '\'' => "\\\'" - case '\\' => "\\\\" - case _ => String.valueOf(ch) - } - def escape(text: String): String = { - text map { ch => - if (ch.isControl) "\\0" + toOctalString(ch) - else escapedChar(ch) - } mkString "" - } - private class Arrow(code: Int) { - def ->(str: String): (Int, ReplToken) = (code, Token(code)(str)) - def ->(tok: ReplToken): (Int, ReplToken) = (code, tok) - } - private val symbolTokenMap = { - implicit def liftToken(code: Int): Arrow = new Arrow(code) - - Map[Int, ReplToken]( - AT -> At, - CASECLASS -> "case class", - CASEOBJECT -> "case object", - COLON -> Colon, - COMMA -> Comma, - DOT -> Dot, - EOF -> Eof, - ERROR -> "<error>", - FALSE -> False, - IMPORT -> Import, - LBRACE -> LBrace, - LBRACKET -> LBracket, - LPAREN -> LParen, - NEWLINE -> Newline, - NEWLINES -> Newlines, - NULL -> Null, - RBRACE -> RBrace, - RBRACKET -> RBracket, - RPAREN -> RParen, - SEMI -> Semi, - SUBTYPE -> Subtype, - SUPERTYPE -> Supertype, - TRUE -> True, - VIEWBOUND -> ViewBound, - XMLSTART -> "<xmlstart>" - ) - } - def isAlphaId(t: ReplToken) = t match { - case Id(name) => name forall (ch => ch.isDigit || ch.isLetter || ch == '_') - case _ => false - } - def isOperatorId(t: ReplToken) = t match { - case Id(name) => !isAlphaId(t) - case _ => false - } - - sealed abstract class ReplToken(val tokenString: String, val cozy: Cozy) { - def this(str: String) = this(str, |--*--| ) - - def insistsOnSpace = false - def cozyRight(other: ReplToken) = (cozy.right || other.cozy.left) - def cozyLeft(other: ReplToken) = (cozy.left || other.cozy.right) - - final def <--?-->(other: ReplToken) = { - !(insistsOnSpace || other.insistsOnSpace) && ( - (this cozyRight other) || - (other cozyLeft this) - ) - } - - // to show invisibles - def rawString = tokenString - override def toString = ( - if (rawTokens) rawString - else tokenString - ) - } - trait InsistCozyRight extends ReplToken { - final override def cozyRight(other: ReplToken) = true - } - trait InsistCozyLeft extends ReplToken { - final override def cozyLeft(other: ReplToken) = true - } - trait InsistCozy extends InsistCozyLeft with InsistCozyRight { } - trait InsistSpaced extends ReplToken { - final override def insistsOnSpace = true - } - trait CozyWithLetters extends ReplToken { - override def cozyRight(other: ReplToken) = isAlphaId(other) || super.cozyRight(other) - override def cozyLeft(other: ReplToken) = isAlphaId(other) || super.cozyLeft(other) - } - trait Brackets extends ReplToken { - private def isCozyToken(t: ReplToken) = t == LBracket || t == RBracket || isAlphaId(t) - override def cozyRight(other: ReplToken) = isCozyToken(other) || super.cozyRight(other) - override def cozyLeft(other: ReplToken) = isCozyToken(other) || super.cozyLeft(other) - } - - case class Token(value: Int)(str: String) extends ReplToken(str) { } - case class Id(name: String) extends ReplToken(name) { } - case class Lit[T](value: T) extends ReplToken(value match { - case s: String => "\"" + s + "\"" - case _ => "" + value - }) - case object At extends ReplToken("@") with InsistCozyRight { } - case object Colon extends ReplToken(":", <*--|) - case object Comma extends ReplToken(",", <*--|) with InsistCozyLeft { } - case object Dot extends ReplToken(".", <*>) with InsistCozy { } - case object Eof extends ReplToken("EOF") - case object ErrorToken extends ReplToken("<internal error>") - case object False extends ReplToken("false") - case object Import extends ReplToken("import") - case object LBrace extends ReplToken("{") with InsistSpaced { } - case object LBracket extends ReplToken("[") with Brackets { } - case object LParen extends ReplToken("(", |--*>) - case object Newline extends ReplToken("\n", <*>) with InsistCozy { override def rawString = "<NL>\n" } - case object Newlines extends ReplToken("\n\n", <*>) with InsistCozy { override def rawString = "<NLS>\n\n" } - case object Null extends ReplToken("null") - case object RBrace extends ReplToken("}", |--*>) with InsistSpaced { } - case object RBracket extends ReplToken("]") with Brackets { } - case object RParen extends ReplToken(")", <*--|) - case object Semi extends ReplToken(";", <*--|) - case object Subtype extends ReplToken("<:") with InsistSpaced { } - case object Supertype extends ReplToken(">:") with InsistSpaced { } - case object True extends ReplToken("true") - case object ViewBound extends ReplToken("<%") with InsistSpaced { } - - class Tokenizer(in: UnitScanner) { - private def translate(tokenCode: Int): ReplToken = tokenCode match { - case IDENTIFIER | BACKQUOTED_IDENT => Id("" + in.name) - case CHARLIT | INTLIT | LONGLIT => Lit(in.intVal) - case DOUBLELIT | FLOATLIT => Lit(in.floatVal) - case STRINGLIT => Lit(escape(in.strVal)) - case SYMBOLLIT => Lit(scala.Symbol(in.strVal)) - case _ => - symbolTokenMap.getOrElse( - tokenCode, - token2name get tokenCode match { - case Some(name) => Token(tokenCode)("" + name) - case _ => Token(tokenCode)("<unknown: " + tokenCode + ">") - } - ) - } - def tokenIterator: Iterator[ReplToken] = ( - Iterator continually { - try translate(in.token) - finally in.nextToken() - } takeWhile (_ ne Eof) - ) - } - - def prettyPrintRaw(tokens: TraversableOnce[ReplToken]) { - withRawTokens(prettyPrint(tokens)) - } - - def prettyPrint(tokens: TraversableOnce[ReplToken]) { - new TokenPrinter prettyPrint tokens - } - - private class TokenPrinter { - type TokenTriple = (ReplToken, ReplToken, ReplToken) - val writer = new Indenter - var prev: List[ReplToken] = Nil - - def isIdentPart(t: ReplToken) = t match { - case Dot | Id(_) => true - case _ => false - } - def prevNonIdent = prev dropWhile isIdentPart match { - case Nil => ErrorToken - case t :: _ => t - } - def inImport = prevNonIdent == Import - - def printToken(left: ReplToken, token: ReplToken) = token match { - case LBrace => - writer openIndent ( - if (writer.atStartOfLine) token - else " " + token - ) - case RBrace => - writer.closeIndent(token) - case tok @ (Newline | Newlines) => - writer.nextIndent(tok) - case _ => - writer print ( - if (writer.atStartOfLine) token - else if (left <--?--> token) token - else " " + token - ) - } - - def prettyPrint(tokens: TraversableOnce[ReplToken]) { - val it = Iterator(Newline) ++ tokens.toIterator ++ Iterator(Newline) sliding 3 map { x => - val List(x1, x2, x3) = x - ((x1, x2, x3)) - } - prettyPrint(it) - } - def prettyPrint(it: Iterator[TokenTriple]) { - while (it.hasNext) it.next match { - // special casing to avoid newline on empty blocks - case (left, LBrace, RBrace) => - it.next - writer print " { }" - // special casing to avoid newlines on import x.{ y, z, q } - case (left, LBrace, _) if inImport => - writer print LBrace - def loop() { - if (it.hasNext) { - val (_, tok, _) = it.next - if (tok != Comma) { - writer print " " - } - writer print tok - if (tok != RBrace) - loop() - } - } - loop() - case (left, token, right) => - printToken(left, token) - - if (it.hasNext) prev ::= token - else printToken(token, right) - } - } - } -} diff --git a/src/compiler/scala/tools/nsc/interpreter/session/JLineHistory.scala b/src/compiler/scala/tools/nsc/interpreter/session/JLineHistory.scala index a09182319c..795ca79668 100644 --- a/src/compiler/scala/tools/nsc/interpreter/session/JLineHistory.scala +++ b/src/compiler/scala/tools/nsc/interpreter/session/JLineHistory.scala @@ -45,11 +45,5 @@ object JLineHistory { override def toString = "History(size = " + size + ", index = " + index + ")" } - def apply(): JLineHistory = - try { new JLineFileHistory } - catch { case x: Exception => - Console.println("Error creating file history: memory history only. " + x) - util.Exceptional(x).show() - new SimpleHistory() - } -}
\ No newline at end of file + def apply(): JLineHistory = try new JLineFileHistory catch { case x: Exception => new SimpleHistory() } +} diff --git a/src/compiler/scala/tools/nsc/io/NullPrintStream.scala b/src/compiler/scala/tools/nsc/io/NullPrintStream.scala deleted file mode 100644 index 52c7ddc74b..0000000000 --- a/src/compiler/scala/tools/nsc/io/NullPrintStream.scala +++ /dev/null @@ -1,37 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.nsc -package io - -import java.io.{ PrintStream, ByteArrayOutputStream } - -/** A sink for when you want to discard all output. - */ -class NullPrintStream extends PrintStream(new ByteArrayOutputStream()) { } - -object NullPrintStream extends NullPrintStream { - def setOut() = Console setOut this - def setErr() = Console setErr this - def setOutAndErr() = { setOut() ; setErr() } - def sinkingOutAndErr[T](body: => T): T = - Console.withOut(this) { - Console.withErr(this) { - body - } - } - - def sinkingSystemOutAndErr[T](body: => T): T = { - val savedOut = System.out - val savedErr = System.err - System setOut NullPrintStream - System setErr NullPrintStream - try body - finally { - System setOut savedOut - System setErr savedErr - } - } -} diff --git a/src/compiler/scala/tools/nsc/io/Sources.scala b/src/compiler/scala/tools/nsc/io/Sources.scala deleted file mode 100644 index 25d27acae8..0000000000 --- a/src/compiler/scala/tools/nsc/io/Sources.scala +++ /dev/null @@ -1,86 +0,0 @@ -package scala.tools.nsc -package io - -import util.ClassPath -import java.util.concurrent.{ Future, ConcurrentHashMap, ExecutionException } -import java.util.zip.ZipException -import collection.JavaConverters._ -import Properties.{ envOrElse, propOrElse } - -class Sources(val path: String) { - val expandedPath = ClassPath.join(ClassPath expandPath path: _*) - val cache = new ConcurrentHashMap[String, List[Fileish]] - def allNames = cache.keys.asScala.toList.sorted - def apply(name: String) = get(name) - def size = cache.asScala.values map (_.length) sum - def isEmpty = path == "" - - private var debug = false - private def dbg(msg: => Any) = if (debug) Console println msg - private val partitioned = ClassPath toPaths expandedPath partition (_.isDirectory) - - val dirs = partitioned._1 map (_.toDirectory) - val jars = partitioned._2 filter Jar.isJarOrZip map (_.toFile) - val (isDone, force) = ( - if (path == "") (() => true, () => ()) - else { - val f1 = spawn(calculateDirs()) - val f2 = spawn(calculateJars()) - val fn1 = () => { f1.isDone() && f2.isDone() } - val fn2 = () => { f1.get() ; f2.get() ; () } - - (fn1, fn2) - } - ) - - private def catchZip(body: => Unit): Unit = { - try body - catch { case x: ZipException => dbg("Caught: " + x) } - } - - private def calculateDirs() = - dirs foreach { d => dbg(d) ; catchZip(addSources(d.deepFiles map (x => Fileish(x)))) } - - private def calculateJars() = - jars foreach { j => dbg(j) ; catchZip(addSources(new Jar(j).fileishIterator)) } - - private def addSources(fs: TraversableOnce[Fileish]) = - fs foreach { f => if (f.isSourceFile) add(f.name, f) } - - private def get(key: String): List[Fileish] = - if (cache containsKey key) cache.get(key) else Nil - - private def add(key: String, value: Fileish) = { - if (cache containsKey key) cache.replace(key, value :: cache.get(key)) - else cache.put(key, List(value)) - } - override def toString = "Sources(%d dirs, %d jars, %d sources)".format( - dirs.size, jars.size, cache.asScala.values map (_.length) sum - ) -} - -trait LowPrioritySourcesImplicits { - self: Sources.type => - - implicit def fallbackSources: Sources = defaultSources -} - -object Sources extends LowPrioritySourcesImplicits { - val empty = new Sources("") - - private def libraryInits = ClassPath.scalaLibrary.toList flatMap (_.toAbsolute.parents) - private def librarySourceDir = libraryInits map (_ / "src") find (_.isDirectory) - private def expandedSourceDir = librarySourceDir.toList flatMap (ClassPath expandDir _.path) - - private val initialPath = sys.props.traceSourcePath.value - private val initialSources = apply(expandedSourceDir :+ initialPath: _*) - - def defaultSources = { - val path = sys.props.traceSourcePath.value - if (path == "") empty - else if (path == initialPath) initialSources - else apply(expandedSourceDir :+ path: _*) - } - - def apply(paths: String*): Sources = new Sources(ClassPath.join(paths: _*)) -} diff --git a/src/compiler/scala/tools/nsc/io/package.scala b/src/compiler/scala/tools/nsc/io/package.scala index 52e6de0bed..d29030603e 100644 --- a/src/compiler/scala/tools/nsc/io/package.scala +++ b/src/compiler/scala/tools/nsc/io/package.scala @@ -23,9 +23,6 @@ package object io { def callable[T](body: => T): Callable[T] = new Callable[T] { override def call() = body } def spawn[T](body: => T): Future[T] = daemonThreadPool submit callable(body) def submit(runnable: Runnable) = daemonThreadPool submit runnable - def runnableFn(f: () => Unit): Runnable = runnable(f()) - def callableFn[T](f: () => T): Callable[T] = callable(f()) - def spawnFn[T](f: () => T): Future[T] = spawn(f()) // Create, start, and return a daemon thread def daemonize(body: => Unit): Thread = newThread(_ setDaemon true)(body) diff --git a/src/compiler/scala/tools/nsc/reporters/ReporterTimer.scala b/src/compiler/scala/tools/nsc/reporters/ReporterTimer.scala deleted file mode 100644 index f55d0684c8..0000000000 --- a/src/compiler/scala/tools/nsc/reporters/ReporterTimer.scala +++ /dev/null @@ -1,18 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2002-2011 LAMP/EPFL - * @author Martin Odersky - */ - -package scala.tools.nsc -package reporters - -import scala.tools.util.AbstractTimer - -/** - * This class implements a timer that uses a Reporter to issue - * timings. - */ -class ReporterTimer(reporter: Reporter) extends AbstractTimer { - def issue(msg: String, duration: Long) = - reporter.info(null, "[" + msg + " in " + duration + "ms]", false) -} diff --git a/src/compiler/scala/tools/nsc/settings/AestheticSettings.scala b/src/compiler/scala/tools/nsc/settings/AestheticSettings.scala index 63775ff1c5..2baff0bb1c 100644 --- a/src/compiler/scala/tools/nsc/settings/AestheticSettings.scala +++ b/src/compiler/scala/tools/nsc/settings/AestheticSettings.scala @@ -27,7 +27,6 @@ trait AestheticSettings { def future = settings.future.value def logClasspath = settings.Ylogcp.value def printStats = settings.Ystatistics.value - def richExes = settings.YrichExes.value || sys.props.traceSourcePath.isSet def target = settings.target.value def unchecked = settings.unchecked.value def verbose = settings.verbose.value diff --git a/src/compiler/scala/tools/nsc/settings/ImmutableSettings.scala b/src/compiler/scala/tools/nsc/settings/ImmutableSettings.scala deleted file mode 100644 index 4de0c2332c..0000000000 --- a/src/compiler/scala/tools/nsc/settings/ImmutableSettings.scala +++ /dev/null @@ -1,11 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.nsc -package settings - -/** TODO. - */ -class ImmutableSettings diff --git a/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala b/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala index 0a9d25af7e..4aa30038f6 100644 --- a/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala +++ b/src/compiler/scala/tools/nsc/settings/ScalaSettings.scala @@ -89,7 +89,7 @@ trait ScalaSettings extends AbsScalaSettings val Xmigration28 = BooleanSetting ("-Xmigration", "Warn about constructs whose behavior may have changed between 2.7 and 2.8.") val nouescape = BooleanSetting ("-Xno-uescape", "Disable handling of \\u unicode escapes.") val Xnojline = BooleanSetting ("-Xnojline", "Do not use JLine for editing.") - val Xverify = BooleanSetting ("-Xverify", "Verify generic signatures in generated bytecode.") + val Xverify = BooleanSetting ("-Xverify", "Verify generic signatures in generated bytecode (asm backend only.)") val plugin = MultiStringSetting("-Xplugin", "file", "Load one or more plugins from files.") val disable = MultiStringSetting("-Xplugin-disable", "plugin", "Disable the given plugin(s).") val showPlugins = BooleanSetting ("-Xplugin-list", "Print a synopsis of loaded plugins.") @@ -146,9 +146,6 @@ trait ScalaSettings extends AbsScalaSettings val noimports = BooleanSetting ("-Yno-imports", "Compile without importing scala.*, java.lang.*, or Predef.") val nopredef = BooleanSetting ("-Yno-predef", "Compile without importing Predef.") val noAdaptedArgs = BooleanSetting ("-Yno-adapted-args", "Do not adapt an argument list (either by inserting () or creating a tuple) to match the receiver.") - val Yprofile = PhasesSetting ("-Yprofile", "(Requires jvm -agentpath to contain yjgpagent) Profile CPU usage of") - val YprofileMem = BooleanSetting ("-Yprofile-memory", "Profile memory, get heap snapshot after each compiler run (requires yjpagent, see above).") - val YprofileClass = StringSetting ("-Yprofile-class", "class", "Name of profiler class.", "scala.tools.util.YourkitProfiling") val Yrecursion = IntSetting ("-Yrecursion", "Set recursion depth used when locking symbols.", 0, Some((0, Int.MaxValue)), (_: String) => None) val selfInAnnots = BooleanSetting ("-Yself-in-annots", "Include a \"self\" identifier inside of annotations.") val Xshowtrees = BooleanSetting ("-Yshow-trees", "(Requires -Xprint:) Print detailed ASTs in formatted form.") @@ -167,9 +164,7 @@ trait ScalaSettings extends AbsScalaSettings val stopBefore = PhasesSetting ("-Ystop-before", "Stop before") val refinementMethodDispatch = ChoiceSetting ("-Ystruct-dispatch", "policy", "structural method dispatch policy", List("no-cache", "mono-cache", "poly-cache", "invoke-dynamic"), "poly-cache") - val globalClass = StringSetting ("-Yglobal-class", "class", "subclass of scala.tools.nsc.Global to use for compiler", "") val Yrangepos = BooleanSetting ("-Yrangepos", "Use range positions for syntax trees.") - val YrichExes = BooleanSetting ("-Yrich-exceptions", "Fancier exceptions. Set source search path with -D" + sys.SystemProperties.traceSourcePath.key) val Ybuilderdebug = ChoiceSetting ("-Ybuilder-debug", "manager", "Compile using the specified build manager.", List("none", "refined", "simple"), "none") val Yreifycopypaste = BooleanSetting ("-Yreify-copypaste", "Dump the reified trees in copypasteable representation.") val Yreplsync = BooleanSetting ("-Yrepl-sync", "Do not use asynchronous code for repl startup") @@ -180,7 +175,6 @@ trait ScalaSettings extends AbsScalaSettings val YvirtClasses = false // too embryonic to even expose as a -Y //BooleanSetting ("-Yvirtual-classes", "Support virtual classes") val exposeEmptyPackage = BooleanSetting("-Yexpose-empty-package", "Internal only: expose the empty package.").internalOnly() - val YnoProductN = BooleanSetting ("-Yno-productN", "Do not add ProductN to case classes") def stop = stopAfter diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala index ef73d6db1a..7c61ec032e 100644 --- a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala +++ b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala @@ -13,7 +13,6 @@ import scala.collection.{ mutable, immutable } import scala.collection.mutable.{ ListBuffer, ArrayBuffer } import scala.annotation.switch import scala.reflect.internal.pickling.{PickleBuffer, ByteCodecs} -import scala.reflect.internal.{ JvmClassInfo, JvmMemberInfo } import scala.tools.nsc.io.AbstractFile /** This abstract class implements a class file parser. @@ -47,8 +46,6 @@ abstract class ClassfileParser { private def currentIsTopLevel = currentClass.toString.indexOf('$') < 0 - private var jvmInfo: JvmClassInfo = _ - private object unpickler extends scala.reflect.internal.pickling.UnPickler { val global: ClassfileParser.this.global.type = ClassfileParser.this.global } @@ -98,7 +95,6 @@ abstract class ClassfileParser { this.in = new AbstractFileReader(file) this.clazz = if (root.isModule) root.companionClass else root this.staticModule = clazz.companionModule - this.jvmInfo = JvmClassInfo.fromBytes(file.toByteArray) this.isScala = false parseHeader @@ -1245,9 +1241,6 @@ abstract class ClassfileParser { in.skip(2 * ifaces) } - protected def getOwner(info: JvmMemberInfo): Symbol = - if (info.isStatic) moduleClass else clazz - protected def getOwner(flags: Int): Symbol = if (isStatic(flags)) moduleClass else clazz diff --git a/src/compiler/scala/tools/nsc/transform/Erasure.scala b/src/compiler/scala/tools/nsc/transform/Erasure.scala index 3de287e58c..ea66dbedd6 100644 --- a/src/compiler/scala/tools/nsc/transform/Erasure.scala +++ b/src/compiler/scala/tools/nsc/transform/Erasure.scala @@ -6,7 +6,6 @@ package scala.tools.nsc package transform -import scala.tools.reflect.SigParser import scala.reflect.internal.ClassfileConstants._ import scala.collection.{ mutable, immutable } import symtab._ @@ -66,16 +65,6 @@ abstract class Erasure extends AddInterfaces } } - // for debugging signatures: traces logic given system property - // performance: get the value here - val traceSignatures = (sys.BooleanProp keyExists "scalac.sigs.trace").value - private object traceSig extends util.Tracer(() => traceSignatures) { - override def stringify(x: Any) = x match { - case tp: Type => super.stringify(dropAllRefinements(tp)) - case _ => super.stringify(x) - } - } - override protected def verifyJavaErasure = settings.Xverify.value || settings.debug.value def needsJavaSig(tp: Type) = !settings.Ynogenericsig.value && NeedsSigCollector.collect(tp) @@ -173,21 +162,6 @@ abstract class Erasure extends AddInterfaces } } - /** Run the signature parser to catch bogus signatures. - */ - def isValidSignature(sym: Symbol, sig: String) = ( - /** Since we're using a sun internal class for signature validation, - * we have to allow for it not existing or otherwise malfunctioning: - * in which case we treat every signature as valid. Medium term we - * should certainly write independent signature validation. - */ - SigParser.isParserAvailable && ( - if (sym.isMethod) SigParser verifyMethod sig - else if (sym.isTerm) SigParser verifyType sig - else SigParser verifyClass sig - ) - ) - private def hiBounds(bounds: TypeBounds): List[Type] = bounds.hi.normalize match { case RefinedType(parents, _) => parents map (_.normalize) case tp => tp :: Nil @@ -199,7 +173,7 @@ abstract class Erasure extends AddInterfaces def javaSig(sym0: Symbol, info: Type): Option[String] = beforeErasure { val isTraitSignature = sym0.enclClass.isTrait - def superSig(parents: List[Type]) = traceSig("superSig", parents) { + def superSig(parents: List[Type]) = { val ps = ( if (isTraitSignature) { // java is unthrilled about seeing interfaces inherit from classes @@ -213,7 +187,7 @@ abstract class Erasure extends AddInterfaces (ps map boxedSig).mkString } def boxedSig(tp: Type) = jsig(tp, primitiveOK = false) - def boundsSig(bounds: List[Type]) = traceSig("boundsSig", bounds) { + def boundsSig(bounds: List[Type]) = { val (isTrait, isClass) = bounds partition (_.typeSymbol.isTrait) val classPart = isClass match { case Nil => ":" // + boxedSig(ObjectClass.tpe) @@ -222,7 +196,7 @@ abstract class Erasure extends AddInterfaces classPart :: (isTrait map boxedSig) mkString ":" } def paramSig(tsym: Symbol) = tsym.name + boundsSig(hiBounds(tsym.info.bounds)) - def polyParamSig(tparams: List[Symbol]) = traceSig("polyParamSig", tparams) ( + def polyParamSig(tparams: List[Symbol]) = ( if (tparams.isEmpty) "" else tparams map paramSig mkString ("<", "", ">") ) @@ -315,22 +289,11 @@ abstract class Erasure extends AddInterfaces else jsig(etp) } } - val result = traceSig("javaSig", (sym0, info)) { - if (needsJavaSig(info)) { - try Some(jsig(info, toplevel = true)) - catch { case ex: UnknownSig => None } - } - else None - } - // Debugging: immediately verify signatures when tracing. - if (traceSignatures) { - result foreach { sig => - if (!isValidSignature(sym0, sig)) - println("**** invalid signature for " + sym0 + ": " + sig) - } + if (needsJavaSig(info)) { + try Some(jsig(info, toplevel = true)) + catch { case ex: UnknownSig => None } } - - result + else None } class UnknownSig extends Exception diff --git a/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala b/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala index 08bf581256..0c1638b76f 100644 --- a/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala +++ b/src/compiler/scala/tools/nsc/typechecker/ContextErrors.scala @@ -9,7 +9,6 @@ package typechecker import scala.collection.{ mutable, immutable } import scala.tools.util.StringOps.{ countElementsAsString, countAsString } import symtab.Flags.{ PRIVATE, PROTECTED } -import scala.tools.util.EditDistance.similarString trait ContextErrors { self: Analyzer => @@ -171,36 +170,7 @@ trait ContextErrors { NormalTypeError(tree, "reference to " + name + " is ambiguous;\n" + msg) def SymbolNotFoundError(tree: Tree, name: Name, owner: Symbol, startingIdentCx: Context) = { - /*** Disabled pending investigation of performance impact. - - // This laborious determination arrived at to keep the tests working. - val calcSimilar = ( - name.length > 2 && ( - startingIdentCx.reportErrors - || startingIdentCx.enclClassOrMethod.reportErrors - ) - ) - // avoid calculating if we're in "silent" mode. - // name length check to limit unhelpful suggestions for e.g. "x" and "b1" - val similar = { - if (!calcSimilar) "" - else { - val allowed = ( - startingIdentCx.enclosingContextChain - flatMap (ctx => ctx.scope.toList ++ ctx.imports.flatMap(_.allImportedSymbols)) - filter (sym => sym.isTerm == name.isTermName) - filterNot (sym => sym.isPackage || sym.isSynthetic || sym.hasMeaninglessName) - ) - val allowedStrings = ( - allowed.map("" + _.name).distinct.sorted - filterNot (s => (s contains '$') || (s contains ' ')) - ) - similarString("" + name, allowedStrings) - } - } - */ - val similar = "" - NormalTypeError(tree, "not found: "+decodeWithKind(name, owner) + similar) + NormalTypeError(tree, "not found: "+decodeWithKind(name, owner)) } // typedAppliedTypeTree diff --git a/src/compiler/scala/tools/nsc/typechecker/Implicits.scala b/src/compiler/scala/tools/nsc/typechecker/Implicits.scala index 793b85da18..8f025336bb 100644 --- a/src/compiler/scala/tools/nsc/typechecker/Implicits.scala +++ b/src/compiler/scala/tools/nsc/typechecker/Implicits.scala @@ -764,12 +764,14 @@ trait Implicits { * so that if there is a best candidate it can still be selected. */ private var divergence = false - private val MaxDiverges = 1 // not sure if this should be > 1 - private val divergenceHandler = util.Exceptional.expiringHandler(MaxDiverges) { - case x: DivergentImplicit => - divergence = true - log("discarding divergent implicit during implicit search") - SearchFailure + private val divergenceHandler: PartialFunction[Throwable, SearchResult] = { + var remaining = 1; + { case x: DivergentImplicit if remaining > 0 => + remaining -= 1 + divergence = true + log("discarding divergent implicit during implicit search") + SearchFailure + } } /** Sorted list of eligible implicits. diff --git a/src/compiler/scala/tools/nsc/util/Exceptional.scala b/src/compiler/scala/tools/nsc/util/Exceptional.scala index 7452aa1b67..7c093b7866 100644 --- a/src/compiler/scala/tools/nsc/util/Exceptional.scala +++ b/src/compiler/scala/tools/nsc/util/Exceptional.scala @@ -3,141 +3,10 @@ package util import java.util.concurrent.ExecutionException import java.lang.reflect.{ InvocationTargetException, UndeclaredThrowableException } -import io.{ Sources, Fileish } import scala.tools.util.StringOps._ import language.implicitConversions -/** A simple throwable wrapper so it looks more like a parade of - * glittering frame-shaped beauties than the other thing. - */ -class Exceptional(val ex: Throwable)(implicit prefs: ScalaPrefs) { - val formatter = prefs.exceptionFormatter(ex) - val unwrapped = Exceptional.unwrap(ex) - val table = formatter.newTable(unwrapped) - def rawTrace() = unwrapped.printStackTrace() - def isScanDone = prefs.codeSources.isDone() - - /** Block until the scanning is complete. */ - def force(): this.type = { - prefs.codeSources.force() - this - } - - /** Stack frame contexts are only shown as long as this is true. */ - def spanFn(frame: JavaStackFrame): Boolean = true - - /** The result of this will be printed before a context trace. */ - def contextPrelude: String = - if (isScanDone || prefs.codeSources.isEmpty) "" - else "/* Still scanning source path: there may be more momentarily. */\n" - - /** Frames with surrounding context. */ - private def contextFrames = toList takeWhile spanFn - def contextHead(): String = contextElems.headOption getOrElse "" - def contextElems() = contextFrames map formatter.inContext - def context(): String = context(length) - def context(num: Int): String = contextPrelude + ojoinOr(contextFrames take num map formatter.inContext, "\n", "No stack trace.") - - /** Exceptional doesn't extend Seq because it turns out to be super - * annoying in the repl: tab-completion sees all the Seq methods. - */ - def length = toList.length - def toList = table.toList - def iterator = table.iterator - def apply(index: Int) = table(index) - - def causes = Exceptional.causes(ex) - def summary = unwrapped.toString + "\n at " + apply(0).shortNameString - - private def println(msg: Any) = { - Console println msg - Console.flush() - } - - def show(): Unit = println(context()) - def show(num: Int): Unit = println(context(num)) - def showCauses() = println((ex :: causes).mkString("", "\n caused by -> ", "")) - def showTable() = println(table) - def showSummary() = println(summary) - - override def toString = summary -} - - object Exceptional { - type Catcher[+T] = PartialFunction[Throwable, T] - - /** Creates an exception handler which will only ever catch the given - * number of exceptions (if the given pf is defined there) and after - * that will disable itself. - */ - def expiringHandler[T](numCatches: Int)(pf: Catcher[T]): Catcher[T] = { - var remaining = numCatches; - { case ex: Throwable if remaining > 0 && pf.isDefinedAt(ex) => - remaining -= 1 - pf(ex) - } - } - - /** The Throwable => Exceptional implicit plus the associated factory. */ - implicit def throwableToExceptional(ex: Throwable)(implicit prefs: ScalaPrefs): Exceptional = apply(ex)(prefs) - def apply(ex: Throwable)(implicit prefs: ScalaPrefs) = new Exceptional(ex)(prefs) - - /** Some handy functions. */ - def stack() = JavaStackFrame frames ((new Throwable).getStackTrace dropWhile isLocal) - def showme() = apply(new Throwable).show() - def showstack() = apply(new Throwable).showTable() - - /** A frame formatter with more refined aesthetics than the default. - * Come, let us be civilized. - */ - object ScalaFormat extends TableDef[JavaStackFrame] { - >> ("file" -> (_.fileName)) >+ ":" - << ("line" -> (_.line)) - >> ("class" -> (_.shortestName)) >+ "." - << ("method" -> (_.methodName)) - } - - trait Calibrated { - def newTable(ex: Throwable): TableDef[JavaStackFrame]#Table - def inContext(frame: JavaStackFrame): String - } - trait Formatter extends (Throwable => Calibrated) { - def apply(ex: Throwable): Calibrated - } - object Formatter { - def apply(implicit prefs: ScalaPrefs): Formatter = new Formatter { - def apply(ex: Throwable) = new Calibrated { - def newTable(ex: Throwable) = new ScalaFormat.Table(JavaStackFrame frames ex) - def inContext(frame: JavaStackFrame) = new FrameContext(frame, prefs.codeSources) toString - } - } - } - - /** Java stack traces have the interesting property of using only the name - * of the file, no paths. This makes it a bit of a gamble to try to associate - * a stack frame with a specific file. Witness the heuristic. - */ - def locateSources(sources: Sources, frame: JavaStackFrame): List[Fileish] = { - // if only one has a matching path, that's fairly sure to be the one - val matches = sources(frame.fileName) filter (_.pkgFromPath endsWith frame.pkgName) - if (matches.isEmpty || matches.tail.isEmpty) - return matches - - // otherwise we'll drink them in and look for a package name - matches filter (_.pkgFromSource endsWith frame.pkgName) - } - - /** Right now this punts if more than one match and it accepts the first at random. - */ - def locateSource(sources: Sources, frame: JavaStackFrame): Option[Fileish] = - locateSources(sources, frame).headOption - - def isLocal(ste: StackTraceElement) = ste.getClassName startsWith this.getClass.getName - def causes(x: Throwable): List[Throwable] = x.getCause match { - case null => Nil - case ex => x :: causes(ex) - } def unwrap(x: Throwable): Throwable = x match { case _: InvocationTargetException | _: ExceptionInInitializerError | diff --git a/src/compiler/scala/tools/nsc/util/FlagsUtil.scala b/src/compiler/scala/tools/nsc/util/FlagsUtil.scala deleted file mode 100644 index b615775468..0000000000 --- a/src/compiler/scala/tools/nsc/util/FlagsUtil.scala +++ /dev/null @@ -1,233 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.nsc -package util - -// Overloading invariants: these are "pseudoinvariants" because many of the -// methods do not exist on Modifiers, only on Symbol, not to mention it is only -// speculative that they are mutually exclusive: but is here to provide a -// starting point for further refinement. -// -// 16: BYNAMEPARAM CAPTURED COVARIANT -// x.isParameter ==> BYNAMEPARAM -// x.isMutable ==> CAPTURED -// x.isType ==> COVARIANT -// -// 17: CONTRAVARIANT INCONSTRUCTOR LABEL -// x.isType ==> CONTRAVARIANT -// x.isClass ==> INCONSTRUCTOR -// x.isMethod ==> LABEL -// -// 25: DEFAULTPARAM TRAIT -// x.isParameter ==> DEFAULTPARAM -// x.isClass ==> TRAIT -// -// 35: EXISTENTIAL MIXEDIN -// x.isType ==> EXISTENTIAL -// x.isTerm ==> MIXEDIN -// -// 37: IMPLCLASS PRESUPER -// x.isClass ==> IMPLCLASS -// x.isTerm ==> PRESUPER - -import scala.collection.{ mutable, immutable } -import symtab.Flags.ExplicitFlags - -class TransFlagManager[T <: Global](val global: T) { - import global._ - import definitions._ - - private var trackerStack: List[FlagTracker] = Nil - private def trackerString = trackerStack.mkString(" ") - - class FlagTracker(val name: String) { - private val mask = symtab.Flags.TRANS_FLAG - private val seen = new mutable.HashSet[Symbol] - - private def doWeOwnFlag = trackerStack.headOption exists (_ eq this) - private def isOK = trackerStack.isEmpty || (trackerStack.head eq this) - - def apply(sym: Symbol) = { - if (!isOK) - log("Testing " + sym.name + " for " + name + " flag, but not at top of stack: " + trackerString) - - sym hasFlag mask - } - def set(sym: Symbol) = { - if (!isOK) - log("Tried to set " + name + " but not at top of stack: " + trackerString) - - seen += sym - sym setFlag mask - } - def reset(sym: Symbol) = { - if (!isOK) - log("Tried to clear " + name + " but not at top of stack: " + trackerString) - - seen -= sym - sym resetFlag mask - } - def clear() { - if (!doWeOwnFlag && seen.nonEmpty) - log("Clearing " + seen.size + " " + name + " flags even though the stack is: " + trackerString) - - seen foreach (_ resetFlag mask) - seen.clear() - } - } - - def forceClear() = { - if (trackerStack.nonEmpty) { - log("Warning: force clearing the stack at " + phase + ": " + trackerString) - trackerStack foreach (_.clear()) - trackerStack = Nil - } - } - - def claimTransFlag(label: String): FlagTracker = { - if (trackerStack.isEmpty || trackerStack.head.name != label) - trackerStack ::= new FlagTracker(label) - - trackerStack.head - } - def releaseTransFlag(label: String): Boolean = { - trackerStack.isEmpty || { - if (trackerStack.head.name == label) { - trackerStack.head.clear() - trackerStack = trackerStack.tail - true - } - else { - log("Warning: trying to release " + label + " flag but the stack is: " + trackerStack.mkString(" ")) - false - } - } - } - def holdingTransFlag[U](label: String)(f: FlagTracker => U): U = { - try { - val t = claimTransFlag(label) - f(t) - } - finally { - releaseTransFlag(label) - } - } -} - - -/** Some functions for generating comments and methods involving flags, - * with the output determined by reflection so we can have a little more - * assurance that documentation and debugging output match up with reality. - * - * For the compiler, the output can be generated with: - * scala scala.tools.nsc.util.FlagsUtilCompiler - */ -class FlagsUtil(flagsObject: AnyRef) { - /** Override to tweak flag strings before output. */ - def addFlagMetadata(name: String) = name - - /** Runs the generative methods in this class. */ - def reflectiveAnalyzeFlags() = { - mkFlagsTable() - println("") - mkFlagToStringMethod() - } - /** A list of the flag names found at each bit position. - */ - def reflectiveFlagNames: List[List[String]] = { - val pairs = flagMethods map { m => - m.getName -> ((m invoke flagsObject) match { - case x: java.lang.Integer => x.intValue: Long - case x: java.lang.Long => x.longValue - }) - } - (0 to 63).toList map { idx => - pairs collect { case (name, value) if value == (1L << idx) => name } - } - } - /** Prints a comment table identifying all the flags (as seen - * via reflection) and at what bit each is located. - */ - def mkFlagsTable() = { - val markedFlagNames = reflectiveFlagNames map (_ map addFlagMetadata) - - val widths = 0 to 2 map { column => - markedFlagNames collect { case xs if xs.length > column => - xs(column).length - } max - } - val fmt = "// %2d: " + (widths map ("%" + _ + "s") mkString " ") - def padded(xs: List[String]) = xs match { - case Nil => List("", "", "") - case x :: Nil => List(x, "", "") - case x1 :: x2 :: Nil => List(x1, x2, "") - case _ => xs take 3 - } - println("// Generated by mkFlagsTable() at " + now + "\n//") - // prints the grid showing which flags are at each index - for ((names, idx) <- markedFlagNames.zipWithIndex) { - println(fmt.format(idx :: padded(names) : _*)) - } - } - /** Prints an implementation of flagToString based on the reflectively - * determined contents of the flags class. - */ - def mkFlagToStringMethod() = { - def key(xs: List[String], flag: Long) = xs match { - case Nil => "%19s".format("0x" + "%x".format(flag) + "L") - case x :: _ => - if (x.head.isLower) "`" + x + "`" - else x - } - def value(xs: List[String], flag: Long) = "\"" + (xs match { - case Nil => "" - case x :: Nil if (flag & ExplicitFlags) != 0 => x.toLowerCase - case xs => xs.map(_.toLowerCase).mkString("<", "/", ">") - }) + "\"" - val pairs: List[(String, String)] = reflectiveFlagNames.zipWithIndex map { - case (xs, idx) => (key(xs, 1L << idx), value(xs, 1L << idx)) - } - val keyWidth = pairs map (_._1.length) max - val bodyWidth = pairs map (_._2.length) max - val fmt = " case %" + keyWidth + "s => %-" + bodyWidth + "s // (1L << %d)" - - println("// Generated by mkFlagToStringMethod() at " + now) - println("@annotation.switch override def flagToString(flag: Long): String = flag match {") - for (((key, body), idx) <- pairs.zipWithIndex) { - print(fmt.format(key, body, idx)) - println("") - } - println(" case _ => \"\"") - println("}") - } - - def isFlagName(s: String) = s stripPrefix "late" stripPrefix "not" forall (x => x.isUpper || x == '_') - def flagMethods = flagsObject.getClass.getMethods.toList filter (x => isFlagName(x.getName)) sortBy (_.getName) - private def now = new java.util.Date toString -} - -object FlagsUtil { - import reflect.internal.ModifierFlags - - trait MarkModifiers extends FlagsUtil { - lazy val isModifiersFlag = classOf[ModifierFlags].getMethods map (_.getName) filter isFlagName toSet - override def addFlagMetadata(name: String) = { - if (isModifiersFlag(name)) name + "/M" - else name - } - } -} - -/** Convenience standalone programs. - */ -object FlagsUtilCompiler extends FlagsUtil(symtab.Flags) with FlagsUtil.MarkModifiers { - def main(args: Array[String]): Unit = reflectiveAnalyzeFlags() -} - -object FlagsUtilLibrary extends FlagsUtil(reflect.internal.Flags) with FlagsUtil.MarkModifiers { - def main(args: Array[String]): Unit = reflectiveAnalyzeFlags() -} - diff --git a/src/compiler/scala/tools/nsc/util/Indenter.scala b/src/compiler/scala/tools/nsc/util/Indenter.scala deleted file mode 100644 index f9ddc4a194..0000000000 --- a/src/compiler/scala/tools/nsc/util/Indenter.scala +++ /dev/null @@ -1,85 +0,0 @@ -package scala.tools.nsc -package util - -import java.io.PrintStream - -class Indenter(var stringFn: Any => String) { - def this() = this("" + _) - def out: PrintStream = System.out - - var indentSpaces = 2 - var isSorted = false - var openString = "" - var closeString = "" - - def braces: this.type = { - openString = " {" - closeString = "}" - this - } - def sorted: this.type = { isSorted = true ; this } - def stringify(fn: Any => String): this.type = { - stringFn = fn - this - } - - def atStartOfLine = startOfLine - private var indentLevel = 0 - private var startOfLine = true - def indent: this.type = { indentLevel += 1 ; this } - def undent: this.type = { indentLevel -= 1 ; this } - def currentIndent = " " * indentLevel * indentSpaces - def printIndent() = { - out.print(currentIndent) - startOfLine = true - } - - // Execute the given body indented one level further. - def >>[T](body: => T): T = { - indentLevel += 1 - try body - finally indentLevel -= 1 - } - - def openIndent(token: Any) { - print(token + "\n") - indent - printIndent() - } - def closeIndent(token: Any) { - print("\n") - undent - printIndent() - print(token) - } - def finishLine(token: Any) { - print(token) - printIndent() - } - def nextIndent(endOfLine: Any) = finishLine(endOfLine) - - def block(label: String)(body: => Unit) { - if (label != "" || openString != "") - pp(label + openString) - - this >> body - - if (closeString != "") - pp(closeString) - } - def print(x: Any) = { - out print stringFn(x) - out.flush() - startOfLine = false - } - def pps(xs: TraversableOnce[Any]) { - if (isSorted) xs.toSeq.sortBy("" + _) foreach pp - else xs foreach pp - } - def pp(x: Any) { - printIndent() - out println stringFn(x) - out.flush() - startOfLine = false - } -} diff --git a/src/compiler/scala/tools/nsc/util/JavaStackFrame.scala b/src/compiler/scala/tools/nsc/util/JavaStackFrame.scala deleted file mode 100644 index d25698ed38..0000000000 --- a/src/compiler/scala/tools/nsc/util/JavaStackFrame.scala +++ /dev/null @@ -1,71 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.nsc -package util - -import io.{ Fileish, Sources } -import Exceptional._ - -class FrameContext(frame: JavaStackFrame, codeSources: Sources) { - val sourceFile = locateSource(codeSources, frame) - import frame._ - - def windowWidth = 3 - def windowSize = windowWidth * 2 + 1 - - lazy val context = sourceFile collect { - case f if line > 0 => - val start = math.max(0, line - windowWidth) - f.lines().toList.slice(start, start + windowSize) - } getOrElse Nil - - protected def fallbackContext = "%s (%s:%s)".format(tag, fileName, line) - - private def linestr(index: Int) = { - val current = line - windowWidth + index - val marker = if (current == line) "*" else " " - marker + current - } - private def contextLines = context.zipWithIndex map { - case (l, i) => linestr(i) + ": " + l + "\n" - } - override def toString = - if (context.isEmpty) fallbackContext - else contextLines.mkString(tag + "\n", "", "") -} - -object FrameContext { - def apply(elem: StackTraceElement): FrameContext = apply(new JavaStackFrame(elem)) - def apply(frame: JavaStackFrame): FrameContext = new FrameContext(frame, Sources()) -} - -class JavaStackFrame(val elem: StackTraceElement) { - def className: String = elem.getClassName() - def methodName: String = elem.getMethodName() - def fileName: String = elem.getFileName() - def line: Int = elem.getLineNumber() - - private def segs = className takeWhile (ch => ch != '$' && ch != '(') split '.' toList ; - lazy val pkgName = segs.init mkString "." - lazy val shortName = segs.last - lazy val shortestName = if (fileName startsWith (shortName + ".")) "<--" else shortName - - private def standardString(which: String) = - "%s.%s(%s:%s)".format(which, methodName, fileName, line) - - def locationString = fileName + ":" + line - def javaString = standardString(className) - def shortNameString = standardString(shortName) - def tag = "[%s.%s]".format(shortName, methodName) - - override def toString = shortNameString -} - -object JavaStackFrame { - def apply(elem: StackTraceElement) = new JavaStackFrame(elem) - def frames(xs: Array[StackTraceElement]): Array[JavaStackFrame] = xs map (x => new JavaStackFrame(x)) - def frames(t: Throwable): Array[JavaStackFrame] = frames(Exceptional.unwrap(t).getStackTrace) -} diff --git a/src/compiler/scala/tools/nsc/util/ProxyReport.scala b/src/compiler/scala/tools/nsc/util/ProxyReport.scala deleted file mode 100644 index 4fc86c3a32..0000000000 --- a/src/compiler/scala/tools/nsc/util/ProxyReport.scala +++ /dev/null @@ -1,146 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.nsc -package util - -import scala.collection.{ mutable, immutable, generic } - -/** A class for analyzing forwarding/proxy relationships. - */ -trait ProxyReport { - val global: Global - import global._ - import definitions._ - - private object classes { - def isIgnorable(sym: Symbol) = sym :: sym.allOverriddenSymbols exists { s => - ObjectClass isSubClass s.owner - } - def nonPrivateMethods(sym: Symbol) = { - val methods = sym.initialize.tpe.nonPrivateMembers filter { x => - x.isMethod && !x.isConstructor && !x.isPrivate && !isIgnorable(x) - } - methods foreach (m => m.initialize.info.paramss.flatten foreach (_.initialize)) - methods - } - lazy val GlobalClass = getRequiredClass(classOf[Global].getName) - lazy val GenericClass = getRequiredModule("scala.collection.generic").moduleClass - lazy val CollectionClass = getRequiredModule("scala.collection").moduleClass - - def getType(name: String) = getMember(GlobalClass, newTypeName(name)) - def getColl(name: String) = getMember(CollectionClass, newTypeName(name)) - def getGeneric(name: String) = getMember(GenericClass, newTypeName(name)) - - // the following operations + those in RewrappingTypeProxy are all operations - // in class Type that are overridden in some subclass - // Important to keep this up-to-date when new operations are added! - def TypeClass = getType("Type") - def SimpleTypeProxy = getType("SimpleTypeProxy") - def RewrappingTypeProxy = getType("RewrappingTypeProxy") - - def TraversableForwarder = getGeneric("TraversableForwarder") - def IterableForwarder = getGeneric("IterableForwarder") - def SeqForwarder = getGeneric("SeqForwarder") - def TraversableLike = getColl("TraversableLike") - def TraversableProxy = getColl("TraversableProxyLike") - def IterableLike = getColl("IterableLike") - def IterableProxy = getColl("IterableProxyLike") - def MapLike = getColl("MapLike") - def MapProxy = getColl("MapProxyLike") - def SeqLike = getColl("SeqLike") - def SeqProxy = getColl("SeqProxyLike") - def SetLike = getColl("SetLike") - def SetProxy = getColl("SetProxyLike") - } - import classes._ - - val wrappedHeader = """ -/** With respect to %s, %s wraps: - */ -trait Wrapped { - """.trim - val unwrappedHeader = """ -/** With respect to %s, %s does NOT wrap: - */ -trait Unwrapped { - """.trim - - def wrapReport(underlying: Symbol, proxy: Symbol) = { - val underlyingMs = nonPrivateMethods(underlying) - val proxyMs = nonPrivateMethods(proxy) filterNot (_.owner == underlying) - val (wrapped, unwrapped) = underlyingMs partition (m => - proxyMs exists (p => - (p.name == m.name) && { - val self = proxy.thisType - val memberTp = self.memberType(p) - val parentTp = self.memberType(m) - - refChecks.overridesTypeInPrefix(memberTp, parentTp, self) - // || { - // // if (p.paramss.flatten.length == m.paramss.flatten.length) - // // println("names equal, overridesType false:\n " + ((p, m, memberTp, parentTp, self)) + "\n") - // - // false - // } - } - ) - ) - - def show(xs: List[Symbol], template: String) = { - val lines = xs.map(_.initialize.defString).sorted.map(" " + _ + "\n") - lines.mkString(template.format(underlying, proxy) + "\n", "", "}") - } - - show(wrapped, wrappedHeader) + "\n\n" + show(unwrapped, unwrappedHeader) - } - - lazy val wrappers = List( - TypeClass -> SimpleTypeProxy, - TypeClass -> RewrappingTypeProxy, - TraversableClass -> TraversableForwarder, - IterableClass -> IterableForwarder, - SeqClass -> SeqForwarder, - TraversableLike -> TraversableProxy, - IterableLike -> IterableProxy, - MapLike -> MapProxy, - SetLike -> SetProxy, - SeqLike -> SeqProxy - ) - - def generate(dir: io.Directory) = { - /** A proxy for a type (identified by field `underlying`) that forwards most - * operations to it (for exceptions, see WrappingProxy, which forwards even more operations). - * every operation that is overridden for some kind of types should be forwarded. - */ - for ((clazz, proxy) <- wrappers) { - val text = wrapReport(clazz, proxy) - val file = dir / (proxy.fullName + ".scala") toFile; - - file writeAll text - println("Created " + file) - } - } -} - -object ProxyReportRunner { - class ProxyGlobal(s: Settings) extends Global(s) { - object proxyReport extends { - val global: ProxyGlobal.this.type = ProxyGlobal.this - } with util.ProxyReport - } - - def main(args: Array[String]): Unit = { - if (args.isEmpty) - return println("Give an output directory as argument.") - - val dir = io.Directory(args(0)).createDirectory() - val s = new Settings() - s.processArguments(args.toList.tail, true) - val g = new ProxyGlobal(s) - val run = new g.Run() - g.afterTyper(g.proxyReport.generate(dir)) - } -} diff --git a/src/compiler/scala/tools/nsc/util/RegexCache.scala b/src/compiler/scala/tools/nsc/util/RegexCache.scala deleted file mode 100644 index 896c1a536f..0000000000 --- a/src/compiler/scala/tools/nsc/util/RegexCache.scala +++ /dev/null @@ -1,40 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Lex Spoon - */ - -package scala.tools.nsc -package util -import java.util.regex.Pattern -import scala.collection.mutable - -object RegexCache { - /** Maps patterns to compiled regexes */ - private val regexMap = mutable.Map.empty[String, Pattern] - - /** Lists the regexes that have been recorded in order */ - private val regexList = new mutable.Queue[String] - - private val regexesToCache = 1000 - - /** Compile a regex and add it to the cache */ - private def compileAndAdd(regex: String): Pattern = { - val pattern = Pattern.compile(regex) - - regexMap += (regex -> pattern) - regexList += regex - - if (regexMap.size > regexesToCache) - regexMap -= regexList.dequeue() - - pattern - } - - - /** Compile a regex, caching */ - def apply(regex: String): Pattern = - regexMap.get(regex) match { - case Some(pattern) => pattern - case None => compileAndAdd(regex) - } -} diff --git a/src/compiler/scala/tools/nsc/util/ScalaClassLoader.scala b/src/compiler/scala/tools/nsc/util/ScalaClassLoader.scala index 120cceb238..47f759830e 100644 --- a/src/compiler/scala/tools/nsc/util/ScalaClassLoader.scala +++ b/src/compiler/scala/tools/nsc/util/ScalaClassLoader.scala @@ -16,8 +16,6 @@ import ScalaClassLoader._ import scala.util.control.Exception.{ catching } import language.implicitConversions -// import Exceptional.unwrap - trait HasClassPath { def classPathURLs: Seq[URL] } diff --git a/src/compiler/scala/tools/nsc/util/ScalaPrefs.scala b/src/compiler/scala/tools/nsc/util/ScalaPrefs.scala deleted file mode 100644 index 03e0f54606..0000000000 --- a/src/compiler/scala/tools/nsc/util/ScalaPrefs.scala +++ /dev/null @@ -1,25 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.nsc -package util - -import io.Sources - -trait ScalaPrefs { - def codeSources: Sources - def exceptionFormatter: Exceptional.Formatter -} - -trait LowPriorityScalaPrefs { - implicit object DefaultScalaPrefs extends ScalaPrefs { - def codeSources = Sources.defaultSources - def exceptionFormatter = Exceptional.Formatter(this) - } -} - -object ScalaPrefs extends LowPriorityScalaPrefs { - def apply(implicit prefs: ScalaPrefs): ScalaPrefs = prefs -} diff --git a/src/compiler/scala/tools/nsc/util/ShowPickled.scala b/src/compiler/scala/tools/nsc/util/ShowPickled.scala index fc39a218f8..53ed96d0d3 100644 --- a/src/compiler/scala/tools/nsc/util/ShowPickled.scala +++ b/src/compiler/scala/tools/nsc/util/ShowPickled.scala @@ -11,8 +11,6 @@ import java.io.{File, FileInputStream, PrintStream} import java.lang.Long.toHexString import java.lang.Float.intBitsToFloat import java.lang.Double.longBitsToDouble - -import cmd.program.Simple import scala.reflect.internal.{Flags, Names} import scala.reflect.internal.pickling.{ PickleBuffer, PickleFormat } import interpreter.ByteCode.scalaSigBytesForPath @@ -119,21 +117,18 @@ object ShowPickled extends Names { result.toInt } - def printFile(buf: PickleBuffer, out: PrintStream): Unit = printFile(buf, out, false) - def printFile(buf: PickleBuffer, out: PrintStream, bare: Boolean) { + def printFile(buf: PickleBuffer, out: PrintStream) { out.println("Version " + buf.readNat() + "." + buf.readNat()) val index = buf.createIndex val entryList = makeEntryList(buf, index) buf.readIndex = 0 - /** A print wrapper which discards everything if bare is true. - */ - def p(s: String) = if (!bare) out print s + def p(s: String) = out print s def printNameRef() { val idx = buf.readNat() val name = entryList nameAt idx - val toPrint = if (bare) " " + name else " %s(%s)".format(idx, name) + val toPrint = " %s(%s)".format(idx, name) out print toPrint } @@ -156,7 +151,7 @@ object ShowPickled extends Names { val accessBoundary = ( for (idx <- privateWithin) yield { val s = entryList nameAt idx - if (bare) s else idx + "(" + s + ")" + idx + "(" + s + ")" } ) val flagString = { @@ -283,31 +278,18 @@ object ShowPickled extends Names { try Some(new PickleBuffer(data, 0, data.length)) catch { case _: Exception => None } - def show(what: String, pickle: PickleBuffer, bare: Boolean) = { + def show(what: String, pickle: PickleBuffer) = { Console.println(what) val saved = pickle.readIndex pickle.readIndex = 0 - printFile(pickle, Console.out, bare) + printFile(pickle, Console.out) pickle.readIndex = saved } - private lazy val ShowPickledSpec = - Simple( - Simple.scalaProgramInfo("showPickled", "Usage: showPickled [--bare] <classname>"), - List("--bare" -> "suppress numbers in output"), - Nil, - null - ) - - /** Option --bare suppresses numbers so the output can be diffed. - */ def main(args: Array[String]) { - val runner = ShowPickledSpec instance args - import runner._ - - residualArgs foreach { arg => + args foreach { arg => (fromFile(arg) orElse fromName(arg)) match { - case Some(pb) => show(arg + ":", pb, parsed isSet "--bare") + case Some(pb) => show(arg + ":", pb) case _ => Console.println("Cannot read " + arg) } } diff --git a/src/compiler/scala/tools/nsc/util/Tracer.scala b/src/compiler/scala/tools/nsc/util/Tracer.scala deleted file mode 100644 index acbf60da5b..0000000000 --- a/src/compiler/scala/tools/nsc/util/Tracer.scala +++ /dev/null @@ -1,73 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.nsc -package util - -import java.io.PrintStream -import scala.runtime.ScalaRunTime - -class Tracer(enabled: () => Boolean) { - def out: PrintStream = System.out - def stringify(x: Any) = ScalaRunTime stringOf x - - // So can pass tuples, lists, whatever as arguments and don't - // get a lot of extra parens or noisy prefixes. - def stringifyArgs(x: Any) = { - x match { - case x: TraversableOnce[_] => x map stringify mkString ", " - case x: Product => x.productIterator map stringify mkString ", " - case _ => stringify(x) - } - } - - private val LBRACE = "{" - private val RBRACE = "}" - private var indentLevel = 0 - private def spaces = " " * (indentLevel * 2) - private def pblock(result: Any) = { - p(LBRACE + "\n") - indented(p(spaces + stringify(result) + "\n")) - p(spaces + RBRACE + "\n") - } - private def passign(name: String, args: String) = - p(spaces + name + "(" + args + ") = ") - - private def indented[T](body: => T): T = { - indentLevel += 1 - try body - finally indentLevel -= 1 - } - private def p(s: String) = { - out.print(s) - out.flush() - } - - def apply[T](name: String, args: => Any)(body: => T): T = { - val result = body - - if (enabled()) { - passign(name, stringifyArgs(args)) - val resultToPrint = result match { - case Some(x) => x - case _ => result - } - // concise output optimization - val isOneliner = resultToPrint match { - case _: Boolean | _: None.type => true - case s: String => s.length < 40 - case _ => false - } - if (isOneliner) p(stringify(resultToPrint) + "\n") - else pblock(resultToPrint) - } - - result - } -} - -object Tracer { - def apply(enabled: => Boolean): Tracer = new Tracer(() => enabled) -} diff --git a/src/compiler/scala/tools/reflect/Invoked.scala b/src/compiler/scala/tools/reflect/Invoked.scala deleted file mode 100644 index 516c6b9bf6..0000000000 --- a/src/compiler/scala/tools/reflect/Invoked.scala +++ /dev/null @@ -1,52 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools -package reflect - -import java.lang.reflect.{ Method, Proxy } - -/** A class representing a single method call. It is primarily for use - * in tandem with Mock. If the invocation did not target an InvocationHandler, - * proxy will be null. - */ -class Invoked private (val proxy: AnyRef, val m: Method, val args: List[AnyRef]) { - def name = m.getName - def arity = m.getParameterTypes.size - def returnType = m.getReturnType - def returns[T: ClassTag] = returnType == classTag[T].erasure - - def invokeOn(target: AnyRef) = m.invoke(target, args: _*) - def isObjectMethod = Set("toString", "equals", "hashCode") contains name - - override def toString = "Invoked: %s called with %s".format( - m.getName, - if (args.isEmpty) "no args" else "args '%s'".format(args mkString ", ") - ) -} - -object Invoked { - def apply(m: Method, args: Seq[Any]): Invoked = apply(null, m, args) - def apply(proxy: AnyRef, m: Method, args: Seq[Any]): Invoked = { - val fixedArgs = if (args == null) Nil else args.toList map (_.asInstanceOf[AnyRef]) - new Invoked(proxy, m, fixedArgs) - } - def unapply(x: Any) = x match { - case x: Invoked => Some((x.proxy, x.m, x.args)) - case _ => None - } - object NameAndArgs { - def unapply(x: Any) = x match { - case x: Invoked => Some((x.name, x.args)) - case _ => None - } - } - object NameAndArity { - def unapply(x: Any) = x match { - case x: Invoked => Some((x.name, x.arity)) - case _ => None - } - } -} diff --git a/src/compiler/scala/tools/reflect/Mock.scala b/src/compiler/scala/tools/reflect/Mock.scala deleted file mode 100644 index 52c052b8a2..0000000000 --- a/src/compiler/scala/tools/reflect/Mock.scala +++ /dev/null @@ -1,60 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools -package reflect - -import java.lang.reflect.{ Method, Proxy, InvocationHandler } - -/** A wrapper around java dynamic proxies to make it easy to pose - * as an interface. See SignalManager for an example usage. - */ -trait Mock extends (Invoked => AnyRef) { - mock => - - def interfaces: List[Class[_]] - def classLoader: ClassLoader - def apply(invoked: Invoked): AnyRef - - def newProxyInstance(handler: InvocationHandler): AnyRef = - Proxy.newProxyInstance(classLoader, interfaces.toArray, handler) - def newProxyInstance(): AnyRef = - newProxyInstance(newInvocationHandler()) - - def newInvocationHandler() = new InvocationHandler { - def invoke(proxy: AnyRef, method: Method, args: Array[AnyRef]) = - try { mock(Invoked(proxy, method, args)) } - catch { case _: NoClassDefFoundError => sys.exit(1) } - } -} - -/** The methods in Mock create the actual proxy instance which can be used - * in place of the associated interface(s). - */ -object Mock { - /** The default implementation calls the partial function if defined, and - * routes Object methods to the proxy: otherwise it throws an exception. - */ - def fromInterfaces(clazz: Class[_], clazzes: Class[_]*)(pf: PartialFunction[Invoked, AnyRef]): AnyRef = { - val ints = clazz :: clazzes.toList - require(ints forall (_.isInterface), "All class objects must represent interfaces") - - val mock = new Mock { - val interfaces = ints - def classLoader = clazz.getClassLoader - def apply(invoked: Invoked) = - if (pf.isDefinedAt(invoked)) pf(invoked) - else if (invoked.isObjectMethod) invoked invokeOn this - else throw new NoSuchMethodException("" + invoked) - } - mock.newProxyInstance() - } - /** Tries to implement all the class's interfaces. - */ - def fromClass(clazz: Class[_])(pf: PartialFunction[Invoked, AnyRef]): AnyRef = allInterfaces(clazz) match { - case Nil => sys.error(clazz + " implements no interfaces.") - case x :: xs => fromInterfaces(x, xs: _*)(pf) - } -} diff --git a/src/compiler/scala/tools/reflect/Shield.scala b/src/compiler/scala/tools/reflect/Shield.scala deleted file mode 100644 index f9c7e54454..0000000000 --- a/src/compiler/scala/tools/reflect/Shield.scala +++ /dev/null @@ -1,44 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools -package reflect - -import java.lang.reflect.Constructor -import nsc.util.ScalaClassLoader - -/** A support class for simplifying the otherwise disbelief-inspiring - * process of working with classes completely reflectively. This is - * the case with e.g. sun.misc.Signal* due to environments which are - * antagonistic to their use. See SignalManager for an example. - * - * The name "Shield" is a reference to shielding the JVM from knowledge - * of what we're doing. - */ -trait Shield { - def className: String - def classLoader: ScalaClassLoader - - // Override this if you are more ambitious about logging or throwing. - def onError[T >: Null](msg: String): T = null - - /** This is handy because all reflective calls want back an AnyRef but - * we will often be generating Units. - */ - protected implicit def boxedUnit(x: Unit): AnyRef = scala.runtime.BoxedUnit.UNIT - - lazy val clazz: Class[_] = classLoader.tryToLoadClass(className) getOrElse onError("Failed to load " + className) - lazy val methods = clazz.getMethods.toList - - def constructor(paramTypes: Class[_]*) = clazz.getConstructor(paramTypes: _*).asInstanceOf[Constructor[AnyRef]] - def method(name: String, arity: Int) = uniqueMethod(name, arity) - def field(name: String) = clazz getField name - - def matchingMethods(name: String, arity: Int) = methods filter (m => nameAndArity(m) == ((name, arity))) - def uniqueMethod(name: String, arity: Int) = matchingMethods(name, arity) match { - case List(x) => x - case _ => onError("No unique match for " + name) - } -} diff --git a/src/compiler/scala/tools/reflect/SigParser.scala b/src/compiler/scala/tools/reflect/SigParser.scala deleted file mode 100644 index 5d85778570..0000000000 --- a/src/compiler/scala/tools/reflect/SigParser.scala +++ /dev/null @@ -1,42 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools -package reflect - -import java.lang.reflect.{ GenericSignatureFormatError, Method } - -/** The usual reflection song and dance to avoid referencing - * any sun.* classes. - */ -class SigParser { - val SunSignatureParser = "sun.reflect.generics.parser.SignatureParser" - private lazy val makeMethod: Method = - try Class.forName(SunSignatureParser) getMethod "make" - catch { case t => null } - - def make() = makeMethod.invoke(null).asInstanceOf[SignatureParserInterface] - - private def wrap(op: => Any) = - try { op ; true } - catch { case _: GenericSignatureFormatError => false } - - def isParserAvailable = makeMethod != null - def verifyClass(s: String) = isParserAvailable && wrap(make() parseClassSig s) - def verifyMethod(s: String) = isParserAvailable && wrap(make() parseMethodSig s) - def verifyType(s: String) = isParserAvailable && wrap(make() parseTypeSig s) - - type ClassSignature <: AnyRef - type MethodTypeSignature <: AnyRef - type TypeSignature <: AnyRef - - type SignatureParserInterface = { - def isParserAvailable: Boolean - def parseClassSig(s: String): ClassSignature - def parseMethodSig(s: String): MethodTypeSignature - def parseTypeSig(s: String): TypeSignature - } -} -object SigParser extends SigParser { } diff --git a/src/compiler/scala/tools/reflect/UniversalFn.scala b/src/compiler/scala/tools/reflect/UniversalFn.scala deleted file mode 100644 index b0c2a19021..0000000000 --- a/src/compiler/scala/tools/reflect/UniversalFn.scala +++ /dev/null @@ -1,59 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools -package reflect - -import java.lang.reflect.{ Method, InvocationTargetException } -import java.{ lang => jl } - -/** For certain reflection tasks it is convenient to treat all methods - * as having the same signature: (Seq[AnyRef]) => AnyRef - * - * That is the "universal signature" and UniversalFn exists to provide - * it without abandoning the information we had before we needed it. - * One place this is used: closures can pose as arbitrary interfaces, - * and this is how we route the arguments from the actual method - * invocation (which targets a proxy object) to the original closure. - */ -class UniversalFn private (val closure: AnyRef, val method: Method) extends (Seq[AnyRef] => AnyRef) { - universal => - - /** Given an interface type argument, creates a proxy object of the - * type of the interface which implements all its methods by routing - * them to this universal function. Will throw an exception in the - * face of any bad data. - */ - def as[T: ClassTag] : T = { - val clazz = classTag[T].erasure - require(clazz.isInterface, "Type argument must be an interface.") - - val interfaceMethods = clazz.getDeclaredMethods.toSet - val proxy = Mock.fromInterfaces(clazz) { - case Invoked(_, m, args) if interfaceMethods(m) => universal(args) - } - proxy.asInstanceOf[T] - } - - def apply(xs: Seq[AnyRef]): AnyRef = - try method.invoke(closure, xs: _*) - catch { case x: InvocationTargetException => throw x.getCause() } -} - -object UniversalFn { - /** We use a private constructor so we can enforce some rules: we don't want - * universal functions to stack up, and right now we will only allow objects - * which appear to be closures (there's no reason not to eventually lift - * this restriction, but it should be harder to shoot your foot first.) - */ - def apply(closure: AnyRef): UniversalFn = closure match { - case x: UniversalFn => x - case _ => - val m = uniqueApply(closure) getOrElse { - throw new IllegalArgumentException("Argument must have exactly one non-bridge apply method.") - } - new UniversalFn(closure, m) - } -} diff --git a/src/compiler/scala/tools/reflect/package.scala b/src/compiler/scala/tools/reflect/package.scala deleted file mode 100644 index 0b0c0905cb..0000000000 --- a/src/compiler/scala/tools/reflect/package.scala +++ /dev/null @@ -1,43 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools - -import java.lang.reflect.Method -import java.{ lang => jl } - -package object reflect { - def nameAndArity(m: Method) = (m.getName, m.getParameterTypes.size) - def allInterfaces(cl: Class[_]): List[Class[_]] = - if (cl == null) Nil - else cl.getInterfaces.toList ++ allInterfaces(cl.getSuperclass) distinct - - def methodsNamed(target: AnyRef, name: String): List[Method] = - target.getClass.getMethods filter (x => x.getName == name) toList - - /** If there is a single non-bridge apply method in the given instance, - * return it: otherwise None. - */ - def uniqueApply(target: AnyRef) = { - methodsNamed(target, "apply") filterNot (_.isBridge) match { - case List(x) => Some(x) - case _ => None - } - } - - def zeroOfClass(clazz: Class[_]) = zeroOf(ClassTag(clazz)) - def zeroOf[T](implicit t: ClassTag[T]): AnyRef = { - if (t == classTag[Boolean] || t == classTag[jl.Boolean]) false: jl.Boolean - else if (t == classTag[Unit] || t == classTag[jl.Void] || t == classTag[scala.runtime.BoxedUnit]) scala.runtime.BoxedUnit.UNIT - else if (t == classTag[Char] || t == classTag[jl.Character]) 0.toChar: jl.Character - else if (t == classTag[Byte] || t == classTag[jl.Byte]) 0.toByte: jl.Byte - else if (t == classTag[Short] || t == classTag[jl.Short]) 0.toShort: jl.Short - else if (t == classTag[Int] || t == classTag[jl.Integer]) 0: jl.Integer - else if (t == classTag[Long] || t == classTag[jl.Long]) 0l: jl.Long - else if (t == classTag[Float] || t == classTag[jl.Float]) 0f: jl.Float - else if (t == classTag[Double] || t == classTag[jl.Double]) 0d: jl.Double - else null - } -} diff --git a/src/compiler/scala/tools/util/AbstractTimer.scala b/src/compiler/scala/tools/util/AbstractTimer.scala deleted file mode 100644 index 210a1ee53c..0000000000 --- a/src/compiler/scala/tools/util/AbstractTimer.scala +++ /dev/null @@ -1,53 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2011, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - - -package scala.tools.util - -import compat.Platform.currentTime -import scala.collection.mutable - -/** - * This abstract class implements the collection of timings. How the - * collected timings are issued has to be implemented in subclasses. - * - * @author Philippe Altherr - * @version 1.0 - */ -abstract class AbstractTimer { - - //######################################################################## - // Private Fields - - /** A stack for maintaining start times */ - private val starts = new mutable.Stack[Long]() - - //######################################################################## - // Public Methods - - /** Issues a timing information (duration in milliseconds). */ - def issue(message: String, duration: Long): Unit - - /** Starts a new timer. */ - def start() { - starts push currentTime - } - - /** Ends the current timer. */ - def stop(message: String) { - val stop = currentTime - issue(message, stop - starts.pop) - } - - /** Drops the current timer. */ - def drop() { - starts.pop - } - - //######################################################################## -} diff --git a/src/compiler/scala/tools/util/ClassPathSettings.scala b/src/compiler/scala/tools/util/ClassPathSettings.scala deleted file mode 100644 index d202279ea1..0000000000 --- a/src/compiler/scala/tools/util/ClassPathSettings.scala +++ /dev/null @@ -1,32 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2006-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools -package util - -trait ClassPathSettings { - def javabootclasspath: String // -javabootclasspath - def javaextdirs: String // -javaextdirs - def bootclasspath: String // -bootclasspath - def extdirs: String // -extdirs - def classpath: String // -classpath - def sourcepath: String // -sourcepath -} - -// val debugLogger = { -// val f = File("/tmp/path-resolve-log.txt") -// if (f.exists) f.truncate() -// else f.createFile() -// -// val res = f.bufferedWriter() -// res write ("Started debug log: %s\n".format(new java.util.Date)) -// res -// } -// def log(msg: Any) = { -// Console println msg -// debugLogger.write(msg.toString + "\n") -// debugLogger flush -// } - diff --git a/src/compiler/scala/tools/util/EditDistance.scala b/src/compiler/scala/tools/util/EditDistance.scala deleted file mode 100644 index 0af34020a8..0000000000 --- a/src/compiler/scala/tools/util/EditDistance.scala +++ /dev/null @@ -1,70 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools -package util - -object EditDistance { - import java.lang.Character.{ toLowerCase => lower } - - def similarString(name: String, allowed: TraversableOnce[String]): String = { - val suggested = suggestions(name, allowed.toSeq, maxDistance = 1, maxSuggestions = 2) - if (suggested.isEmpty) "" - else suggested.mkString(" (similar: ", ", ", ")") - } - - def suggestions(a: String, bs: Seq[String], maxDistance: Int, maxSuggestions: Int): Seq[String] = ( - bs map (b => (b, distance(a, b))) - filter (_._2 <= maxDistance) - sortBy (_._2) - take (maxSuggestions) - map (_._1) - ) - - def distance(a: String, b: String): Int = levenshtein(a, b, transpositions = true) - - def levenshtein(s: String, t: String, transpositions: Boolean): Int = { - val n = s.length - val m = t.length - if (n == 0) return m - if (m == 0) return n - - val d = Array.ofDim[Int](n + 1, m + 1) - var i = 0 - val max = math.max(m, n) - while (i <= max) { - if (i <= n) - d(i)(0) = i - if (i <= m) - d(0)(i) = i - i += 1 - } - i = 1 - - while (i <= n) { - val s_i = s(i - 1) - var j = 1 - while (j <= m) { - val t_j = t(j - 1) - val cost = if (lower(s_i) == lower(t_j)) 0 else 1 - - val c1 = d(i - 1)(j) + 1 - val c2 = d(i)(j - 1) + 1 - val c3 = d(i - 1)(j - 1) + cost - - d(i)(j) = c1 min c2 min c3 - - if (transpositions) { - if (i > 1 && j > 1 && s(i - 1) == t(j - 2) && s(i - 2) == t(j - 1)) - d(i)(j) = d(i)(j) min (d(i - 2)(j - 2) + cost) - } - j += 1 - } - i += 1 - } - - d(n)(m) - } -} diff --git a/src/compiler/scala/tools/util/Javap.scala b/src/compiler/scala/tools/util/Javap.scala index 6d5988d1dd..42d8a910f0 100644 --- a/src/compiler/scala/tools/util/Javap.scala +++ b/src/compiler/scala/tools/util/Javap.scala @@ -10,7 +10,7 @@ import java.lang.reflect.{ GenericSignatureFormatError, Method, Constructor } import java.lang.{ ClassLoader => JavaClassLoader } import scala.tools.nsc.util.ScalaClassLoader import java.io.{ InputStream, PrintWriter, ByteArrayInputStream, FileNotFoundException } -import scala.tools.nsc.io.{ File, NullPrintStream } +import scala.tools.nsc.io.File import Javap._ trait Javap { diff --git a/src/compiler/scala/tools/util/Profiling.scala b/src/compiler/scala/tools/util/Profiling.scala deleted file mode 100644 index 44393eef20..0000000000 --- a/src/compiler/scala/tools/util/Profiling.scala +++ /dev/null @@ -1,52 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools -package util - -/** This is a (very) minimal stub for profiling, the purpose - * of which is making it possible to integrate profiling hooks in - * the compiler without creating a dependency on any particular - * profiler. You can specify a profiler class (which must be an - * instance of this class) like so: - * - * // or -Yprofile:phase to profile individual phases - * scalac -Yprofile-class your.profiler.Class -Yprofile:all <files> - * - */ -abstract class Profiling { - def isActive: Boolean - def startProfiling(): Unit - def stopProfiling(): Unit - def captureSnapshot(): Unit - - def allocationFreq: Option[Int] // record every Nth allocation - def startRecordingAllocations(): Unit - def stopRecordingAllocations(): Unit - - def profile[T](body: => T): T = profileCPU(body) - - def profileCPU[T](body: => T): T = { - startProfiling() - val result = body - stopProfiling() - captureSnapshot() - result - } - - def profileMem[T](body: => T): T = { - startRecordingAllocations() - val result = body - stopRecordingAllocations() - result - } - - /** Advance the current object generation. - * - * Each object on the heap is associated to a generation number. Generations - * start at 1, and are automatically advanced on each snapshot capture. - */ - def advanceGeneration(desc: String = ""): Unit -} diff --git a/src/compiler/scala/tools/util/SignalManager.scala b/src/compiler/scala/tools/util/SignalManager.scala deleted file mode 100644 index e93297386a..0000000000 --- a/src/compiler/scala/tools/util/SignalManager.scala +++ /dev/null @@ -1,275 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools -package util - -import java.lang.reflect.{ Method, Constructor } -import scala.tools.reflect._ -import scala.collection.{ mutable, immutable } -import nsc.io.timer -import nsc.util.{ ScalaClassLoader, Exceptional } -import Exceptional.unwrap -import scala.util.Random - -/** Signal handling code. 100% clean of any references to sun.misc: - * it's all reflection and proxies and invocation handlers and lasers, - * so even the choosiest runtimes will be cool with it. - * - * Sun/Oracle says sun.misc.* is unsupported and therefore so is all - * of this. Simple examples: - * {{{ - val manager = scala.tools.util.SignalManager // or you could make your own - // Assignment clears any old handlers; += chains them. - manager("HUP") = println("HUP 1!") - manager("HUP") += println("HUP 2!") - // Use raise() to raise a signal: this will print both lines - manager("HUP").raise() - // See a report on every signal's current handler - manager.dump() - * }}} - */ -class SignalManager(classLoader: ScalaClassLoader) { - def this() = this(ScalaClassLoader.appLoader) - private val illegalArgHandler: PartialFunction[Throwable, Boolean] = { - case x if unwrap(x).isInstanceOf[IllegalArgumentException] => false - } - private def fail(msg: String) = new SignalError(msg) - - object rSignalHandler extends Shield { - val className = "sun.misc.SignalHandler" - val classLoader = SignalManager.this.classLoader - - lazy val SIG_DFL = field("SIG_DFL") get null - lazy val SIG_IGN = field("SIG_IGN") get null - - /** Create a new signal handler based on the function. - */ - def apply(action: Invoked => Unit) = Mock.fromInterfaces(clazz) { - case inv @ Invoked.NameAndArgs("handle", _ :: Nil) => action(inv) - } - def empty = rSignalHandler(_ => ()) - } - import rSignalHandler.{ SIG_DFL, SIG_IGN } - - object rSignal extends Shield { - val className = "sun.misc.Signal" - val classLoader = SignalManager.this.classLoader - - lazy val handleMethod = method("handle", 2) - lazy val raiseMethod = method("raise", 1) - lazy val numberMethod = method("getNumber", 0) - - /** Create a new Signal with the given name. - */ - def apply(name: String) = constructor(classOf[String]) newInstance name - def handle(signal: AnyRef, current: AnyRef) = { - if (signal == null || current == null) fail("Signals cannot be null") - else handleMethod.invoke(null, signal, current) - } - def raise(signal: AnyRef) = { - if (signal == null) fail("Signals cannot be null") - else raiseMethod.invoke(null, signal) - } - def number(signal: AnyRef): Int = numberMethod.invoke(signal).asInstanceOf[Int] - - class WSignal(val name: String) { - lazy val signal = rSignal apply name - def number = rSignal number signal - def raise() = rSignal raise signal - def handle(handler: AnyRef) = rSignal.handle(signal, handler) - - def isError = false - def setTo(body: => Unit) = register(name, false, body) - def +=(body: => Unit) = register(name, true, body) - - /** It's hard to believe there's no way to get a signal's current - * handler without replacing it, but if there is I couldn't find - * it, so we have this swapping code. - */ - def withCurrentHandler[T](f: AnyRef => T): T = { - val swap = handle(rSignalHandler.empty) - - try f(swap) - finally handle(swap) - } - def isDefault = try withCurrentHandler { - case SIG_DFL => true - case _ => false - } catch illegalArgHandler - def isIgnored = try withCurrentHandler { - case SIG_IGN => true - case _ => false - } catch illegalArgHandler - def isSetTo(ref: AnyRef) = - try withCurrentHandler { _ eq ref } - catch illegalArgHandler - - def handlerString() = withCurrentHandler { - case SIG_DFL => "Default" - case SIG_IGN => "Ignore" - case x => "" + x - } - - override def toString = "%10s %s".format("SIG" + name, - try handlerString() - catch { case x: Exception => "VM threw " + unwrap(x) } - ) - override def equals(other: Any) = other match { - case x: WSignal => name == x.name - case _ => false - } - override def hashCode = name.## - } - } - type WSignal = rSignal.WSignal - - /** Adds a handler for the named signal. If shouldChain is true, - * the installed handler will call the previous handler after the - * new one has executed. If false, the old handler is dropped. - */ - private def register(name: String, shouldChain: Boolean, body: => Unit) = { - val signal = rSignal(name) - val current = rSignalHandler(_ => body) - val prev = rSignal.handle(signal, current) - - if (shouldChain) { - val chainer = rSignalHandler { inv => - val signal = inv.args.head - - inv invokeOn current - prev match { - case SIG_IGN | SIG_DFL => () - case _ => inv invokeOn prev - } - } - rSignal.handle(signal, chainer) - chainer - } - else current - } - - /** Use apply and update to get and set handlers. - */ - def apply(name: String): WSignal = - try { new WSignal(name) } - catch { case x: IllegalArgumentException => new SignalError(x.getMessage) } - - def update(name: String, body: => Unit): Unit = apply(name) setTo body - - class SignalError(message: String) extends WSignal("") { - override def isError = true - override def toString = message - } - - def public(name: String, description: String)(body: => Unit): Unit = { - try { - val wsig = apply(name) - if (wsig.isError) - return - - wsig setTo body - registerInfoHandler() - addPublicHandler(wsig, description) - } - catch { - case x: Exception => () // ignore failure - } - } - /** Makes sure the info handler is registered if we see activity. */ - private def registerInfoHandler() = { - val INFO = apply("INFO") - if (publicHandlers.isEmpty && INFO.isDefault) { - INFO setTo Console.println(info()) - addPublicHandler(INFO, "Print signal handler registry on console.") - } - } - private def addPublicHandler(wsig: WSignal, description: String) = { - if (publicHandlers contains wsig) () - else publicHandlers = publicHandlers.updated(wsig, description) - } - private var publicHandlers: Map[WSignal, String] = Map() - def info(): String = { - registerInfoHandler() - val xs = publicHandlers.toList sortBy (_._1.name) map { - case (wsig, descr) => " %2d %5s %s".format(wsig.number, wsig.name, descr) - } - - xs.mkString("\nSignal handler registry:\n", "\n", "") - } -} - -object SignalManager extends SignalManager { - private implicit def mkWSignal(name: String): WSignal = this(name) - private lazy val signalNumberMap = all map (x => x.number -> x) toMap - - def all = List( - HUP, INT, QUIT, ILL, TRAP, ABRT, EMT, FPE, // 1-8 - KILL, BUS, SEGV, SYS, PIPE, ALRM, TERM, URG, // 9-15 - STOP, TSTP, CONT, CHLD, TTIN, TTOU, IO, XCPU, // 16-23 - XFSZ, VTALRM, PROF, WINCH, INFO, USR1, USR2 // 24-31 - ) - /** Signals which are either inaccessible or which seem like - * particularly bad choices when looking for an open one. - */ - def reserved = Set(QUIT, TRAP, ABRT, KILL, BUS, SEGV, ALRM, STOP, INT) - def unreserved = all filterNot reserved - def defaultSignals() = unreserved filter (_.isDefault) - def ignoredSignals() = unreserved filter (_.isIgnored) - def findOpenSignal() = Random.shuffle(defaultSignals()).head - - def dump() = all foreach (x => println("%2s %s".format(x.number, x))) - - def apply(sigNumber: Int): WSignal = signalNumberMap(sigNumber) - - def HUP: WSignal = "HUP" - def INT: WSignal = "INT" - def QUIT: WSignal = "QUIT" - def ILL: WSignal = "ILL" - def TRAP: WSignal = "TRAP" - def ABRT: WSignal = "ABRT" - def EMT: WSignal = "EMT" - def FPE: WSignal = "FPE" - def KILL: WSignal = "KILL" - def BUS: WSignal = "BUS" - def SEGV: WSignal = "SEGV" - def SYS: WSignal = "SYS" - def PIPE: WSignal = "PIPE" - def ALRM: WSignal = "ALRM" - def TERM: WSignal = "TERM" - def URG: WSignal = "URG" - def STOP: WSignal = "STOP" - def TSTP: WSignal = "TSTP" - def CONT: WSignal = "CONT" - def CHLD: WSignal = "CHLD" - def TTIN: WSignal = "TTIN" - def TTOU: WSignal = "TTOU" - def IO: WSignal = "IO" - def XCPU: WSignal = "XCPU" - def XFSZ: WSignal = "XFSZ" - def VTALRM: WSignal = "VTALRM" - def PROF: WSignal = "PROF" - def WINCH: WSignal = "WINCH" - def INFO: WSignal = "INFO" - def USR1: WSignal = "USR1" - def USR2: WSignal = "USR2" - - /** Given a number of seconds, a signal, and a function: sets up a handler which upon - * receiving the signal once, calls the function with argument true, and if the - * signal is received again within the allowed time, calls it with argument false. - * (Otherwise it calls it with true and starts the timer over again.) - */ - def requireInterval(seconds: Int, wrapper: WSignal)(fn: Boolean => Unit) = { - var received = false - wrapper setTo { - if (received) fn(false) - else { - received = true - fn(true) - timer(seconds)(received = false) - } - } - } -} diff --git a/src/compiler/scala/tools/util/Signallable.scala b/src/compiler/scala/tools/util/Signallable.scala deleted file mode 100644 index af98bfac83..0000000000 --- a/src/compiler/scala/tools/util/Signallable.scala +++ /dev/null @@ -1,65 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools -package util - -import java.security.AccessControlException - -/** A class for things which are signallable. - */ -abstract class Signallable[T] private (val signal: String, val description: String) { - private var last: Option[T] = None - private def lastString = last match { - case Some(()) => "" - case Some(x) => "" + x - case _ => "" - } - - /** The most recent result from the signal handler. */ - def lastResult: Option[T] = last - - /** Method to be executed when the associated signal is received. */ - def onSignal(): T - - // todo: - // def unregister(): Boolean - - override def toString = " SIG(%s) => %s%s".format( - signal, description, if (lastString == "") "" else " (" + lastString + ")" - ) -} - -object Signallable { - /** Same as the other apply, but an open signal is found for you. - */ - def apply[T](description: String)(body: => T): Signallable[T] = wrap { - apply(SignalManager.findOpenSignal().name, description)(body) - } - - /** Given a signal name, a description, and a handler body, this - * registers a signal handler and returns the Signallable instance. - * The signal handler registry is thereafter available by calling - * SignalManager.info(), or sending SIGINFO to the manager will - * dump it to console. - */ - def apply[T](signal: String, description: String)(body: => T): Signallable[T] = wrap { - val result = create[T](signal, description, body) - SignalManager.public(signal, description)(result.onSignal()) - result - } - - private def wrap[T](body: => Signallable[T]): Signallable[T] = - try body catch { case _: AccessControlException => null } - - private def create[T](signal: String, description: String, body: => T): Signallable[T] = - new Signallable[T](signal, description) { - def onSignal = { - val result = body - last = Some(result) - result - } - } -} diff --git a/src/compiler/scala/tools/util/SocketConnection.scala b/src/compiler/scala/tools/util/SocketConnection.scala deleted file mode 100644 index 6b56be569c..0000000000 --- a/src/compiler/scala/tools/util/SocketConnection.scala +++ /dev/null @@ -1,52 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2002-2011, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - - -package scala.tools.util - -import java.io.{PrintWriter, InputStreamReader, BufferedReader} -import java.io.IOException -import java.net.{Socket, InetAddress} -import java.net.UnknownHostException - -/** This class implements the connection to the server. - * - * @author Martin Odersky - * @version 1.0 - */ -class SocketConnection(hostname: String, port: Int) { - - def this(port: Int) = this(InetAddress.getLocalHost().getHostName(), port) - - private var socket: Socket = _ - var out: PrintWriter = _ - var in: BufferedReader = _ - var errorMessage: String = _ - - def open(): Boolean = { - try { - socket = new Socket(hostname, port) - out = new PrintWriter(socket.getOutputStream(), true) - in = new BufferedReader(new InputStreamReader(socket.getInputStream())) - true - } catch { - case e: UnknownHostException => - errorMessage = "Don't know about host: " + hostname + "." - false - case e: IOException => - errorMessage = "Couldn't get I/O for the connection to: " + hostname + "." - false - } - } - - def close() { - in.close() - out.close() - socket.close() - } -} diff --git a/src/compiler/scala/tools/util/Which.scala b/src/compiler/scala/tools/util/Which.scala deleted file mode 100644 index 1cafe156b5..0000000000 --- a/src/compiler/scala/tools/util/Which.scala +++ /dev/null @@ -1,38 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools -package util - -import scala.tools.nsc._ - -/** A tool for identifying which classfile is being used. - * under the given conditions. - */ -object Which { - def main(args: Array[String]): Unit = { - val settings = new Settings() - val names = settings.processArguments(args.toList, true)._2 - val global = new Global(settings) - val cp = global.classPath - - import cp._ - - for (name <- names) { - def fail() = println("Could not find: %s".format(name)) - (cp findClass name) match { - case Some(classRep) => classRep.binary match { - case Some(f) => println("%s is %s".format(name, f)) - case _ => fail - } - case _ => fail - } - } - } -} - - - - diff --git a/src/compiler/scala/tools/util/color/Ansi.scala b/src/compiler/scala/tools/util/color/Ansi.scala deleted file mode 100644 index 1ed43579bb..0000000000 --- a/src/compiler/scala/tools/util/color/Ansi.scala +++ /dev/null @@ -1,58 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2012 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.util -package color - -import collection.mutable - -object Ansi { - final val ESC = '\u001b' // <esc> - final val LBR = '\u005b' // [ - final val CSI = new String(Array(ESC, LBR)) // control sequence introducer - final val CSI_FINAL = "m" // control sequence final byte - - def colors = List(Black, Red, Green, Yellow, Blue, Magenta, Cyan, White) - def effects = List(Reset, Bright, Faint, Italic, Underline, Blink, Inverse, Hidden, Strikethrough) - - // No, that's not the finale of "CSI: Crime Scene Investigation." - - def colorizerFor(codes: Seq[Int]): String => String = - s => ansiCodeToString(codes) + s + ansiCodeToString(0) - - def ansiCodeToString(code: Int): String = CSI + code + CSI_FINAL - def ansiCodeToString(codes: Seq[Int]): String = codes.mkString(CSI, ";", CSI_FINAL) -} - -/** An ansi control sequence. The colorize function prepends - * the control sequence to the given String and appends a - * reset sequence. - */ -class Ansi(atoms0: List[AnsiAtom]) { - val atoms = atoms0 sortBy (x => (!x.isAttr, x.isInstanceOf[AnsiBackground])) - val colorize = Ansi colorizerFor codes - - def codes = atoms map (_.code) - def /(that: AnsiAtom) = new Ansi(atoms :+ that) - // This looks redundant with / , but isn't - it is a way - // to ensure that the argument will be a background color, - // even if a foreground color is passed as an argument - // (as it will be implicitly converted.) - def on(that: AnsiBackground) = this / that - - // Convenience functions. - def reset = this / Reset - def bright = this / Bright - def faint = this / Faint - def italic = this / Italic - def underline = this / Underline - def blink = this / Blink - def inverse = this / Inverse - def hidden = this / Hidden - def strikethrough = this / Strikethrough - - // adjectives first - override def toString = atoms mkString " " -} diff --git a/src/compiler/scala/tools/util/color/AnsiAtom.scala b/src/compiler/scala/tools/util/color/AnsiAtom.scala deleted file mode 100644 index 5d5490f6e9..0000000000 --- a/src/compiler/scala/tools/util/color/AnsiAtom.scala +++ /dev/null @@ -1,51 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2012 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.util -package color - -case object Reset extends AnsiAttr(0) -case object Bright extends AnsiAttr(1) -case object Faint extends AnsiAttr(2) -case object Italic extends AnsiAttr(3) -case object Underline extends AnsiAttr(4) -case object Blink extends AnsiAttr(5) -case object Inverse extends AnsiAttr(7) -case object Hidden extends AnsiAttr(8) -case object Strikethrough extends AnsiAttr(9) - -case object Black extends AnsiForeground(30) -case object Red extends AnsiForeground(31) -case object Green extends AnsiForeground(32) -case object Yellow extends AnsiForeground(33) -case object Blue extends AnsiForeground(34) -case object Magenta extends AnsiForeground(35) -case object Cyan extends AnsiForeground(36) -case object White extends AnsiForeground(37) -case object Default extends AnsiForeground(39) - -/** One piece of an ansi control sequence. Either a color - * (foreground or background) or an attribute (e.g. bright, underline.) - * Control sequences are created from AnsiAtoms with the / operator. - */ -trait AnsiAtom { - def code: Int - def isAttr: Boolean -} -sealed abstract class AnsiAttr(val code: Int) extends AnsiAtom { - final def isAttr = true -} -sealed abstract class AnsiColor(val code: Int) extends AnsiAtom { - final def isAttr = false - def flip: AnsiColor -} -sealed abstract class AnsiForeground(code: Int) extends AnsiColor(code) { - require(30 <= code && code <= 39, code) - val flip: AnsiBackground = new AnsiBackground(this) -} -sealed class AnsiBackground(val flip: AnsiForeground) extends AnsiColor(flip.code + 10) { - require(40 <= code && code <= 49, code) - override def toString = "(on " + flip + " background)" -} diff --git a/src/compiler/scala/tools/util/color/CString.scala b/src/compiler/scala/tools/util/color/CString.scala deleted file mode 100644 index fa57229f09..0000000000 --- a/src/compiler/scala/tools/util/color/CString.scala +++ /dev/null @@ -1,37 +0,0 @@ -package scala.tools.util -package color - -/** A colorized String. It's difficult to achieve precise - * formatting and selective string colorization simultaneously, - * because all length-based calculations will break down in - * the face of the ansi controls. It doesn't do much yet, but - * this is here to eventually make that transparent. - */ -final class CString(val uncolorized: String, val colorized: String) { - def visibleLength = uncolorized.length - def colorizedLength = colorized.length - def show() = Console println colorized - def bytes() = colorized map (_.toByte) - def >() = show() - - def append(x: CString): CString = new CString(uncolorized + x.uncolorized, colorized + x.colorized) - def +(other: CString): CString = this append other - - override def toString = colorized -} - -class CStringOps(str: String) { - /** String to String operation. - * println("foo" in Red) - * println("bar" in Magenta.bright) - */ - def in(ansi: Ansi): String = ansi colorize str - - /** Gave in to one bit of punctuation, because everyone adds - * strings with '+' and we need something which higher precedence - * for it to be at all satisfying. - * - * "foo" %> Red + "bar" %> Magenta.bright - */ - def %>(ansi: Ansi): CString = new CString(str, in(ansi)) -} diff --git a/src/compiler/scala/tools/util/color/ColorNames.scala b/src/compiler/scala/tools/util/color/ColorNames.scala deleted file mode 100644 index ff4b01a9df..0000000000 --- a/src/compiler/scala/tools/util/color/ColorNames.scala +++ /dev/null @@ -1,391 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2012 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.util.color - -/** Raw data adapted from perl's Term-ExtendedColor, which is published - * under perl's Artistic license: http://dev.perl.org/licenses/artistic.html - * - * These aren't actually in use yet. - */ -trait ColorNames { - type ColorType - def translateCode(ansiCode: String): ColorType - - private implicit def liftAnsiCode(code: String): ColorType = translateCode(code) - - // Possible alternative names or aliases, also from the perl: - // - // reset, clear, normal reset all attributes - // bold, bright bold or bright, depending on implementation - // faint decreased intensity (not widely supported) - // italic, cursive italic or cursive - // underline, underscore underline - // blink slow blink - // blink_ms rapid blink (only supported in MS DOS) - // reverse, inverse, negative reverse video - // conceal conceal, or hide (not widely supported) - - // Brightest to darkest color - val red1: ColorType = "5;196" - val red2: ColorType = "5;160" - val red3: ColorType = "5;124" - val red4: ColorType = "5;088" - val red5: ColorType = "5;052" - - val green1: ColorType = "5;156" - val green2: ColorType = "5;150" - val green3: ColorType = "5;120" - val green4: ColorType = "5;114" - val green5: ColorType = "5;084" - val green6: ColorType = "5;078" - val green7: ColorType = "5;155" - val green8: ColorType = "5;149" - val green9: ColorType = "5;119" - val green10: ColorType = "5;113" - val green11: ColorType = "5;083" - val green12: ColorType = "5;077" - val green13: ColorType = "5;047" - val green14: ColorType = "5;041" - val green15: ColorType = "5;118" - val green16: ColorType = "5;112" - val green17: ColorType = "5;082" - val green18: ColorType = "5;076" - val green19: ColorType = "5;046" - val green20: ColorType = "5;040" - val green21: ColorType = "5;034" - val green22: ColorType = "5;028" - val green23: ColorType = "5;022" - val green24: ColorType = "5;107" - val green25: ColorType = "5;071" - val green26: ColorType = "5;070" - val green27: ColorType = "5;064" - val green28: ColorType = "5;065" - - val blue1: ColorType = "5;075" - val blue2: ColorType = "5;074" - val blue3: ColorType = "5;073" - val blue4: ColorType = "5;039" - val blue5: ColorType = "5;038" - val blue6: ColorType = "5;037" - val blue7: ColorType = "5;033" - val blue8: ColorType = "5;032" - val blue9: ColorType = "5;031" - val blue10: ColorType = "5;027" - val blue11: ColorType = "5;026" - val blue12: ColorType = "5;025" - val blue13: ColorType = "5;021" - val blue14: ColorType = "5;020" - val blue15: ColorType = "5;019" - val blue16: ColorType = "5;018" - val blue17: ColorType = "5;017" - - val yellow1: ColorType = "5;228" - val yellow2: ColorType = "5;222" - val yellow3: ColorType = "5;192" - val yellow4: ColorType = "5;186" - val yellow5: ColorType = "5;227" - val yellow6: ColorType = "5;221" - val yellow7: ColorType = "5;191" - val yellow8: ColorType = "5;185" - val yellow9: ColorType = "5;226" - val yellow10: ColorType = "5;220" - val yellow11: ColorType = "5;190" - val yellow12: ColorType = "5;184" - val yellow13: ColorType = "5;214" - val yellow14: ColorType = "5;178" - val yellow15: ColorType = "5;208" - val yellow16: ColorType = "5;172" - val yellow17: ColorType = "5;202" - val yellow18: ColorType = "5;166" - - val magenta1: ColorType = "5;219" - val magenta2: ColorType = "5;183" - val magenta3: ColorType = "5;218" - val magenta4: ColorType = "5;182" - val magenta5: ColorType = "5;217" - val magenta6: ColorType = "5;181" - val magenta7: ColorType = "5;213" - val magenta8: ColorType = "5;177" - val magenta9: ColorType = "5;212" - val magenta10: ColorType = "5;176" - val magenta11: ColorType = "5;211" - val magenta12: ColorType = "5;175" - val magenta13: ColorType = "5;207" - val magenta14: ColorType = "5;171" - val magenta15: ColorType = "5;205" - val magenta16: ColorType = "5;169" - val magenta17: ColorType = "5;201" - val magenta18: ColorType = "5;165" - val magenta19: ColorType = "5;200" - val magenta20: ColorType = "5;164" - val magenta21: ColorType = "5;199" - val magenta22: ColorType = "5;163" - val magenta23: ColorType = "5;198" - val magenta24: ColorType = "5;162" - val magenta25: ColorType = "5;197" - val magenta26: ColorType = "5;161" - - val gray1: ColorType = "5;255" - val gray2: ColorType = "5;254" - val gray3: ColorType = "5;253" - val gray4: ColorType = "5;252" - val gray5: ColorType = "5;251" - val gray6: ColorType = "5;250" - val gray7: ColorType = "5;249" - val gray8: ColorType = "5;248" - val gray9: ColorType = "5;247" - val gray10: ColorType = "5;246" - val gray11: ColorType = "5;245" - val gray12: ColorType = "5;244" - val gray13: ColorType = "5;243" - val gray14: ColorType = "5;242" - val gray15: ColorType = "5;241" - val gray16: ColorType = "5;240" - val gray17: ColorType = "5;239" - val gray18: ColorType = "5;238" - val gray19: ColorType = "5;237" - val gray20: ColorType = "5;236" - val gray21: ColorType = "5;235" - val gray22: ColorType = "5;234" - val gray23: ColorType = "5;233" - val gray24: ColorType = "5;232" - - val purple1: ColorType = "5;147" - val purple2: ColorType = "5;146" - val purple3: ColorType = "5;145" - val purple4: ColorType = "5;141" - val purple5: ColorType = "5;140" - val purple6: ColorType = "5;139" - val purple7: ColorType = "5;135" - val purple8: ColorType = "5;134" - val purple9: ColorType = "5;133" - val purple10: ColorType = "5;129" - val purple11: ColorType = "5;128" - val purple12: ColorType = "5;127" - val purple13: ColorType = "5;126" - val purple14: ColorType = "5;125" - val purple15: ColorType = "5;111" - val purple16: ColorType = "5;110" - val purple17: ColorType = "5;109" - val purple18: ColorType = "5;105" - val purple19: ColorType = "5;104" - val purple20: ColorType = "5;103" - val purple21: ColorType = "5;099" - val purple22: ColorType = "5;098" - val purple23: ColorType = "5;097" - val purple24: ColorType = "5;096" - val purple25: ColorType = "5;093" - val purple26: ColorType = "5;092" - val purple27: ColorType = "5;091" - val purple28: ColorType = "5;090" - val purple29: ColorType = "5;055" - val purple30: ColorType = "5;054" - - val cyan1: ColorType = "5;159" - val cyan2: ColorType = "5;158" - val cyan3: ColorType = "5;157" - val cyan4: ColorType = "5;153" - val cyan5: ColorType = "5;152" - val cyan6: ColorType = "5;151" - val cyan7: ColorType = "5;123" - val cyan8: ColorType = "5;122" - val cyan9: ColorType = "5;121" - val cyan10: ColorType = "5;117" - val cyan11: ColorType = "5;116" - val cyan12: ColorType = "5;115" - val cyan13: ColorType = "5;087" - val cyan14: ColorType = "5;086" - val cyan15: ColorType = "5;085" - val cyan16: ColorType = "5;081" - val cyan17: ColorType = "5;080" - val cyan18: ColorType = "5;079" - val cyan19: ColorType = "5;051" - val cyan20: ColorType = "5;050" - val cyan21: ColorType = "5;049" - val cyan22: ColorType = "5;045" - val cyan23: ColorType = "5;044" - val cyan24: ColorType = "5;043" - - val orange1: ColorType = "5;208" - val orange2: ColorType = "5;172" - val orange3: ColorType = "5;202" - val orange4: ColorType = "5;166" - val orange5: ColorType = "5;130" - - // Approximations of X11 color mappings - // https://secure.wikimedia.org/wikipedia/en/wiki/X11%20colors - - val aquamarine1: ColorType = "5;086" - val aquamarine3: ColorType = "5;079" - val blueviolet: ColorType = "5;057" - val cadetblue1: ColorType = "5;072" - val cadetblue2: ColorType = "5;073" - val chartreuse1: ColorType = "5;118" - val chartreuse2: ColorType = "5;082" - val chartreuse3: ColorType = "5;070" - val chartreuse4: ColorType = "5;064" - val cornflowerblue: ColorType = "5;069" - val cornsilk1: ColorType = "5;230" - val darkblue: ColorType = "5;018" - val darkcyan: ColorType = "5;036" - val darkgoldenrod: ColorType = "5;136" - val darkgreen: ColorType = "5;022" - val darkkhaki: ColorType = "5;143" - val darkmagenta1: ColorType = "5;090" - val darkmagenta2: ColorType = "5;091" - val darkolivegreen1: ColorType = "5;191" - val darkolivegreen2: ColorType = "5;155" - val darkolivegreen3: ColorType = "5;107" - val darkolivegreen4: ColorType = "5;113" - val darkolivegreen5: ColorType = "5;149" - val darkorange3: ColorType = "5;130" - val darkorange4: ColorType = "5;166" - val darkorange1: ColorType = "5;208" - val darkred1: ColorType = "5;052" - val darkred2: ColorType = "5;088" - val darkseagreen1: ColorType = "5;158" - val darkseagreen2: ColorType = "5;157" - val darkseagreen3: ColorType = "5;150" - val darkseagreen4: ColorType = "5;071" - val darkslategray1: ColorType = "5;123" - val darkslategray2: ColorType = "5;087" - val darkslategray3: ColorType = "5;116" - val darkturquoise: ColorType = "5;044" - val darkviolet: ColorType = "5;128" - val deeppink1: ColorType = "5;198" - val deeppink2: ColorType = "5;197" - val deeppink3: ColorType = "5;162" - val deeppink4: ColorType = "5;125" - val deepskyblue1: ColorType = "5;039" - val deepskyblue2: ColorType = "5;038" - val deepskyblue3: ColorType = "5;031" - val deepskyblue4: ColorType = "5;023" - val dodgerblue1: ColorType = "5;033" - val dodgerblue2: ColorType = "5;027" - val dodgerblue3: ColorType = "5;026" - val gold1: ColorType = "5;220" - val gold3: ColorType = "5;142" - val greenyellow: ColorType = "5;154" - val grey0: ColorType = "5;016" - val grey100: ColorType = "5;231" - val grey11: ColorType = "5;234" - val grey15: ColorType = "5;235" - val grey19: ColorType = "5;236" - val grey23: ColorType = "5;237" - val grey27: ColorType = "5;238" - val grey30: ColorType = "5;239" - val grey3: ColorType = "5;232" - val grey35: ColorType = "5;240" - val grey37: ColorType = "5;059" - val grey39: ColorType = "5;241" - val grey42: ColorType = "5;242" - val grey46: ColorType = "5;243" - val grey50: ColorType = "5;244" - val grey53: ColorType = "5;102" - val grey54: ColorType = "5;245" - val grey58: ColorType = "5;246" - val grey62: ColorType = "5;247" - val grey63: ColorType = "5;139" - val grey66: ColorType = "5;248" - val grey69: ColorType = "5;145" - val grey70: ColorType = "5;249" - val grey74: ColorType = "5;250" - val grey7: ColorType = "5;233" - val grey78: ColorType = "5;251" - val grey82: ColorType = "5;252" - val grey84: ColorType = "5;188" - val grey85: ColorType = "5;253" - val grey89: ColorType = "5;254" - val grey93: ColorType = "5;255" - val honeydew2: ColorType = "5;194" - val hotpink2: ColorType = "5;169" - val hotpink3: ColorType = "5;132" - val hotpink: ColorType = "5;205" - val indianred1: ColorType = "5;203" - val indianred: ColorType = "5;167" - val khaki1: ColorType = "5;228" - val khaki3: ColorType = "5;185" - val lightcoral: ColorType = "5;210" - val lightcyan1: ColorType = "5;195" - val lightcyan3: ColorType = "5;152" - val lightgoldenrod1: ColorType = "5;227" - val lightgoldenrod2: ColorType = "5;186" - val lightgoldenrod3: ColorType = "5;179" - val lightgreen: ColorType = "5;119" - val lightpink1: ColorType = "5;217" - val lightpink3: ColorType = "5;174" - val lightpink4: ColorType = "5;095" - val lightsalmon1: ColorType = "5;216" - val lightsalmon3: ColorType = "5;137" - val lightseagreen: ColorType = "5;037" - val lightskyblue1: ColorType = "5;153" - val lightskyblue3: ColorType = "5;109" - val lightslateblue: ColorType = "5;105" - val lightslategrey: ColorType = "5;103" - val lightsteelblue1: ColorType = "5;189" - val lightsteelblue3: ColorType = "5;146" - val lightsteelblue: ColorType = "5;147" - val lightyellow3: ColorType = "5;187" - val mediumorchid1: ColorType = "5;171" - val mediumorchid3: ColorType = "5;133" - val mediumorchid: ColorType = "5;134" - val mediumpurple1: ColorType = "5;141" - val mediumpurple2: ColorType = "5;135" - val mediumpurple3: ColorType = "5;097" - val mediumpurple4: ColorType = "5;060" - val mediumpurple: ColorType = "5;104" - val mediumspringgreen: ColorType = "5;049" - val mediumturquoise: ColorType = "5;080" - val mediumvioletred: ColorType = "5;126" - val mistyrose1: ColorType = "5;224" - val mistyrose3: ColorType = "5;181" - val navajowhite1: ColorType = "5;223" - val navajowhite3: ColorType = "5;144" - val navyblue: ColorType = "5;017" - val orangered1: ColorType = "5;202" - val orchid1: ColorType = "5;213" - val orchid2: ColorType = "5;212" - val orchid: ColorType = "5;170" - val palegreen1: ColorType = "5;121" - val palegreen3: ColorType = "5;077" - val paleturquoise1: ColorType = "5;159" - val paleturquoise4: ColorType = "5;066" - val palevioletred1: ColorType = "5;211" - val pink1: ColorType = "5;218" - val pink3: ColorType = "5;175" - val plum1: ColorType = "5;219" - val plum2: ColorType = "5;183" - val plum3: ColorType = "5;176" - val plum4: ColorType = "5;096" - val purple: ColorType = "5;129" - val rosybrown: ColorType = "5;138" - val royalblue1: ColorType = "5;063" - val salmon1: ColorType = "5;209" - val sandybrown: ColorType = "5;215" - val seagreen1: ColorType = "5;084" - val seagreen2: ColorType = "5;083" - val seagreen3: ColorType = "5;078" - val skyblue1: ColorType = "5;117" - val skyblue2: ColorType = "5;111" - val skyblue3: ColorType = "5;074" - val slateblue1: ColorType = "5;099" - val slateblue3: ColorType = "5;061" - val springgreen1: ColorType = "5;048" - val springgreen2: ColorType = "5;042" - val springgreen3: ColorType = "5;035" - val springgreen4: ColorType = "5;029" - val steelblue1: ColorType = "5;075" - val steelblue3: ColorType = "5;068" - val steelblue: ColorType = "5;067" - val tan: ColorType = "5;180" - val thistle1: ColorType = "5;225" - val thistle3: ColorType = "5;182" - val turquoise2: ColorType = "5;045" - val turquoise4: ColorType = "5;030" - val violet: ColorType = "5;177" - val wheat1: ColorType = "5;229" - val wheat4: ColorType = "5;101" -} diff --git a/src/compiler/scala/tools/util/color/package.scala b/src/compiler/scala/tools/util/color/package.scala deleted file mode 100644 index 3b3e85751e..0000000000 --- a/src/compiler/scala/tools/util/color/package.scala +++ /dev/null @@ -1,22 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2012 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.util - -/** - * Wrappers around ansi colors. - * - * @author Paul Phillips - * @version 2.10 - */ -package object color { - implicit def implicitLiftAnsiAtom(c: AnsiAtom): Ansi = new Ansi(List(c)) - implicit def implicitColorToBackground(c: AnsiColor): AnsiBackground = c match { - case x: AnsiBackground => x - case x: AnsiForeground => x.flip - } - implicit def implicitCStringOps(str: String): CStringOps = new CStringOps(str) - implicit def implicitCString(str: String): CString = new CString(str, str) -} diff --git a/src/library/scala/sys/SystemProperties.scala b/src/library/scala/sys/SystemProperties.scala index 4853da3495..d5777922b4 100644 --- a/src/library/scala/sys/SystemProperties.scala +++ b/src/library/scala/sys/SystemProperties.scala @@ -78,6 +78,5 @@ object SystemProperties { lazy val preferIPv4Stack = bool("java.net.preferIPv4Stack", "system should prefer IPv4 sockets") lazy val preferIPv6Addresses = bool("java.net.preferIPv6Addresses", "system should prefer IPv6 addresses") lazy val noTraceSupression = bool("scala.control.noTraceSuppression", "scala should not suppress any stack trace creation") - lazy val traceSourcePath = str("scala.control.sourcepath", "sourcepath for looking up stack trace elements") } diff --git a/src/yourkit/scala/tools/util/YourkitProfiling.scala b/src/yourkit/scala/tools/util/YourkitProfiling.scala deleted file mode 100644 index 677a85112b..0000000000 --- a/src/yourkit/scala/tools/util/YourkitProfiling.scala +++ /dev/null @@ -1,63 +0,0 @@ -package scala.tools -package util - -import com.yourkit.api._ -import com.yourkit.runtime._ -import nsc.io._ - -class YourkitProfiling extends Profiling { - @volatile private var active = false - @volatile private var freq: Option[Int] = None - lazy val controller = new Controller - - def defaultFreq = 100 - def allocationFreq = freq - def setAllocationFreq(x: Int) = freq = if (x <= 0) None else Some(x) - - def startRecordingAllocations() = { - controller.startAllocationRecording(true, freq getOrElse defaultFreq, false, 0) - } - def stopRecordingAllocations() = { - controller.stopAllocationRecording() - } - - def startProfiling(): Unit = { - if (isActive) - return - - active = true - daemonize { - try { - controller.startCPUProfiling(ProfilingModes.CPU_SAMPLING, Controller.DEFAULT_FILTERS) - if (freq.isDefined) - startRecordingAllocations() - } - catch { - case _: PresentableException => () // if it's already running, no big deal - } - } - } - - def captureSnapshot() = { - daemonize(controller.captureSnapshot(ProfilingModes.SNAPSHOT_WITH_HEAP)) - } - - def stopProfiling() = { - try { - if (freq.isDefined) - stopRecordingAllocations() - - controller.stopCPUProfiling() - } - catch { - case _: PresentableException => () // if it's already running, no big deal - } - finally active = false - } - - def advanceGeneration(desc: String) { - controller.advanceGeneration(desc) - } - - def isActive = active -} |