diff options
Diffstat (limited to 'src')
102 files changed, 189 insertions, 6685 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/AnnotationInfos.scala b/src/compiler/scala/reflect/internal/AnnotationInfos.scala index 5bdd04e544..91e1c3d50d 100644 --- a/src/compiler/scala/reflect/internal/AnnotationInfos.scala +++ b/src/compiler/scala/reflect/internal/AnnotationInfos.scala @@ -138,7 +138,11 @@ trait AnnotationInfos extends api.AnnotationInfos { self: SymbolTable => // necessary for reification, see Reifiers.scala for more info private var orig: Tree = EmptyTree def original = orig - def setOriginal(t: Tree): this.type = { orig = t; this } + def setOriginal(t: Tree): this.type = { + orig = t + this setPos t.pos + this + } override def toString = ( atp + 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/HasFlags.scala b/src/compiler/scala/reflect/internal/HasFlags.scala index 348f81c51d..0937577ca3 100644 --- a/src/compiler/scala/reflect/internal/HasFlags.scala +++ b/src/compiler/scala/reflect/internal/HasFlags.scala @@ -75,70 +75,41 @@ trait HasFlags { * flag carrying entity. */ def resolveOverloadedFlag(flag: Long): String = Flags.flagToString(flag) - - def privateWithinString = if (hasAccessBoundary) privateWithin.toString else "" - - protected def isSetting(f: Long, mask: Long) = !hasFlag(f) && ((mask & f) != 0L) - protected def isClearing(f: Long, mask: Long) = hasFlag(f) && ((mask & f) != 0L) // Tests which come through cleanly: both Symbol and Modifiers use these // identically, testing for a single flag. - def isCase = hasFlag(CASE ) - def isFinal = hasFlag(FINAL ) - def isImplicit = hasFlag(IMPLICIT ) - def isLazy = hasFlag(LAZY ) - def isMutable = hasFlag(MUTABLE ) // in Modifiers, formerly isVariable - def isOverride = hasFlag(OVERRIDE ) - def isPrivate = hasFlag(PRIVATE ) - def isProtected = hasFlag(PROTECTED) - def isSynthetic = hasFlag(SYNTHETIC) - def isInterface = hasFlag(INTERFACE) - - // Newly introduced based on having a reasonably obvious clean translation. - def isPrivateLocal = hasAllFlags(PrivateLocal) - def isProtectedLocal = hasAllFlags(ProtectedLocal) - def isParamAccessor = hasFlag(PARAMACCESSOR) - def isCaseAccessor = hasFlag(CASEACCESSOR) - def isSuperAccessor = hasFlag(SUPERACCESSOR) - def isLifted = hasFlag(LIFTED) - - // Formerly the Modifiers impl did not include the access boundary check, - // which must have been a bug. - def isPublic = hasNoFlags(PRIVATE | PROTECTED) && !hasAccessBoundary - - // Removed isClass qualification since the flag isn't overloaded and - // sym.isClass is enforced in Namers#validate. - def isSealed = hasFlag(SEALED) - - // Removed !isClass qualification since the flag isn't overloaded. - def isDeferred = hasFlag(DEFERRED) - - // Dropped isTerm condition because flag isn't overloaded. + def hasAbstractFlag = hasFlag(ABSTRACT) + def hasAccessorFlag = hasFlag(ACCESSOR) + def hasDefault = hasAllFlags(DEFAULTPARAM | PARAM) + def hasLocalFlag = hasFlag(LOCAL) + def hasModuleFlag = hasFlag(MODULE) + def hasPackageFlag = hasFlag(PACKAGE) + def hasStableFlag = hasFlag(STABLE) + def hasStaticFlag = hasFlag(STATIC) def isAbstractOverride = hasFlag(ABSOVERRIDE) - def isAnyOverride = hasFlag(OVERRIDE | ABSOVERRIDE) - - // Disambiguating: DEFAULTPARAM, TRAIT - def hasDefault = hasAllFlags(DEFAULTPARAM | PARAM) - def isTrait = hasFlag(TRAIT) && !hasFlag(PARAM) - - // Straightforwardly named accessors already being used differently. - // These names are most likely temporary. - def hasAbstractFlag = hasFlag(ABSTRACT) - def hasAccessorFlag = hasFlag(ACCESSOR) - def hasLocalFlag = hasFlag(LOCAL) - def hasModuleFlag = hasFlag(MODULE) - def hasPackageFlag = hasFlag(PACKAGE) - def hasStableFlag = hasFlag(STABLE) - def hasStaticFlag = hasFlag(STATIC) - - // Disambiguating: LABEL, CONTRAVARIANT, INCONSTRUCTOR - def isLabel = hasAllFlags(LABEL | METHOD) && !hasAccessorFlag - // Cannot effectively disambiguate the others at this level. - def hasContravariantFlag = hasFlag(CONTRAVARIANT) - def hasInConstructorFlag = hasFlag(INCONSTRUCTOR) - - // Name - def isJavaDefined = hasFlag(JAVA) + def isAnyOverride = hasFlag(OVERRIDE | ABSOVERRIDE) + def isCase = hasFlag(CASE) + def isCaseAccessor = hasFlag(CASEACCESSOR) + def isDeferred = hasFlag(DEFERRED) + def isFinal = hasFlag(FINAL) + def isImplicit = hasFlag(IMPLICIT) + def isInterface = hasFlag(INTERFACE) + def isJavaDefined = hasFlag(JAVA) + def isLabel = hasAllFlags(LABEL | METHOD) && !hasAccessorFlag + def isLazy = hasFlag(LAZY) + def isLifted = hasFlag(LIFTED) + def isMutable = hasFlag(MUTABLE) + def isOverride = hasFlag(OVERRIDE) + def isParamAccessor = hasFlag(PARAMACCESSOR) + def isPrivate = hasFlag(PRIVATE) + def isPrivateLocal = hasAllFlags(PrivateLocal) + def isProtected = hasFlag(PROTECTED) + def isProtectedLocal = hasAllFlags(ProtectedLocal) + def isPublic = hasNoFlags(PRIVATE | PROTECTED) && !hasAccessBoundary + def isSealed = hasFlag(SEALED) + def isSuperAccessor = hasFlag(SUPERACCESSOR) + def isSynthetic = hasFlag(SYNTHETIC) + def isTrait = hasFlag(TRAIT) && !hasFlag(PARAM) def flagBitsToString(bits: Long): String = { // Fast path for common case @@ -162,7 +133,7 @@ trait HasFlags { } def accessString: String = { - val pw = privateWithinString + val pw = if (hasAccessBoundary) privateWithin.toString else "" if (pw == "") { if (hasAllFlags(PrivateLocal)) "private[this]" @@ -188,8 +159,6 @@ trait HasFlags { def hasTraitFlag = hasFlag(TRAIT) @deprecated("Use hasDefault", "2.10.0") def hasDefaultFlag = hasFlag(DEFAULTPARAM) - @deprecated("", "2.9.0") - def isAbstract = hasFlag(ABSTRACT) @deprecated("Use isValueParameter or isTypeParameter", "2.10.0") def isParameter = hasFlag(PARAM) @deprecated("Use flagString", "2.10.0") 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/SymbolCreations.scala b/src/compiler/scala/reflect/internal/SymbolCreations.scala deleted file mode 100644 index ac82ffe62a..0000000000 --- a/src/compiler/scala/reflect/internal/SymbolCreations.scala +++ /dev/null @@ -1,112 +0,0 @@ - /* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.reflect -package internal - -import scala.collection.{ mutable, immutable } -import scala.collection.mutable.ListBuffer -import util.Statistics._ -import Flags._ -import api.Modifier - -trait SymbolCreations { - self: SymbolTable => - - import definitions._ - - /** Symbol creation interface, possibly better moved somewhere else. - * It'd be nice if we had virtual classes, but since we - * don't: these methods insulate the direct instantiation of the symbols - * (which may be overridden, e.g. in SynchronizedSymbols) from the - * enforcement of preconditions and choice of symbol constructor based - * on flags, which are (or should be) final so they can be reasoned about - * without lots of surprises. - */ - trait SymbolCreatorInterface { - // Fallbacks; more precise creators should normally be called. - protected def createTermSymbol(name: TermName, pos: Position, newFlags: Long): TermSymbol - // This in fact does not exist anymore in the interests of better typed TypeSymbols. - // protected def createTypeSymbol(name: TypeName, pos: Position, newFlags: Long): TypeSymbol - - // I believe all but rogue TypeSymbols are one of: ClassSymbol, AbstractTypeSymbol, AliasTypeSymbol, or TypeSkolem. - protected def createAbstractTypeSymbol(name: TypeName, pos: Position, newFlags: Long): AbstractTypeSymbol - protected def createAliasTypeSymbol(name: TypeName, pos: Position, newFlags: Long): AliasTypeSymbol - protected def createTypeSkolemSymbol(name: TypeName, origin: AnyRef, pos: Position, newFlags: Long): TypeSkolem - protected def createClassSymbol(name: TypeName, pos: Position, newFlags: Long): ClassSymbol - - // More specific ClassSymbols. - // TODO - AnonymousClassSymbol. - // TODO maybe - PackageObjects, but that one cost me a lot of time when I tried it before - // because it broke reification some way I couldn't see. - protected def createModuleClassSymbol(name: TypeName, pos: Position, newFlags: Long): ModuleClassSymbol - protected def createPackageClassSymbol(name: TypeName, pos: Position, newFlags: Long): PackageClassSymbol - protected def createRefinementClassSymbol(pos: Position, newFlags: Long): RefinementClassSymbol - protected def createImplClassSymbol(name: TypeName, pos: Position, newFlags: Long): ClassSymbol - protected def createPackageObjectClassSymbol(pos: Position, newFlags: Long): PackageObjectClassSymbol - - // Distinguished term categories include methods, modules, packages, package objects, - // value parameters, and values (including vals, vars, and lazy vals.) - protected def createMethodSymbol(name: TermName, pos: Position, newFlags: Long): MethodSymbol - protected def createModuleSymbol(name: TermName, pos: Position, newFlags: Long): ModuleSymbol - protected def createPackageSymbol(name: TermName, pos: Position, newFlags: Long): PackageSymbol - - // TODO - // protected def createValueParameterSymbol(name: TermName, pos: Position, newFlags: Long): TermSymbol - // protected def createValueMemberSymbol(name: TermName, pos: Position, newFlags: Long): TermSymbol - } - - trait SymbolCreator extends SymbolCreatorInterface { - self: Symbol => - - /*** Predictable symbol creation. - * - * newTermSymbol, newClassSymbol, and newNonClassSymbol all create symbols based - * only on the flags (for reconstruction after reification.) It would be nice to - * combine the last two into newTypeSymbol, but this requires some flag which allows us - * to distinguish classes and type aliases, which as yet does not exist. - * - * The fundamental flags used to determine which Symbol subclass to instantiate are: - * METHOD, PACKAGE, MODULE, PARAM, DEFERRED. - */ - final def newTermSymbol(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): TermSymbol = { - if ((newFlags & METHOD) != 0) - createMethodSymbol(name, pos, newFlags) - else if ((newFlags & PACKAGE) != 0) - createPackageSymbol(name, pos, newFlags | PackageFlags) - else if ((newFlags & MODULE) != 0) - createModuleSymbol(name, pos, newFlags) - else if ((newFlags & PARAM) != 0) - createValueParameterSymbol(name, pos, newFlags) - else - createValueMemberSymbol(name, pos, newFlags) - } - - final def newClassSymbol(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): ClassSymbol = { - if (name == tpnme.REFINE_CLASS_NAME) - createRefinementClassSymbol(pos, newFlags) - else if ((newFlags & PACKAGE) != 0) - createPackageClassSymbol(name, pos, newFlags | PackageFlags) - else if (name == tpnme.PACKAGE) - createPackageObjectClassSymbol(pos, newFlags) - else if ((newFlags & MODULE) != 0) - createModuleClassSymbol(name, pos, newFlags) - else if ((newFlags & IMPLCLASS) != 0) - createImplClassSymbol(name, pos, newFlags) - else - createClassSymbol(name, pos, newFlags) - } - - final def newNonClassSymbol(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): TypeSymbol = { - if ((newFlags & DEFERRED) != 0) - createAbstractTypeSymbol(name, pos, newFlags) - else - createAliasTypeSymbol(name, pos, newFlags) - } - - def newTypeSymbol(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): TypeSymbol = - newNonClassSymbol(name, pos, newFlags) - } -} diff --git a/src/compiler/scala/reflect/internal/SymbolFlags.scala b/src/compiler/scala/reflect/internal/SymbolFlags.scala deleted file mode 100644 index 4ce8ac40df..0000000000 --- a/src/compiler/scala/reflect/internal/SymbolFlags.scala +++ /dev/null @@ -1,175 +0,0 @@ - /* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.reflect -package internal - -import scala.collection.{ mutable, immutable } -import scala.collection.mutable.ListBuffer -import util.Statistics._ -import Flags._ -import api.Modifier - -trait SymbolFlags { - self: SymbolTable => - - 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 => - - // Forced for performance reasons to define all the flag manipulation - // methods alongside the field being manipulated. - def getFlag(mask: Long): Long - def hasFlag(mask: Long): Boolean - def hasAllFlags(mask: Long): Boolean - def setFlag(mask: Long): this.type - def resetFlag(mask: Long): this.type - def initFlags(mask: Long): this.type - def resetFlags(): Unit - - 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) - - /** String representation of symbol's variance */ - def varianceString: String = - if (variance == 1) "+" - else if (variance == -1) "-" - else "" - - override def flagMask = - if (settings.debug.value && !isAbstractType) AllFlags - else if (owner.isRefinementClass) ExplicitFlags & ~OVERRIDE - else ExplicitFlags - - // make the error message more googlable - def flagsExplanationString = - if (isGADTSkolem) " (this is a GADT skolem)" - else "" - - /** If the given flag is set on this symbol, also set the corresponding - * notFLAG. For instance if flag is PRIVATE, the notPRIVATE flag will - * be set if PRIVATE is currently set. - */ - final def setNotFlag(flag: Int) = if (hasFlag(flag)) setFlag((flag: @annotation.switch) match { - case PRIVATE => notPRIVATE - case PROTECTED => notPROTECTED - case OVERRIDE => notOVERRIDE - case _ => abort("setNotFlag on invalid flag: " + flag) - }) - - def shortSymbolClass = getClass.getName.split('.').last.stripPrefix("Symbols$") - def symbolCreationString: String = ( - "%s%25s | %-40s | %s".format( - if (settings.uniqid.value) "%06d | ".format(id) else "", - shortSymbolClass, - name.decode + " in " + owner, - rawFlagString - ) - ) - } -} diff --git a/src/compiler/scala/reflect/internal/SymbolTable.scala b/src/compiler/scala/reflect/internal/SymbolTable.scala index 76b4f5f53e..ddd6c43031 100644 --- a/src/compiler/scala/reflect/internal/SymbolTable.scala +++ b/src/compiler/scala/reflect/internal/SymbolTable.scala @@ -13,9 +13,7 @@ import scala.tools.nsc.util.WeakHashSet abstract class SymbolTable extends api.Universe with Collections with Names - with SymbolCreations with Symbols - with SymbolFlags with FreeVars with Types with Kinds @@ -290,35 +288,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 +311,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..b32b955631 100644 --- a/src/compiler/scala/reflect/internal/Symbols.scala +++ b/src/compiler/scala/reflect/internal/Symbols.scala @@ -157,9 +157,6 @@ trait Symbols extends api.Symbols { self: SymbolTable => abstract class Symbol protected[Symbols] (initOwner: Symbol, initPos: Position, initName: Name) extends AbsSymbolImpl with HasFlags - with SymbolFlagLogic - with SymbolCreator - // with FlagVerifier // DEBUG with Annotatable[Symbol] { type AccessBoundaryType = Symbol @@ -209,6 +206,36 @@ trait Symbols extends api.Symbols { self: SymbolTable => } } + def rawFlagString(mask: Long): String = calculateFlagString(rawflags & mask) + def rawFlagString: String = rawFlagString(flagMask) + def debugFlagString: String = flagString(AllFlags) + + /** String representation of symbol's variance */ + def varianceString: String = + if (variance == 1) "+" + else if (variance == -1) "-" + else "" + + override def flagMask = + if (settings.debug.value && !isAbstractType) AllFlags + else if (owner.isRefinementClass) ExplicitFlags & ~OVERRIDE + else ExplicitFlags + + // make the error message more googlable + def flagsExplanationString = + if (isGADTSkolem) " (this is a GADT skolem)" + else "" + + def shortSymbolClass = getClass.getName.split('.').last.stripPrefix("Symbols$") + def symbolCreationString: String = ( + "%s%25s | %-40s | %s".format( + if (settings.uniqid.value) "%06d | ".format(id) else "", + shortSymbolClass, + name.decode + " in " + owner, + rawFlagString + ) + ) + /** !!! The logic after "hasFlag" is far too opaque to be unexplained. * I'm guessing it's attempting to compensate for flag overloading, * and embedding such logic in an undocumented island like this is a @@ -620,15 +647,15 @@ trait Symbols extends api.Symbols { self: SymbolTable => && owner.isPackageClass && nme.isReplWrapperName(name) ) - @inline final override def getFlag(mask: Long): Long = flags & mask + @inline final def getFlag(mask: Long): Long = flags & mask /** Does symbol have ANY flag in `mask` set? */ - @inline final override def hasFlag(mask: Long): Boolean = (flags & mask) != 0 + @inline final def hasFlag(mask: Long): Boolean = (flags & mask) != 0 /** Does symbol have ALL the flags in `mask` set? */ - @inline final override def hasAllFlags(mask: Long): Boolean = (flags & mask) == mask + @inline final def hasAllFlags(mask: Long): Boolean = (flags & mask) == mask - 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) } + def setFlag(mask: Long): this.type = { _rawflags |= mask ; this } + def resetFlag(mask: Long): this.type = { _rawflags &= ~mask ; this } + def resetFlags() { rawflags &= TopLevelCreationFlags } /** Default implementation calls the generic string function, which * will print overloaded flags as <flag1/flag2/flag3>. Subclasses @@ -639,7 +666,7 @@ trait Symbols extends api.Symbols { self: SymbolTable => /** Set the symbol's flags to the given value, asserting * that the previous value was 0. */ - override def initFlags(mask: Long): this.type = { + def initFlags(mask: Long): this.type = { assert(rawflags == 0L, symbolCreationString) _rawflags = mask this @@ -1085,6 +1112,44 @@ trait Symbols extends api.Symbols { self: SymbolTable => protected def createValueMemberSymbol(name: TermName, pos: Position, newFlags: Long): TermSymbol = new TermSymbol(this, pos, name) initFlags newFlags + final def newTermSymbol(name: TermName, pos: Position = NoPosition, newFlags: Long = 0L): TermSymbol = { + if ((newFlags & METHOD) != 0) + createMethodSymbol(name, pos, newFlags) + else if ((newFlags & PACKAGE) != 0) + createPackageSymbol(name, pos, newFlags | PackageFlags) + else if ((newFlags & MODULE) != 0) + createModuleSymbol(name, pos, newFlags) + else if ((newFlags & PARAM) != 0) + createValueParameterSymbol(name, pos, newFlags) + else + createValueMemberSymbol(name, pos, newFlags) + } + + final def newClassSymbol(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): ClassSymbol = { + if (name == tpnme.REFINE_CLASS_NAME) + createRefinementClassSymbol(pos, newFlags) + else if ((newFlags & PACKAGE) != 0) + createPackageClassSymbol(name, pos, newFlags | PackageFlags) + else if (name == tpnme.PACKAGE) + createPackageObjectClassSymbol(pos, newFlags) + else if ((newFlags & MODULE) != 0) + createModuleClassSymbol(name, pos, newFlags) + else if ((newFlags & IMPLCLASS) != 0) + createImplClassSymbol(name, pos, newFlags) + else + createClassSymbol(name, pos, newFlags) + } + + final def newNonClassSymbol(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): TypeSymbol = { + if ((newFlags & DEFERRED) != 0) + createAbstractTypeSymbol(name, pos, newFlags) + else + createAliasTypeSymbol(name, pos, newFlags) + } + + def newTypeSymbol(name: TypeName, pos: Position = NoPosition, newFlags: Long = 0L): TypeSymbol = + newNonClassSymbol(name, pos, newFlags) + /** The class or term up to which this symbol is accessible, * or RootClass if it is public. As java protected statics are * otherwise completely inaccessible in scala, they are treated @@ -2434,8 +2499,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 +2526,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 +2801,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 +2959,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 +3018,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/reflect/internal/TypeDebugging.scala b/src/compiler/scala/reflect/internal/TypeDebugging.scala index 54efef8142..85a1767067 100644 --- a/src/compiler/scala/reflect/internal/TypeDebugging.scala +++ b/src/compiler/scala/reflect/internal/TypeDebugging.scala @@ -50,33 +50,6 @@ trait TypeDebugging { def refine(defs: Scope): String = defs.toList.mkString("{", " ;\n ", "}") } - def dump(tp: Type): Unit = { - println("** " + tp + " / " + tp.getClass + " **") - import tp._ - - println("typeSymbol = " + typeSymbol) - println("termSymbol = " + termSymbol) - println("widen = " + widen) - println("deconst = " + deconst) - println("typeOfThis = " + typeOfThis) - println("bounds = " + bounds) - println("parents = " + parents) - println("prefixChain = " + prefixChain) - println("typeConstructor = " + typeConstructor) - println(" .. typeConstructor.typeParams = " + typeConstructor.typeParams) - println(" .. _.variance = " + (typeConstructor.typeParams map (_.variance))) - println("typeArgs = " + typeArgs) - println("resultType = " + resultType) - println("finalResultType = " + finalResultType) - println("paramss = " + paramss) - println("paramTypes = " + paramTypes) - println("typeParams = " + typeParams) - println("boundSyms = " + boundSyms) - println("baseTypeSeq = " + baseTypeSeq) - println("baseClasses = " + baseClasses) - println("toLongString = " + toLongString) - } - private def debug(tp: Type): String = tp match { case TypeRef(pre, sym, args) => debug(pre) + "." + sym.nameString + str.tparams(args) case ThisType(sym) => sym.nameString + ".this" 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/MainInterpreter.scala b/src/compiler/scala/tools/nsc/MainInterpreter.scala deleted file mode 100644 index 5d190bbe14..0000000000 --- a/src/compiler/scala/tools/nsc/MainInterpreter.scala +++ /dev/null @@ -1,13 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Lex Spoon - */ - -package scala.tools.nsc - -import interpreter._ - -@deprecated("Use a class in the scala.tools.nsc.interpreter package.", "2.9.0") -object MainInterpreter { - def main(args: Array[String]): Unit = new ILoop main args -} 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/AbstractFileClassLoader.scala b/src/compiler/scala/tools/nsc/interpreter/AbstractFileClassLoader.scala index 3a605975f4..605ecee6c7 100644 --- a/src/compiler/scala/tools/nsc/interpreter/AbstractFileClassLoader.scala +++ b/src/compiler/scala/tools/nsc/interpreter/AbstractFileClassLoader.scala @@ -19,11 +19,6 @@ class AbstractFileClassLoader(root: AbstractFile, parent: ClassLoader) extends ClassLoader(parent) with ScalaClassLoader { - // private val defined = mutable.Map[String, Class[_]]() - - override protected def trace = - sys.props contains "scala.debug.classloader" - protected def classNameToPath(name: String): String = if (name endsWith ".class") name else name.replace('.', '/') + ".class" @@ -68,29 +63,13 @@ class AbstractFileClassLoader(root: AbstractFile, parent: ClassLoader) case null => super.classBytes(name) case file => file.toByteArray } - override def loadClass(name: String, resolve: Boolean) = { - classLoaderLog("load " + name + ".") - super.loadClass(name, resolve) - } override def findClass(name: String): JClass = { val bytes = classBytes(name) - classLoaderLog("find %s: %s".format(name, - if (bytes.isEmpty) "failed." - else bytes.size + " bytes." - )) - if (bytes.isEmpty) + if (bytes.length == 0) throw new ClassNotFoundException(name) - else { - val clazz = defineClass(name, bytes, 0, bytes.length) - // defined(name) = clazz - clazz - } + else + defineClass(name, bytes, 0, bytes.length) } - // Don't know how to construct an URL for something which exists only in memory - // override def getResource(name: String): URL = findAbstractFile(name) match { - // case null => super.getResource(name) - // case file => new URL(...) - // } private val packages = mutable.Map[String, Package]() diff --git a/src/compiler/scala/tools/nsc/interpreter/CodeHandlers.scala b/src/compiler/scala/tools/nsc/interpreter/CodeHandlers.scala index 453b106808..fc68998225 100644 --- a/src/compiler/scala/tools/nsc/interpreter/CodeHandlers.scala +++ b/src/compiler/scala/tools/nsc/interpreter/CodeHandlers.scala @@ -17,29 +17,9 @@ import scala.util.control.ControlThrowable trait CodeHandlers[T] { self => -/* - // A declaration introduces names and assigns them types. - // It can form part of a class definition (§5.1) or of a refinement in a compound type (§3.2.7). - // (Ed: aka abstract members.) - // - // ‘val’ ValDcl | ‘var’ VarDcl | ‘def’ FunDcl | ‘type’ {nl} TypeDcl - def decl(code: String): T - - // A definition introduces names that denote terms or types. - // It can form part of an object or class definition or it can be local to a block. - // (Ed: aka concrete members.) - // - // ‘val’ PatDef | ‘var’ VarDef | ‘def’ FunDef | ‘type’ {nl} TypeDef | - // [‘case’] ‘class’ ClassDef | [‘case’] ‘object’ ObjectDef | ‘trait’ TraitDef - def defn(code: String): T -*/ - // Expressions are composed of operators and operands. def expr(code: String): T - // An import clause has the form import p.I where p is a stable identifier (§3.1) and I is an import expression. - def impt(code: String): T - // Statements occur as parts of blocks and templates. // A statement can be an import, a definition or an expression, or it can be empty. // Statements used in the template of a class definition can also be declarations. @@ -54,10 +34,7 @@ trait CodeHandlers[T] { case _: NoSuccess => Nil } - // def decl(code: String) = try Some(self.decl(code)) catch handler - // def defn(code: String) = try Some(self.defn(code)) catch handler def expr(code: String) = try Some(self.expr(code)) catch handler - def impt(code: String) = try Some(self.impt(code)) catch handler def stmt(code: String) = try Some(self.stmt(code)) catch handler def stmts(code: String) = try (self.stmts(code) map (x => Some(x))) catch handlerSeq } diff --git a/src/compiler/scala/tools/nsc/interpreter/Completion.scala b/src/compiler/scala/tools/nsc/interpreter/Completion.scala index 86f48b9d69..7a3e1913b6 100644 --- a/src/compiler/scala/tools/nsc/interpreter/Completion.scala +++ b/src/compiler/scala/tools/nsc/interpreter/Completion.scala @@ -14,13 +14,11 @@ import Completion._ trait Completion { type ExecResult def resetVerbosity(): Unit - def execute(line: String): Option[ExecResult] def completer(): ScalaCompleter } object NoCompletion extends Completion { type ExecResult = Nothing def resetVerbosity() = () - def execute(line: String) = None def completer() = NullCompleter } @@ -44,8 +42,6 @@ object Completion { && !(code startsWith "./") && !(code startsWith "..") ) - private val pathStarts = """/ \ ./ ../ ~/""" split ' ' toSet - def looksLikePath(code: String) = (code != null) && (pathStarts exists (code startsWith _)) object Forwarder { def apply(forwardTo: () => Option[CompletionAware]): CompletionAware = new CompletionAware { def completions(verbosity: Int) = forwardTo() map (_ completions verbosity) getOrElse Nil diff --git a/src/compiler/scala/tools/nsc/interpreter/CompletionAware.scala b/src/compiler/scala/tools/nsc/interpreter/CompletionAware.scala index c33675a83a..b3bbeb3169 100644 --- a/src/compiler/scala/tools/nsc/interpreter/CompletionAware.scala +++ b/src/compiler/scala/tools/nsc/interpreter/CompletionAware.scala @@ -12,40 +12,15 @@ import scala.reflect.NameTransformer * will supply their own candidates and resolve their own paths. */ trait CompletionAware { - /** The delimiters which are meaningful when this CompletionAware - * object is in control. - */ - // TODO - // def delimiters(): List[Char] = List('.') - /** The complete list of unqualified Strings to which this * object will complete. */ def completions(verbosity: Int): List[String] - /** Default filter to apply to completions. - */ - def filterNotFunction(s: String): Boolean = false - - /** Default sort. - */ - def sortFunction(s1: String, s2: String): Boolean = s1 < s2 - - /** Default map. - */ - def mapFunction(s: String) = NameTransformer decode s - /** The next completor in the chain. */ def follow(id: String): Option[CompletionAware] = None - /** What to return if this completion is given as a command. It - * returns None by default, which means to allow the repl to interpret - * the line normally. Returning Some(_) means the line will never - * reach the scala interpreter. - */ - def execute(id: String): Option[Any] = None - /** A list of useful information regarding a specific uniquely * identified completion. This is specifically written for the * following situation, but should be useful elsewhere too: @@ -75,45 +50,13 @@ trait CompletionAware { else comps else follow(parsed.bufferHead) map (_ completionsFor parsed.bufferTail) getOrElse Nil - results filterNot filterNotFunction map mapFunction sortWith (sortFunction _) - } - - /** TODO - unify this and completionsFor under a common traverser. - */ - def executionFor(parsed: Parsed): Option[Any] = { - import parsed._ - - if (isUnqualified && !isLastDelimiter && (completions(verbosity) contains buffer)) execute(buffer) - else if (!isQualified) None - else follow(bufferHead) flatMap (_ executionFor bufferTail) + results.sorted } } object CompletionAware { val Empty = new CompletionAware { def completions(verbosity: Int) = Nil } - /** Artificial object demonstrating completion */ - // lazy val replVars = CompletionAware( - // Map[String, CompletionAware]( - // "ids" -> CompletionAware(() => unqualifiedIds, completionAware _), - // "synthVars" -> CompletionAware(() => allBoundNames filter isSynthVarName map (_.toString)), - // "types" -> CompletionAware(() => allSeenTypes map (_.toString)), - // "implicits" -> CompletionAware(() => allImplicits map (_.toString)) - // ) - // ) - - // class Forwarder(underlying: CompletionAware) extends CompletionAware { - // override def completions() = underlying.completions() - // override def filterNotFunction(s: String) = underlying.filterNotFunction(s) - // override def sortFunction(s1: String, s2: String) = underlying.sortFunction(s1, s2) - // override def mapFunction(s: String) = underlying.mapFunction(s) - // override def follow(id: String) = underlying.follow(id) - // override def execute(id: String) = underlying.execute(id) - // override def completionsFor(parsed: Parsed) = underlying.completionsFor(parsed) - // override def executionFor(parsed: Parsed) = underlying.executionFor(parsed) - // } - // - def unapply(that: Any): Option[CompletionAware] = that match { case x: CompletionAware => Some((x)) case _ => None 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/Eval.scala b/src/compiler/scala/tools/nsc/interpreter/Eval.scala deleted file mode 100644 index 6a59cbb6bf..0000000000 --- a/src/compiler/scala/tools/nsc/interpreter/Eval.scala +++ /dev/null @@ -1,33 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.nsc -package interpreter - -trait Eval { - /** Executes code looking for an implicit conversion from the type - * of the given identifier to CompletionAware. - */ - // def completionAwareImplicit[T](id: String) = { - // val f1string = "%s => %s".format(typeForIdent(id).get, classOf[CompletionAware].getName) - // val code = """{ - // | def f(implicit x: (%s) = null): %s = x - // | val f1 = f - // | if (f1 == null) None else Some(f1(%s)) - // |}""".stripMargin.format(f1string, f1string, id) - // - // evalExpr[Option[CompletionAware]](code) - // } - - // Coming soon - // implicit def string2liftedcode(s: String): LiftedCode = new LiftedCode(s) - // case class LiftedCode(code: String) { - // val lifted: String = { - // beQuietDuring { interpret(code) } - // eval2[String]("({ " + code + " }).toString") - // } - // def >> : String = lifted - // } -}
\ No newline at end of file diff --git a/src/compiler/scala/tools/nsc/interpreter/ExprTyper.scala b/src/compiler/scala/tools/nsc/interpreter/ExprTyper.scala index 0cd918b6a5..79b429e26a 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,17 +29,9 @@ 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()) - def impt(code: String) = applyRule(code, _.importExpr()) - def impts(code: String) = applyRule(code, _.importClause()) def stmts(code: String) = applyRule(code, _.templateStats()) def stmt(code: String) = stmts(code).last // guaranteed nonempty } @@ -111,13 +102,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/FileCompletion.scala b/src/compiler/scala/tools/nsc/interpreter/FileCompletion.scala deleted file mode 100644 index e1eb938b3c..0000000000 --- a/src/compiler/scala/tools/nsc/interpreter/FileCompletion.scala +++ /dev/null @@ -1,56 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.nsc -package interpreter - -/** TODO - * Spaces, dots, and other things in filenames are not correctly handled. - * space-escaping, knowing when we're inside quotes, etc. would be nice. - */ - -import io.{ Directory, Path } - -/** This isn't 100% clean right now, but it works and is simple. Rather - * than delegate to new objects on each '/' in the path, we treat the - * buffer like a path and process it directly. - */ -object FileCompletion { - def executionFor(buffer: String): Option[Path] = { - Some(Directory.Home match { - case Some(d) if buffer startsWith "~" => d / buffer.tail - case _ => Path(buffer) - }) filter (_.exists) - } - - private def fileCompletionForwarder(buffer: String, where: Directory): List[String] = { - completionsFor(where.path + buffer) map (_ stripPrefix where.path) toList - } - - private def homeCompletions(buffer: String): List[String] = { - require(buffer startsWith "~/") - val home = Directory.Home getOrElse (return Nil) - fileCompletionForwarder(buffer.tail, home) map ("~" + _) - } - private def cwdCompletions(buffer: String): List[String] = { - require(buffer startsWith "./") - val cwd = Directory.Current getOrElse (return Nil) - fileCompletionForwarder(buffer.tail, cwd) map ("." + _) - } - - def completionsFor(buffer: String): List[String] = - if (buffer startsWith "~/") homeCompletions(buffer) - else if (buffer startsWith "./") cwdCompletions(buffer) - else { - val p = Path(buffer) - val (dir, stub) = - // don't want /foo/. expanding "." - if (p.name == ".") (p.parent, ".") - else if (p.isDirectory) (p.toDirectory, "") - else (p.parent, p.name) - - dir.list filter (_.name startsWith stub) map (_.path) toList - } -}
\ No newline at end of file diff --git a/src/compiler/scala/tools/nsc/interpreter/ILoop.scala b/src/compiler/scala/tools/nsc/interpreter/ILoop.scala index 297d6ad1b9..de778e7469 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._ @@ -49,6 +49,9 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) var settings: Settings = _ var intp: IMain = _ + @deprecated("Use `intp` instead.", "2.9.0") def interpreter = intp + @deprecated("Use `intp` instead.", "2.9.0") def interpreter_= (i: Interpreter): Unit = intp = i + /** Having inherited the difficult "var-ness" of the repl instance, * I'm trying to work around it by moving operations into a class from * which it will appear a stable prefix. @@ -103,27 +106,11 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) def isAsync = !settings.Yreplsync.value lazy val power = new Power(intp, new StdReplVals(this)) - - // TODO - // object opt extends AestheticSettings - // - @deprecated("Use `intp` instead.", "2.9.0") - def interpreter = intp - - @deprecated("Use `intp` instead.", "2.9.0") - def interpreter_= (i: Interpreter): Unit = intp = i - def history = in.history /** 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 +139,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 ) } @@ -287,14 +257,12 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) cmd("imports", "[name name ...]", "show import history, identifying sources of names", importsCommand), cmd("implicits", "[-v]", "show the implicits in scope", implicitsCommand), cmd("javap", "<path|class>", "disassemble a file or class name", javapCommand), - nullary("keybindings", "show how ctrl-[A-Z] and other keys are bound", keybindingsCommand), cmd("load", "<path>", "load and interpret a Scala file", loadCommand), nullary("paste", "enter paste mode: all input up to ctrl-D compiled together", pasteCommand), nullary("power", "enable power user mode", powerCmd), nullary("quit", "exit the interpreter", () => Result(false, None)), nullary("replay", "reset execution and replay all previous commands", replay), nullary("reset", "reset the repl to its initial state, forgetting all session entries", resetCommand), - // nullary("reset", "reset the interpreter, forgetting session values but retaining session types", replay), shCommand, nullary("silent", "disable/enable automatic printing of results", verbosity), cmd("type", "[-v] <expr>", "display the type of an expression without evaluating it", typeCommand), @@ -303,31 +271,7 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) /** Power user commands */ lazy val powerCommands: List[LoopCommand] = List( - nullary("dump", "displays a view of the interpreter's internal state", dumpCommand), - nullary("vals", "gives information about the power mode repl vals", valsCommand), - cmd("phase", "<phase>", "set the implicit phase for power commands", phaseCommand), - cmd("wrap", "<method>", "name of method to wrap around each repl line", wrapCommand) withLongHelp (""" - |:wrap - |:wrap clear - |:wrap <method> - | - |Installs a wrapper around each line entered into the repl. - |Currently it must be the simple name of an existing method - |with the specific signature shown in the following example. - | - |def timed[T](body: => T): T = { - | val start = System.nanoTime - | try body - | finally println((System.nanoTime - start) + " nanos elapsed.") - |} - |:wrap timed - | - |If given no argument, :wrap names the wrapper installed. - |An argument of clear will remove the wrapper if any is active. - |Note that wrappers do not compose (a new one replaces the old - |one) and also that the :phase command uses the same machinery, - |so setting :wrap will clear any :phase setting. - """.stripMargin.trim) + cmd("phase", "<phase>", "set the implicit phase for power commands", phaseCommand) ) private def dumpCommand(): Result = { @@ -508,14 +452,7 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) else res.show() } } - private def keybindingsCommand(): Result = { - if (in.keyBindings.isEmpty) "Key bindings unavailable." - else { - echo("Reading jline properties for default key bindings.") - echo("Accuracy not guaranteed: treat this as a guideline only.\n") - in.keyBindings foreach (x => echo ("" + x)) - } - } + private def wrapCommand(line: String): Result = { def failMsg = "Argument to :wrap must be the name of a method with signature [T](=> T): T" onIntp { intp => @@ -539,10 +476,7 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) intp setExecutionWrapper intp.pathToTerm(wrapper) "Set wrapper to '" + wrapper + "'" case tp => - failMsg + ( - if (tp == NoType) "\nFound: <unknown>" - else "\nFound: <unknown>" - ) + failMsg + "\nFound: <unknown>" } case _ => failMsg } @@ -551,18 +485,6 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) private def pathToPhaseWrapper = intp.pathToTerm("$r") + ".phased.atCurrent" private def phaseCommand(name: String): Result = { - // This line crashes us in TreeGen: - // - // if (intp.power.phased set name) "..." - // - // Exception in thread "main" java.lang.AssertionError: assertion failed: ._7.type - // at scala.Predef$.assert(Predef.scala:99) - // at scala.tools.nsc.ast.TreeGen.mkAttributedQualifier(TreeGen.scala:69) - // at scala.tools.nsc.ast.TreeGen.mkAttributedQualifier(TreeGen.scala:44) - // at scala.tools.nsc.ast.TreeGen.mkAttributedRef(TreeGen.scala:101) - // at scala.tools.nsc.ast.TreeGen.mkAttributedStableRef(TreeGen.scala:143) - // - // But it works like so, type annotated. val phased: Phased = power.phased import phased.NoPhaseName @@ -603,14 +525,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 { @@ -846,10 +760,6 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) }) } - def runCompletion = - try in.completion execute code map (intp bindSyntheticValue _) - catch { case ex: Exception => None } - /** Here we place ourselves between the user and the interpreter and examine * the input they are ostensibly submitting. We intervene in several cases: * @@ -871,25 +781,8 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) // line comment, do nothing None } - /** Due to my accidentally letting file completion execution sneak ahead - * of actual parsing this now operates in such a way that the scala - * interpretation always wins. However to avoid losing useful file - * completion I let it fail and then check the others. So if you - * type /tmp it will echo a failure and then give you a Directory object. - * It's not pretty: maybe I'll implement the silence bits I need to avoid - * echoing the failure. - */ - else if (intp isParseable code) { - val (code, result) = reallyInterpret - if (power != null && code == IR.Error) - runCompletion - - result - } - else runCompletion match { - case Some(_) => None // completion hit: avoid the latent error - case _ => reallyInterpret._2 // trigger the latent error - } + else + reallyInterpret._2 } // runs :load `file` on any files passed via -i @@ -968,7 +861,7 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) /** process command-line arguments and do as they request */ def process(args: Array[String]): Boolean = { - val command = new CommandLine(args.toList, msg => echo("scala: " + msg)) + val command = new CommandLine(args.toList, echo) def neededHelp(): String = (if (command.settings.help.value) command.usageMsg + "\n" else "") + (if (command.settings.Xhelp.value) command.xusageMsg + "\n" else "") @@ -981,13 +874,6 @@ class ILoop(in0: Option[BufferedReader], protected val out: JPrintWriter) } @deprecated("Use `process` instead", "2.9.0") - def main(args: Array[String]): Unit = { - if (isReplDebug) - System.out.println(new java.util.Date) - - process(args) - } - @deprecated("Use `process` instead", "2.9.0") def main(settings: Settings): Unit = process(settings) } @@ -1050,32 +936,4 @@ object ILoop { } } def run(lines: List[String]): String = run(lines map (_ + "\n") mkString) - - // provide the enclosing type T - // in order to set up the interpreter's classpath and parent class loader properly - def breakIf[T: ClassTag](assertion: => Boolean, args: NamedParam*): Unit = - if (assertion) break[T](args.toList) - - // start a repl, binding supplied args - def break[T: ClassTag](args: List[NamedParam]): Unit = savingContextLoader { - val msg = if (args.isEmpty) "" else " Binding " + args.size + " value%s.".format( - if (args.size == 1) "" else "s" - ) - echo("Debug repl starting." + msg) - val repl = new ILoop { - override def prompt = "\ndebug> " - } - repl.settings = new Settings(echo) - repl.settings.embeddedDefaults[T] - repl.createInterpreter() - repl.in = new JLineReader(new JLineCompletion(repl)) - - // rebind exit so people don't accidentally call sys.exit by way of predef - repl.quietRun("""def exit = println("Type :quit to resume program execution.")""") - args foreach (p => repl.bind(p.name, p.tpe, p.value)) - repl.loop() - - echo("\nDebug repl exiting.") - repl.closeInterpreter() - } } 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..956e282b26 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,19 +300,14 @@ 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() _classLoader } private class TranslatingClassLoader(parent: ClassLoader) extends AbstractFileClassLoader(virtualDirectory, parent) { - private[IMain] var traceClassLoading = isReplTrace - override protected def trace = super.trace || traceClassLoading - /** Overridden here to try translating a simple name to the generated * class name if the original attempt fails. This method is used by * getResourceAsStream as well as findClass. @@ -596,6 +580,7 @@ class IMain(initialSettings: Settings, protected val out: JPrintWriter) extends def interpretSynthetic(line: String): IR.Result = interpret(line, true) def interpret(line: String, synthetic: Boolean): IR.Result = { def loadAndRunReq(req: Request) = { + classLoader.setAsContext() val (result, succeeded) = req.loadAndRun /** To our displeasure, ConsoleReporter offers only printMessage, @@ -725,33 +710,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 +993,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 +1088,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 +1100,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 +1181,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/InteractiveReader.scala b/src/compiler/scala/tools/nsc/interpreter/InteractiveReader.scala index 55706f4fd2..241ba5fa4a 100644 --- a/src/compiler/scala/tools/nsc/interpreter/InteractiveReader.scala +++ b/src/compiler/scala/tools/nsc/interpreter/InteractiveReader.scala @@ -22,7 +22,6 @@ trait InteractiveReader { def history: History def completion: Completion - def keyBindings: List[KeyBinding] def eraseLine(): Unit def redrawLine(): Unit def currentLine: String diff --git a/src/compiler/scala/tools/nsc/interpreter/JLineCompletion.scala b/src/compiler/scala/tools/nsc/interpreter/JLineCompletion.scala index 795b2e3678..b1e6a9d7d9 100644 --- a/src/compiler/scala/tools/nsc/interpreter/JLineCompletion.scala +++ b/src/compiler/scala/tools/nsc/interpreter/JLineCompletion.scala @@ -279,24 +279,6 @@ class JLineCompletion(val intp: IMain) extends Completion with CompletionOutput if (parsed.isEmpty) xs map ("." + _) else xs } - // chasing down results which won't parse - // This used to work fine, now it reports a type error before any - // exception gets to us. See SI-5657. Don't have time to deal with - // it, so disabling everything. - def execute(line: String): Option[ExecResult] = { - return None // disabled - - val parsed = Parsed(line) - def noDotOrSlash = line forall (ch => ch != '.' && ch != '/') - - if (noDotOrSlash) None // we defer all unqualified ids to the repl. - else { - (ids executionFor parsed) orElse - (rootClass executionFor parsed) orElse - (FileCompletion executionFor line) - } - } - // generic interface for querying (e.g. interpreter loop, testing) def completions(buf: String): List[String] = topLevelFor(Parsed.dotted(buf + ".", buf.length + 1)) @@ -360,15 +342,9 @@ class JLineCompletion(val intp: IMain) extends Completion with CompletionOutput if (!looksLikeInvocation(buf)) None else tryCompletion(Parsed.dotted(buf drop 1, cursor), lastResultFor) - def regularCompletion = tryCompletion(mkDotted, topLevelFor) - def fileCompletion = - if (!looksLikePath(buf)) None - else tryCompletion(mkUndelimited, FileCompletion completionsFor _.buffer) - def tryAll = ( lastResultCompletion - orElse regularCompletion - orElse fileCompletion + orElse tryCompletion(mkDotted, topLevelFor) getOrElse Candidates(cursor, Nil) ) diff --git a/src/compiler/scala/tools/nsc/interpreter/JLineReader.scala b/src/compiler/scala/tools/nsc/interpreter/JLineReader.scala index 99f6b627eb..758f6e2abc 100644 --- a/src/compiler/scala/tools/nsc/interpreter/JLineReader.scala +++ b/src/compiler/scala/tools/nsc/interpreter/JLineReader.scala @@ -22,9 +22,6 @@ class JLineReader(_completion: => Completion) extends InteractiveReader { lazy val completion = _completion lazy val history: JLineHistory = JLineHistory() - lazy val keyBindings = - try KeyBinding parse slurp(term.getDefaultBindings) - catch { case _: Exception => Nil } private def term = consoleReader.getTerminal() def reset() = term.reset() diff --git a/src/compiler/scala/tools/nsc/interpreter/KeyBinding.scala b/src/compiler/scala/tools/nsc/interpreter/KeyBinding.scala deleted file mode 100644 index a7ca3a77f3..0000000000 --- a/src/compiler/scala/tools/nsc/interpreter/KeyBinding.scala +++ /dev/null @@ -1,39 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.nsc -package interpreter - -case class KeyBinding(name: String, code: Int, aliases: List[String], description: String) { - def nameString = if (aliases.nonEmpty) aliases mkString ", " else name - override def toString = "%3d %s: %s".format(code, nameString, description) -} - -object KeyBinding { - def parse(bindings: String): List[KeyBinding] = { - def loop(xs: List[String]): List[KeyBinding] = { - val (comment, lines) = xs span (_ startsWith "#") - val description = comment map (_ drop 1 trim) mkString " " - val (aliases, desc) = description span (_ != ':') match { - case (x, y) => ( - x split ',' map (_.trim) toList, - if (y == "") "" else y.tail.trim - ) - } - lines match { - case Nil => Nil - case hd :: tl => - val kb = (hd indexOf '=') match { - case -1 => KeyBinding(hd, -1, aliases, desc) - case idx => KeyBinding(hd drop idx + 1, hd take idx toInt, aliases, desc) - } - kb :: loop(tl) - } - } - // This is verrrrrrrry specific to the current contents - // of the keybindings.properties in jline. - loop(bindings split "\\n" map (_.trim) dropWhile (_ != "") filterNot (_ == "") toList) sortBy (_.code) - } -} 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/ProductCompletion.scala b/src/compiler/scala/tools/nsc/interpreter/ProductCompletion.scala deleted file mode 100644 index dc4582eb17..0000000000 --- a/src/compiler/scala/tools/nsc/interpreter/ProductCompletion.scala +++ /dev/null @@ -1,44 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.nsc -package interpreter - -class SeqCompletion[T](elems: Seq[T]) extends CompletionAware { - lazy val completions = elems.indices.toList map ("(%d)" format _) - def completions(verbosity: Int) = completions - private def elemAt(name: String) = - if (completions contains name) Some(elems(name drop 1 dropRight 1 toInt)) else None - - override def execute(name: String) = elemAt(name) - override def follow(name: String) = elemAt(name) map (x => ProductCompletion(x)) -} - -/** TODO - deal with non-case products by giving them _1 _2 etc. */ -class ProductCompletion(root: Product) extends CompletionAware { - lazy val caseFields: List[Any] = root.productIterator.toList - lazy val caseNames: List[String] = ByteCode caseParamNamesForPath root.getClass.getName getOrElse Nil - private def isValid = caseFields.length == caseNames.length - - private def fieldForName(s: String) = (completions indexOf s) match { - case idx if idx > -1 && isValid => Some(caseFields(idx)) - case _ => None - } - - lazy val completions = caseNames - def completions(verbosity: Int) = completions - override def execute(name: String) = fieldForName(name) - override def follow(name: String) = fieldForName(name) map (x => ProductCompletion(x)) -} - -object ProductCompletion { - /** TODO: other traversables. */ - def apply(elem: Any): CompletionAware = elem match { - case x: Seq[_] => new SeqCompletion[Any](x) - case x: Product => new ProductCompletion(x) - // case x: Map[_, _] => - case _ => CompletionAware.Empty - } -} 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/ReplStrings.scala b/src/compiler/scala/tools/nsc/interpreter/ReplStrings.scala index 175f6263ad..0c9f4fcd47 100644 --- a/src/compiler/scala/tools/nsc/interpreter/ReplStrings.scala +++ b/src/compiler/scala/tools/nsc/interpreter/ReplStrings.scala @@ -11,15 +11,6 @@ import scala.PartialFunction.cond import scala.reflect.internal.Chars trait ReplStrings { - // Longest common prefix - def longestCommonPrefix(xs: List[String]): String = { - if (xs.isEmpty || xs.contains("")) "" - else xs.head.head match { - case ch => - if (xs.tail forall (_.head == ch)) "" + ch + longestCommonPrefix(xs map (_.tail)) - else "" - } - } /** Convert a string into code that can recreate the string. * This requires replacing all special characters by escape * codes. It does not add the surrounding " marks. */ 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/Runner.scala b/src/compiler/scala/tools/nsc/interpreter/Runner.scala deleted file mode 100644 index f9f75da3c6..0000000000 --- a/src/compiler/scala/tools/nsc/interpreter/Runner.scala +++ /dev/null @@ -1,11 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.nsc -package interpreter - -object Runner { - def main(args: Array[String]): Unit = new ILoop process args -} diff --git a/src/compiler/scala/tools/nsc/interpreter/SimpleReader.scala b/src/compiler/scala/tools/nsc/interpreter/SimpleReader.scala index 992bef8056..a57b047bc0 100644 --- a/src/compiler/scala/tools/nsc/interpreter/SimpleReader.scala +++ b/src/compiler/scala/tools/nsc/interpreter/SimpleReader.scala @@ -18,7 +18,6 @@ extends InteractiveReader { val history = NoHistory val completion = NoCompletion - val keyBindings: List[KeyBinding] = Nil def init() = () def reset() = () diff --git a/src/compiler/scala/tools/nsc/interpreter/XMLCompletion.scala b/src/compiler/scala/tools/nsc/interpreter/XMLCompletion.scala deleted file mode 100644 index 9979814afb..0000000000 --- a/src/compiler/scala/tools/nsc/interpreter/XMLCompletion.scala +++ /dev/null @@ -1,44 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.nsc -package interpreter - -import xml.{ XML, Group, Node, NodeSeq } -import XMLCompletion._ -import scala.collection.{ mutable, immutable } - -class XMLCompletion(root: Node) extends CompletionAware { - private val nodeCache = new mutable.HashMap[String, Node] - private def getNode(s: String): Option[Node] = { - completions // make sure cache is populated - nodeCache get s - } - - lazy val completions: List[String] = { - def children = root.child.toList - def uniqueTags = children groupBy (_.label) filter (_._2.size == 1) map (_._1) - val uniqs = uniqueTags.toList - - children.foldLeft(List[String]())((res, node) => { - val name = node.label - def count = res filter (_ startsWith (name + "[")) size // ] - val suffix = if (uniqs contains name) "" else "[%d]" format (count + 1) - val s = name + suffix - - nodeCache(s) = node - - s :: res - }).sorted - } - def completions(verbosity: Int) = completions - - override def execute(id: String) = getNode(id) - override def follow(id: String) = getNode(id) map (x => new XMLCompletion(x)) -} - -object XMLCompletion { - def apply(x: Node) = new XMLCompletion(x) -} 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/ClassAndJarInfo.scala b/src/compiler/scala/tools/nsc/io/ClassAndJarInfo.scala deleted file mode 100644 index c9ed535841..0000000000 --- a/src/compiler/scala/tools/nsc/io/ClassAndJarInfo.scala +++ /dev/null @@ -1,44 +0,0 @@ -/* NSC -- new Scala compiler - * Copyright 2005-2011 LAMP/EPFL - * @author Paul Phillips - */ - -package scala.tools.nsc -package io - -import java.net.{ URL, URLClassLoader } -import java.io.IOException -import collection.JavaConverters._ - -/** A convenience class for finding the jar with the bytecode for - * a given Class object and similar common tasks. - */ -class ClassAndJarInfo[T: ClassTag] { - val tag = classTag[T] - def clazz = tag.erasure - def internalName = clazz.getName.replace('.', '/') - - def resourceURL = new URLClassLoader(Array[URL]()) getResource internalName + ".class" - - def baseOfPath(path: String) = path indexOf '!' match { - case -1 => path stripSuffix internalName + ".class" - case idx => path take idx - } - - def simpleClassName = clazz.getName split """[$.]""" last - def classUrl = clazz getResource simpleClassName + ".class" - def codeSource = protectionDomain.getCodeSource() - def jarManifest = ( - try new JManifest(jarManifestUrl.openStream()) - catch { case _: IOException => new JManifest() } - ) - def jarManifestMainAttrs = jarManifest.getMainAttributes().asScala - def jarManifestUrl = new URL(baseOfPath("" + classUrl) + "!/META-INF/MANIFEST.MF") - def locationFile = File(locationUrl.toURI.getPath()) - def locationUrl = if (codeSource == null) new URL("file:///") else codeSource.getLocation() - def protectionDomain = clazz.getProtectionDomain() - def rootClasspath = rootPossibles find (_.exists) - def rootFromLocation = Path(locationUrl.toURI.getPath()) - def rootFromResource = Path(baseOfPath(classUrl.getPath) stripPrefix "file:") - def rootPossibles = Iterator(rootFromResource, rootFromLocation) -} 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/package.scala b/src/compiler/scala/tools/nsc/package.scala index a908062b2f..88d600c113 100644 --- a/src/compiler/scala/tools/nsc/package.scala +++ b/src/compiler/scala/tools/nsc/package.scala @@ -6,11 +6,6 @@ package scala.tools package object nsc { - @deprecated("Use a class in the scala.tools.nsc.interpreter package.", "2.9.0") - type InterpreterSettings = interpreter.ISettings - @deprecated("Use a class in the scala.tools.nsc.interpreter package.", "2.9.0") - val InterpreterResults = interpreter.Results - type Phase = scala.reflect.internal.Phase val NoPhase = scala.reflect.internal.NoPhase 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/transform/ExplicitOuter.scala b/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala index 8daad8a2ac..9cffb6a1e1 100644 --- a/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala +++ b/src/compiler/scala/tools/nsc/transform/ExplicitOuter.scala @@ -149,7 +149,7 @@ abstract class ExplicitOuter extends InfoTransform if (sym.owner.isTrait && ((sym hasFlag (ACCESSOR | SUPERACCESSOR)) || sym.isModule)) { // 5 sym.makeNotPrivate(sym.owner) } - if (sym.owner.isTrait) sym setNotFlag PROTECTED // 6 + if (sym.owner.isTrait && sym.isProtected) sym setFlag notPROTECTED // 6 if (sym.isClassConstructor && isInner(sym.owner)) { // 1 val p = sym.newValueParameter(innerClassConstructorParamName, sym.pos) .setInfo(sym.owner.outerClass.thisType) @@ -448,8 +448,8 @@ abstract class ExplicitOuter extends InfoTransform override def transform(tree: Tree): Tree = { val sym = tree.symbol if (sym != null && sym.isType) { //(9) - sym setNotFlag PRIVATE - sym setNotFlag PROTECTED + if (sym.isPrivate) sym setFlag notPRIVATE + if (sym.isProtected) sym setFlag notPROTECTED } tree match { case Template(parents, self, decls) => 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/ClassPath.scala b/src/compiler/scala/tools/nsc/util/ClassPath.scala index 48ec941b50..404490bd49 100644 --- a/src/compiler/scala/tools/nsc/util/ClassPath.scala +++ b/src/compiler/scala/tools/nsc/util/ClassPath.scala @@ -9,7 +9,7 @@ package util import java.net.URL import scala.collection.{ mutable, immutable } -import io.{ File, Directory, Path, Jar, AbstractFile, ClassAndJarInfo } +import io.{ File, Directory, Path, Jar, AbstractFile } import scala.tools.util.StringOps.splitWhere import Jar.isJarOrZip import File.pathSeparator @@ -23,16 +23,6 @@ import java.net.MalformedURLException * @author Stepan Koltsov */ object ClassPath { - def scalaLibrary = locate[Option[_]] - def scalaCompiler = locate[Global] - - def infoFor[T](value: T) = info(value.getClass) - def info[T](clazz: Class[T]) = new ClassAndJarInfo()(ClassTag[T](clazz)) - def info[T: ClassTag] = new ClassAndJarInfo[T] - def locate[T: ClassTag] = info[T].rootClasspath - def locateJar[T: ClassTag] = info[T].rootPossibles find (x => isJarOrZip(x)) map (x => File(x)) - def locateDir[T: ClassTag] = info[T].rootPossibles find (_.isDirectory) map (_.toDirectory) - /** Expand single path entry */ private def expandS(pattern: String): List[String] = { val wildSuffix = File.separator + "*" @@ -54,26 +44,6 @@ object ClassPath { else List(pattern) } - /** Return duplicated classpath entries as - * (name, list of origins) - * in the order they occur on the path. - */ - // def findDuplicates(cp: ClassPath[_]) = { - // def toFullName(x: (String, _, cp.AnyClassRep)) = x._1 + "." + x._3.name - // def toOriginString(x: ClassPath[_]) = x.origin getOrElse x.name - // - // /** Flatten everything into tuples, recombine grouped by name, filter down to 2+ entries. */ - // val flattened = ( - // for ((pkgName, pkg) <- cp.allPackagesWithNames ; clazz <- pkg.classes) yield - // (pkgName, pkg, clazz) - // ) - // val multipleAppearingEntries = flattened groupBy toFullName filter (_._2.size > 1) - // - // /** Extract results. */ - // for (name <- flattened map toFullName distinct ; dups <- multipleAppearingEntries get name) yield - // (name, dups map { case (_, cp, _) => toOriginString(cp) }) - // } - /** Split classpath using platform-dependent path separator */ def split(path: String): List[String] = (path split pathSeparator).toList filterNot (_ == "") distinct @@ -240,26 +210,6 @@ abstract class ClassPath[T] { def packages: IndexedSeq[ClassPath[T]] def sourcepaths: IndexedSeq[AbstractFile] - /** Information which entails walking the tree. This is probably only - * necessary for tracking down problems - it's normally not used. - */ - // def allPackages: List[ClassPath[T]] = packages ::: (packages flatMap (_.allPackages)) - // def allPackageNames: List[String] = { - // def subpackages(prefix: String, cp: ClassPath[T]): List[String] = ( - // (cp.packages map (prefix + _.name)) ::: - // (cp.packages flatMap (x => subpackages(prefix + x.name + ".", x))) - // ) - // subpackages("", this) - // } - // def allPackagesWithNames: List[(String, ClassPath[T])] = { - // val root = packages map (p => p.name -> p) - // val subs = - // for ((prefix, p) <- root ; (k, v) <- p.allPackagesWithNames) yield - // (prefix + "." + k, v) - // - // root ::: subs - // } - /** * Represents classes which can be loaded with a ClassfileLoader/MsilFileLoader * and / or a SourcefileLoader. @@ -431,41 +381,10 @@ extends ClassPath[T] { } new MergedClassPath[T](newEntries, context) } - // - // override def allPackages: List[ClassPath[T]] = entries flatMap (_.allPackages) - // override def allPackageNames = entries flatMap (_.allPackageNames) - // override def allPackagesWithNames = entries flatMap (_.allPackagesWithNames) - // - // def duplicatedClasses = { - // def toFullName(x: (String, _, AnyClassRep)) = x._1 + "." + x._3.name - // - // /** Flatten everything into tuples, recombine grouped by name, filter down to 2+ entries. */ - // val flattened = ( - // for ((pkgName, pkg) <- allPackagesWithNames ; clazz <- pkg.classes) yield - // (pkgName, pkg, clazz) - // ) - // val multipleAppearingEntries = flattened groupBy toFullName filter (_._2.size > 1) - // - // /** Using original name list as reference point, return duplicated entries as - // * (name, list of origins) - // * in the order they occur on the path. - // */ - // for (name <- flattened map toFullName distinct ; dups <- multipleAppearingEntries get name) yield - // (name, dups map { - // case (_, cp, _) if cp.origin.isDefined => cp.origin.get - // case (_, cp, _) => cp.asURLs.mkString - // }) - // } - // def show() { println("ClassPath %s has %d entries and results in:\n".format(name, entries.size)) asClasspathString split ':' foreach (x => println(" " + x)) } - // def showDuplicates() = - // ClassPath findDuplicates this foreach { - // case (name, xs) => println(xs.mkString(name + ":\n ", "\n ", "\n")) - // } - // override def toString() = "merged classpath "+ entries.mkString("(", "\n", ")") } 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..4c7920d6b3 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] } @@ -26,14 +24,6 @@ trait HasClassPath { * of java reflection. */ trait ScalaClassLoader extends JClassLoader { - /** Override to see classloader activity traced */ - protected def trace: Boolean = false - protected lazy val classLoaderUniqueId = "Cl#" + System.identityHashCode(this) - protected def classLoaderLog(msg: => String) { - if (trace) - Console.err.println("[" + classLoaderUniqueId + "] " + msg) - } - /** Executing an action with this classloader as context classloader */ def asContext[T](action: => T): T = { val saved = contextLoader @@ -55,18 +45,6 @@ trait ScalaClassLoader extends JClassLoader { def create(path: String): AnyRef = tryToInitializeClass[AnyRef](path) map (_.newInstance()) orNull - override def findClass(name: String) = { - val result = super.findClass(name) - classLoaderLog("findClass(%s) = %s".format(name, result)) - result - } - - override def loadClass(name: String, resolve: Boolean) = { - val result = super.loadClass(name, resolve) - classLoaderLog("loadClass(%s, %s) = %s".format(name, resolve, result)) - result - } - def constructorsOf[T <: AnyRef : ClassTag]: List[Constructor[T]] = classTag[T].erasure.getConstructors.toList map (_.asInstanceOf[Constructor[T]]) @@ -100,7 +78,6 @@ trait ScalaClassLoader extends JClassLoader { case null => Nil case p => p.loaderChain }) - override def toString = classLoaderUniqueId } /** Methods for obtaining various classloaders. @@ -173,7 +150,7 @@ object ScalaClassLoader { classloaderURLs :+= url super.addURL(url) } - def toLongString = urls.mkString("URLClassLoader(id=" + classLoaderUniqueId + "\n ", "\n ", "\n)\n") + def toLongString = urls.mkString("URLClassLoader(\n ", "\n ", "\n)\n") } def fromURLs(urls: Seq[URL], parent: ClassLoader = null): URLClassLoader = 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/Enumeration.scala b/src/library/scala/Enumeration.scala index ea0d20957d..2b658ee4f7 100644 --- a/src/library/scala/Enumeration.scala +++ b/src/library/scala/Enumeration.scala @@ -113,8 +113,8 @@ abstract class Enumeration (initial: Int) extends Serializable { * enumeration, but no higher than 0. */ private var bottomId = if(initial < 0) initial else 0 - /** The highest integer amongst those used to identify values in this - * enumeration. */ + /** The one higher than the highest integer amongst those used to identify + * values in this enumeration. */ final def maxId = topId /** The value of this enumeration with given id `x` diff --git a/src/library/scala/collection/interfaces/IterableMethods.scala b/src/library/scala/collection/interfaces/IterableMethods.scala deleted file mode 100644 index 8efc3fe6f9..0000000000 --- a/src/library/scala/collection/interfaces/IterableMethods.scala +++ /dev/null @@ -1,38 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2011, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.collection -package interfaces - -import generic._ -import mutable.Buffer -import annotation.unchecked.uncheckedVariance - -/** - * @since 2.8 - */ -trait IterableMethods[+A, +This <: IterableLike[A, This] with Iterable[A]] extends TraversableMethods[A, This] { - self: Iterable[A] => - - // abstract - def iterator: Iterator[A] - - // concrete - def dropRight(n: Int): Iterable[A] - def grouped(size: Int): Iterator[Iterable[A]] - def sameElements[B >: A](that: GenIterable[B]): Boolean - def sliding(size: Int): Iterator[Iterable[A]] - def sliding(size: Int, step: Int): Iterator[Iterable[A]] - def takeRight(n: Int): Iterable[A] - def zipAll[B, A1 >: A, That](that: GenIterable[B], e1: A1, e2: B)(implicit bf: CanBuildFrom[This, (A1, B), That]): That - def zipWithIndex[A1 >: A, That](implicit bf: CanBuildFrom[This, (A1, Int), That]): That - def zip[A1 >: A, B, That](that: GenIterable[B])(implicit bf: CanBuildFrom[This, (A1, B), That]): That - - override def view: IterableView[A, This] - override def view(from: Int, until: Int): IterableView[A, This] -} diff --git a/src/library/scala/collection/interfaces/MapMethods.scala b/src/library/scala/collection/interfaces/MapMethods.scala deleted file mode 100644 index bc38ccdd2e..0000000000 --- a/src/library/scala/collection/interfaces/MapMethods.scala +++ /dev/null @@ -1,45 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2011, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.collection -package interfaces - -import generic._ - -/** - * @since 2.8 - */ -trait MapMethods[A, +B, +This <: MapLike[A, B, This] with Map[A, B]] - extends IterableMethods[(A, B), This] - with SubtractableMethods[A, This] { - self: Map[A, B] => - - // abstract - def empty: This - def get(key: A): Option[B] - def iterator: Iterator[(A, B)] - def + [B1 >: B] (kv: (A, B1)): Map[A, B1] - def - (key: A): This - - // concrete - def getOrElse[B1 >: B](key: A, default: => B1): B1 - def apply(key: A): B - def contains(key: A): Boolean - def isDefinedAt(key: A): Boolean - def keys: Iterable[A] - def keysIterator: Iterator[A] - def keySet: Set[A] - def values: Iterable[B] - def valuesIterator: Iterator[B] - def default(key: A): B - def filterKeys(p: A => Boolean): Map[A, B] - def mapValues[C](f: B => C): Map[A, C] - def updated [B1 >: B](key: A, value: B1): Map[A, B1] - def + [B1 >: B] (elem1: (A, B1), elem2: (A, B1), elems: (A, B1) *): Map[A, B1] - def ++[B1 >: B](xs: GenTraversableOnce[(A, B1)]): Map[A, B1] -} diff --git a/src/library/scala/collection/interfaces/SeqMethods.scala b/src/library/scala/collection/interfaces/SeqMethods.scala deleted file mode 100644 index 4327073d21..0000000000 --- a/src/library/scala/collection/interfaces/SeqMethods.scala +++ /dev/null @@ -1,70 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2011, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.collection -package interfaces - -import generic._ -import mutable.Buffer - -/** - * @since 2.8 - */ -trait SeqMethods[+A, +This <: SeqLike[A, This] with Seq[A]] extends IterableMethods[A, This] { - self: Seq[A] => - - // abstract - def apply(idx: Int): A - def length: Int - - // concrete - def +:[B >: A, That](elem: B)(implicit bf: CanBuildFrom[This, B, That]): That - def :+[B >: A, That](elem: B)(implicit bf: CanBuildFrom[This, B, That]): That - def combinations(n: Int): Iterator[This] - def contains(elem: Any): Boolean - def containsSlice[B](that: Seq[B]): Boolean - def corresponds[B](that: Seq[B])(p: (A,B) => Boolean): Boolean - def diff[B >: A, That](that: Seq[B]): This - def distinct: This - def endsWith[B](that: Seq[B]): Boolean - def indexOfSlice[B >: A](that: Seq[B]): Int - def indexOfSlice[B >: A](that: Seq[B], fromIndex: Int): Int - def indexOf[B >: A](elem: B): Int - def indexOf[B >: A](elem: B, from: Int): Int - def indexWhere(p: A => Boolean): Int - def indexWhere(p: A => Boolean, from: Int): Int - def indices: Range - def intersect[B >: A, That](that: Seq[B]): This - def isDefinedAt(x: Int): Boolean - def lastIndexOfSlice[B >: A](that: Seq[B]): Int - def lastIndexOfSlice[B >: A](that: Seq[B], fromIndex: Int): Int - def lastIndexOf[B >: A](elem: B): Int - def lastIndexOf[B >: A](elem: B, end: Int): Int - def lastIndexWhere(p: A => Boolean): Int - def lastIndexWhere(p: A => Boolean, end: Int): Int - def lengthCompare(len: Int): Int - def padTo[B >: A, That](len: Int, elem: B)(implicit bf: CanBuildFrom[This, B, That]): That - def patch[B >: A, That](from: Int, patch: GenSeq[B], replaced: Int)(implicit bf: CanBuildFrom[This, B, That]): That - def permutations: Iterator[This] - def prefixLength(p: A => Boolean): Int - def reverse: This - def reverseIterator: Iterator[A] - def reverseMap[B, That](f: A => B)(implicit bf: CanBuildFrom[This, B, That]): That - def segmentLength(p: A => Boolean, from: Int): Int - def sortBy[B](f: A => B)(implicit ord: Ordering[B]): This - def sortWith(lt: (A, A) => Boolean): This - def sorted[B >: A](implicit ord: Ordering[B]): This - def startsWith[B](that: Seq[B]): Boolean - def startsWith[B](that: Seq[B], offset: Int): Boolean - def union[B >: A, That](that: Seq[B])(implicit bf: CanBuildFrom[This, B, That]): That - def updated[B >: A, That](index: Int, elem: B)(implicit bf: CanBuildFrom[This, B, That]): That - - // refinements - def view: SeqView[A, This] - def view(from: Int, until: Int): SeqView[A, This] -} diff --git a/src/library/scala/collection/interfaces/SetMethods.scala b/src/library/scala/collection/interfaces/SetMethods.scala deleted file mode 100644 index 3b6214f45c..0000000000 --- a/src/library/scala/collection/interfaces/SetMethods.scala +++ /dev/null @@ -1,51 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2011, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.collection -package interfaces - -import generic._ -import mutable.Buffer -import annotation.unchecked.uncheckedVariance - -/** - * @since 2.8 - */ -trait SubtractableMethods[A, +This <: Subtractable[A, This]] { - def -(elem: A): This - def -(elem1: A, elem2: A, elems: A*): This - def --(xs: TraversableOnce[A]): This -} - -/** - * @since 2.8 - */ -trait SetMethods[A, +This <: SetLike[A, This] with Set[A]] - extends IterableMethods[A, This] - with SubtractableMethods[A, This] { - self: Set[A] => - - // abstract - def empty: This - def contains(elem: A): Boolean - def + (elem: A): This - def - (elem: A): This - - // concrete - def & (that: Set[A]): This - def &~ (that: Set[A]): This - def + (elem1: A, elem2: A, elems: A*): This - def apply(elem: A): Boolean - def diff(that: Set[A]): This - def intersect(that: Set[A]): This - def subsetOf(that: Set[A]): Boolean - def subsets(len: Int): Iterator[This] - def subsets: Iterator[This] - def union(that: Set[A]): This - def | (that: Set[A]): This -} diff --git a/src/library/scala/collection/interfaces/TraversableMethods.scala b/src/library/scala/collection/interfaces/TraversableMethods.scala deleted file mode 100644 index 8aba39093d..0000000000 --- a/src/library/scala/collection/interfaces/TraversableMethods.scala +++ /dev/null @@ -1,63 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2011, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.collection -package interfaces - -import generic._ - -/** - * @since 2.8 - */ -trait TraversableMethods[+A, +This <: TraversableLike[A, This]] extends TraversableOnceMethods[A] { - self: Traversable[A] => - - // maps/iteration - def flatMap[B, That](f: A => GenTraversableOnce[B])(implicit bf: CanBuildFrom[This, B, That]): That - def map[B, That](f: A => B)(implicit bf: CanBuildFrom[This, B, That]): That - def collect[B, That](pf: PartialFunction[A, B])(implicit bf: CanBuildFrom[This, B, That]): That - def scanLeft[B, That](z: B)(op: (B, A) => B)(implicit bf: CanBuildFrom[This, B, That]): That - def scanRight[B, That](z: B)(op: (A, B) => B)(implicit bf: CanBuildFrom[This, B, That]): That - - // new collections - def ++:[B >: A, That](that: TraversableOnce[B])(implicit bf: CanBuildFrom[This, B, That]): That - def ++[B >: A, That](that: GenTraversableOnce[B])(implicit bf: CanBuildFrom[This, B, That]): That - - // element retrieval - def head: A - def headOption: Option[A] - def last: A - def lastOption: Option[A] - - // subcollections - def drop(n: Int): Traversable[A] - def dropWhile(p: A => Boolean): Traversable[A] - def filter(p: A => Boolean): Traversable[A] - def filterNot(p: A => Boolean): Traversable[A] - def init: Traversable[A] - def inits: Iterator[This] - def slice(from: Int, until: Int): Traversable[A] - def tail: Traversable[A] - def tails: Iterator[This] - def take(n: Int): Traversable[A] - def takeWhile(p: A => Boolean): Traversable[A] - def withFilter(p: A => Boolean): FilterMonadic[A, Traversable[A]] - - // subdivisions - def groupBy[K](f: A => K): Map[K, Traversable[A]] - def partition(p: A => Boolean): (Traversable[A], Traversable[A]) - def span(p: A => Boolean): (Traversable[A], Traversable[A]) - def splitAt(n: Int): (Traversable[A], Traversable[A]) - - // info - def stringPrefix: String - - // views - def view: TraversableView[A, This] - def view(from: Int, until: Int): TraversableView[A, This] -} diff --git a/src/library/scala/collection/interfaces/TraversableOnceMethods.scala b/src/library/scala/collection/interfaces/TraversableOnceMethods.scala deleted file mode 100644 index 543d59d118..0000000000 --- a/src/library/scala/collection/interfaces/TraversableOnceMethods.scala +++ /dev/null @@ -1,77 +0,0 @@ -/* __ *\ -** ________ ___ / / ___ Scala API ** -** / __/ __// _ | / / / _ | (c) 2003-2011, LAMP/EPFL ** -** __\ \/ /__/ __ |/ /__/ __ | http://scala-lang.org/ ** -** /____/\___/_/ |_/____/_/ | | ** -** |/ ** -\* */ - -package scala.collection -package interfaces - -trait TraversableOnceMethods[+A] { - self: TraversableOnce[A] => - - def foreach[U](f: A => U): Unit - def size: Int - protected[this] def reversed: TraversableOnce[A] - - // tests - def hasDefiniteSize: Boolean - def isEmpty: Boolean - def isTraversableAgain: Boolean - def nonEmpty: Boolean - - // applying a predicate - def collectFirst[B](pf: PartialFunction[A, B]): Option[B] - def count(p: A => Boolean): Int - def exists(p: A => Boolean): Boolean - def find(p: A => Boolean): Option[A] - def forall(p: A => Boolean): Boolean - - // folds - def /:[B](z: B)(op: (B, A) => B): B - def :\[B](z: B)(op: (A, B) => B): B - def foldLeft[B](z: B)(op: (B, A) => B): B - def foldRight[B](z: B)(op: (A, B) => B): B - def reduceLeftOption[B >: A](op: (B, A) => B): Option[B] - def reduceLeft[B >: A](op: (B, A) => B): B - def reduceRightOption[B >: A](op: (A, B) => B): Option[B] - def reduceRight[B >: A](op: (A, B) => B): B - - // copies - def copyToArray[B >: A](xs: Array[B]): Unit - def copyToArray[B >: A](xs: Array[B], start: Int): Unit - def copyToArray[B >: A](xs: Array[B], start: Int, len: Int): Unit - def copyToBuffer[B >: A](dest: mutable.Buffer[B]): Unit - - // conversions - def toArray[B >: A : ArrayTag]: Array[B] - def toBuffer[B >: A]: mutable.Buffer[B] - def toIndexedSeq: immutable.IndexedSeq[A] - def toIterable: Iterable[A] - def toIterator: Iterator[A] - def toList: List[A] - def toMap[T, U](implicit ev: A <:< (T, U)): immutable.Map[T, U] - def toSeq: Seq[A] - def toSet[B >: A]: immutable.Set[B] - def toStream: Stream[A] - def toTraversable: Traversable[A] - - // type-constrained folds - def maxBy[B](f: A => B)(implicit cmp: Ordering[B]): A - def max[B >: A](implicit cmp: Ordering[B]): A - def minBy[B](f: A => B)(implicit cmp: Ordering[B]): A - def min[B >: A](implicit cmp: Ordering[B]): A - def product[B >: A](implicit num: Numeric[B]): B - def sum[B >: A](implicit num: Numeric[B]): B - - // strings - def mkString(start: String, sep: String, end: String): String - def mkString(sep: String): String - def mkString: String - - def addString(buf: StringBuilder, start: String, sep: String, end: String): StringBuilder - def addString(buf: StringBuilder, sep: String): StringBuilder - def addString(buf: StringBuilder): StringBuilder -} 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 -} |