summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authormichelou <michelou@epfl.ch>2006-07-19 12:56:02 +0000
committermichelou <michelou@epfl.ch>2006-07-19 12:56:02 +0000
commitd21d4888b3e9dd39dd9c4460e7ced2a93a9fff77 (patch)
treeffdef2cdbc0feb9203ff5c5469bc1119c1000673
parentab1b3687202bdce0824a7f567b32c7a4a406f1a0 (diff)
downloadscala-d21d4888b3e9dd39dd9c4460e7ced2a93a9fff77.tar.gz
scala-d21d4888b3e9dd39dd9c4460e7ced2a93a9fff77.tar.bz2
scala-d21d4888b3e9dd39dd9c4460e7ced2a93a9fff77.zip
removed leading/trailing tabs/blanks, added hea...
removed leading/trailing tabs/blanks, added headers and comments
-rw-r--r--src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala452
-rw-r--r--src/compiler/scala/tools/nsc/ast/TreeInfo.scala10
-rw-r--r--src/compiler/scala/tools/nsc/symtab/classfile/ClassfileConstants.scala99
-rw-r--r--src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala101
-rw-r--r--src/compiler/scala/tools/nsc/symtab/classfile/MetaParser.scala113
-rw-r--r--src/compiler/scala/tools/nsc/symtab/classfile/PickleBuffer.scala89
-rw-r--r--src/compiler/scala/tools/nsc/symtab/classfile/PickleFormat.scala100
-rw-r--r--src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala292
-rw-r--r--src/compiler/scala/tools/nsc/symtab/classfile/SymblfileParser.scala31
-rw-r--r--src/compiler/scala/tools/nsc/symtab/classfile/UnPickler.scala210
-rw-r--r--src/compiler/scala/tools/util/AbstractTimer.scala32
-rw-r--r--src/compiler/scala/tools/util/SocketConnection.scala24
-rw-r--r--src/compiler/scala/tools/util/SocketServer.scala30
-rw-r--r--src/compiler/scala/tools/util/StringOps.scala21
-rw-r--r--src/compiler/scala/tools/util/UTF8Codec.scala81
15 files changed, 892 insertions, 793 deletions
diff --git a/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala b/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala
index 2a91c9a131..2d082b4b83 100644
--- a/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala
+++ b/src/compiler/scala/tools/nsc/ast/TreeBrowsers.scala
@@ -1,46 +1,49 @@
-/* NSC -- new scala compiler
- * Copyright 2005 LAMP/EPFL
+/* NSC -- new Scala compiler
+ * Copyright 2005-2006 LAMP/EPFL
* @author Martin Odersky
*/
// $Id$
-package scala.tools.nsc.ast;
-import scala.concurrent._;
-import symtab.Flags._;
+package scala.tools.nsc.ast
+import scala.concurrent._
+import symtab.Flags._
-import java.lang.Math;
-import java.util.HashMap;
-import java.io.StringWriter;
+import java.lang.Math
+import java.util.HashMap
+import java.io.StringWriter
-import javax.swing.tree._;
-import javax.swing.event.TreeModelListener;
-import javax.swing._;
+import javax.swing.tree._
+import javax.swing.event.TreeModelListener
+import javax.swing._
-import java.awt.BorderLayout;
-import java.awt.{List => awtList, _};
-import java.awt.event._;
+import java.awt.BorderLayout
+import java.awt.{List => awtList, _}
+import java.awt.event._
-import scala.text._;
+import scala.text._
/**
* Tree browsers can show the AST in a graphical and interactive
* way, useful for debugging and understanding.
+ *
+ * @author Martin Odersky
+ * @version 1.0
*/
abstract class TreeBrowsers {
- val global: Global;
- import global._;
- import nme.EMPTY;
+ val global: Global
+ import global._
+ import nme.EMPTY
/** Pseudo tree class, so that all JTree nodes are treated uniformly */
case class ProgramTree(units: List[UnitTree]) extends Tree {
- override def toString(): String = "Program";
+ override def toString(): String = "Program"
}
/** Pseudo tree class, so that all JTree nodes are treated uniformly */
case class UnitTree(unit: CompilationUnit) extends Tree {
- override def toString(): String = unit.toString();
+ override def toString(): String = unit.toString()
}
def create(): SwingBrowser = new SwingBrowser();
@@ -51,99 +54,100 @@ abstract class TreeBrowsers {
class SwingBrowser {
def browse(t: Tree): Unit = {
- val phase: Phase = globalPhase;
+ val phase: Phase = globalPhase
- val tm = new ASTTreeModel(t);
+ val tm = new ASTTreeModel(t)
- val frame = new BrowserFrame();
- frame.setTreeModel(tm);
+ val frame = new BrowserFrame()
+ frame.setTreeModel(tm)
- val lock = new Lock();
- frame.createFrame(lock);
+ val lock = new Lock()
+ frame.createFrame(lock)
// wait for the frame to be closed
- lock.acquire;
+ lock.acquire
}
def browse(units: Iterator[CompilationUnit]): Unit =
- browse(units.toList);
+ browse(units.toList)
/** print the whole program */
def browse(units: List[CompilationUnit]): Unit = {
- val phase: Phase = globalPhase;
- var unitList: List[UnitTree] = Nil;
-
+ val phase: Phase = globalPhase
+ var unitList: List[UnitTree] = Nil
for (val i <- units)
- unitList = UnitTree(i) :: unitList;
- val tm = new ASTTreeModel(ProgramTree(unitList));
+ unitList = UnitTree(i) :: unitList
+ val tm = new ASTTreeModel(ProgramTree(unitList))
- val frame = new BrowserFrame();
- frame.setTreeModel(tm);
+ val frame = new BrowserFrame()
+ frame.setTreeModel(tm)
- val lock = new Lock();
- frame.createFrame(lock);
+ val lock = new Lock()
+ frame.createFrame(lock)
// wait for the frame to be closed
- lock.acquire;
+ lock.acquire
}
}
/** Tree model for abstract syntax trees */
class ASTTreeModel(val program: Tree) extends TreeModel {
- var listeners: List[TreeModelListener] = Nil;
+ var listeners: List[TreeModelListener] = Nil
/** Add a listener to this tree */
- def addTreeModelListener(l : TreeModelListener): Unit = listeners = l :: listeners;
+ def addTreeModelListener(l: TreeModelListener): Unit =
+ listeners = l :: listeners
/** Return the index'th child of parent */
- def getChild(parent: Any, index: Int): AnyRef = {
- packChildren(parent).drop(index).head;
- }
+ def getChild(parent: Any, index: Int): AnyRef =
+ packChildren(parent).drop(index).head
/** Return the number of children this 'parent' has */
def getChildCount(parent: Any): Int =
- packChildren(parent).length;
+ packChildren(parent).length
/** Return the index of the given child */
def getIndexOfChild(parent: Any, child: Any): Int =
- packChildren(parent).dropWhile(c => c != child).length;
+ packChildren(parent).dropWhile(c => c != child).length
/** Return the root node */
- def getRoot(): AnyRef = program;
+ def getRoot(): AnyRef = program
/** Test whether the given node is a leaf */
- def isLeaf(node: Any): Boolean = packChildren(node).length == 0;
+ def isLeaf(node: Any): Boolean = packChildren(node).length == 0
def removeTreeModelListener(l: TreeModelListener): Unit =
- listeners remove (x => x == l);
+ listeners remove (x => x == l)
/** we ignore this message for now */
- def valueForPathChanged(path: TreePath, newValue: Any) = ();
+ def valueForPathChanged(path: TreePath, newValue: Any) = ()
/**
* Return a list of children for the given node.
*/
def packChildren(t: Any): List[AnyRef] =
- TreeInfo.children(t.asInstanceOf[Tree]);
+ TreeInfo.children(t.asInstanceOf[Tree])
}
/**
* A window that can host the Tree widget and provide methods for
* displaying information
+ *
+ * @author Iulian Dragos
+ * @version 1.0
*/
class BrowserFrame {
- val frame = new JFrame("Scala AST");
- val topLeftPane = new JPanel(new BorderLayout());
- val topRightPane = new JPanel(new BorderLayout());
- val bottomPane = new JPanel(new BorderLayout());
- var splitPane: JSplitPane = _;
- var treeModel: TreeModel = _;
-
- val textArea: JTextArea = new JTextArea(20, 50);
- val infoPanel = new TextInfoPanel();
+ val frame = new JFrame("Scala AST")
+ val topLeftPane = new JPanel(new BorderLayout())
+ val topRightPane = new JPanel(new BorderLayout())
+ val bottomPane = new JPanel(new BorderLayout())
+ var splitPane: JSplitPane = _
+ var treeModel: TreeModel = _
+ val textArea: JTextArea = new JTextArea(20, 50)
+ val infoPanel = new TextInfoPanel()
/** Create a frame that displays the AST.
*
@@ -154,53 +158,52 @@ abstract class TreeBrowsers {
* especially symbols/types would change while the window is visible.
*/
def createFrame(lock: Lock): Unit = {
- lock.acquire; // keep the lock until the user closes the window
+ lock.acquire // keep the lock until the user closes the window
- frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
+ frame.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE)
frame.addWindowListener(new WindowAdapter() {
/** Release the lock, so compilation may resume after the window is closed. */
- override def windowClosed(e: WindowEvent): Unit = lock.release;
+ override def windowClosed(e: WindowEvent): Unit = lock.release
});
val tree = new JTree(treeModel) {
/** Return the string for a tree node. */
override def convertValueToText(value: Any, sel: Boolean,
- exp: Boolean, leaf: Boolean,
- row: Int, hasFocus: Boolean) = {
- val Pair(cls, name) = TreeInfo.treeName(value.asInstanceOf[Tree]);
+ exp: Boolean, leaf: Boolean,
+ row: Int, hasFocus: Boolean) = {
+ val Pair(cls, name) = TreeInfo.treeName(value.asInstanceOf[Tree])
if (name != EMPTY)
- cls + "[" + name.toString() + "]";
- else
- cls;
-
+ cls + "[" + name.toString() + "]"
+ else
+ cls
}
}
tree.addTreeSelectionListener(new javax.swing.event.TreeSelectionListener() {
def valueChanged(e: javax.swing.event.TreeSelectionEvent): Unit = {
- textArea.setText(e.getPath().getLastPathComponent().toString());
- infoPanel.update(e.getPath().getLastPathComponent());
+ textArea.setText(e.getPath().getLastPathComponent().toString())
+ infoPanel.update(e.getPath().getLastPathComponent())
}
- });
+ })
- val topSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, topLeftPane, topRightPane);
- topSplitPane.setResizeWeight(0.5);
+ val topSplitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT, topLeftPane, topRightPane)
+ topSplitPane.setResizeWeight(0.5)
- topLeftPane.add(new JScrollPane(tree), BorderLayout.CENTER);
- topRightPane.add(new JScrollPane(infoPanel), BorderLayout.CENTER);
+ topLeftPane.add(new JScrollPane(tree), BorderLayout.CENTER)
+ topRightPane.add(new JScrollPane(infoPanel), BorderLayout.CENTER)
- bottomPane.add(new JScrollPane(textArea), BorderLayout.CENTER);
- textArea.setFont(new Font("monospaced", Font.PLAIN, 14));
- textArea.setEditable(false);
+ bottomPane.add(new JScrollPane(textArea), BorderLayout.CENTER)
+ textArea.setFont(new Font("monospaced", Font.PLAIN, 14))
+ textArea.setEditable(false)
- splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topSplitPane, bottomPane);
- frame.getContentPane().add(splitPane);
- frame.pack();
- frame.setVisible(true);
+ splitPane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, topSplitPane, bottomPane)
+ frame.getContentPane().add(splitPane)
+ frame.pack()
+ frame.setVisible(true)
}
- def setTreeModel(tm: TreeModel): Unit = treeModel = tm;
+ def setTreeModel(tm: TreeModel): Unit = treeModel = tm
}
/**
@@ -208,31 +211,31 @@ abstract class TreeBrowsers {
*/
class TextInfoPanel extends JTextArea(30, 40) {
- setFont(new Font("monospaced", Font.PLAIN, 12));
+ setFont(new Font("monospaced", Font.PLAIN, 12))
def update(v: AnyRef): Unit = {
- val t: Tree = v.asInstanceOf[Tree];
- val str = new StringBuffer();
- var buf = new StringWriter();
+ val t: Tree = v.asInstanceOf[Tree]
+ val str = new StringBuffer()
+ var buf = new StringWriter()
t match {
- case ProgramTree(_) => ();
- case UnitTree(_) => ();
+ case ProgramTree(_) => ()
+ case UnitTree(_) => ()
case _ =>
- str.append("Symbol: ").append(TreeInfo.symbolText(t));
- str.append("\nSymbol info: \n");
- TreeInfo.symbolTypeDoc(t).format(getWidth() / getColumnWidth(), buf);
- str.append(buf.toString());
- str.append("\nSymbol tpe: \n");
+ str.append("Symbol: ").append(TreeInfo.symbolText(t))
+ str.append("\nSymbol info: \n")
+ TreeInfo.symbolTypeDoc(t).format(getWidth() / getColumnWidth(), buf)
+ str.append(buf.toString())
+ str.append("\nSymbol tpe: \n")
if (t.symbol != null) {
buf = new StringWriter();
- TypePrinter.toDocument(t.symbol.tpe).format(getWidth() / getColumnWidth(), buf);
- str.append(buf.toString());
+ TypePrinter.toDocument(t.symbol.tpe).format(getWidth() / getColumnWidth(), buf)
+ str.append(buf.toString())
}
- str.append("\nSymbol Attributes: \n").append(TreeInfo.symbolAttributes(t));
- str.append("\nType: \n").append(if (t.tpe ne null) t.tpe.toString() else "");
- }
- setText(str.toString());
+ str.append("\nSymbol Attributes: \n").append(TreeInfo.symbolAttributes(t))
+ str.append("\nType: \n").append(if (t.tpe ne null) t.tpe.toString() else "")
+ }
+ setText(str.toString())
}
}
@@ -246,268 +249,268 @@ abstract class TreeBrowsers {
/** Return the case class name and the Name, if the node defines one */
def treeName(t: Tree): Pair[String, Name] = t match {
case ProgramTree(units) =>
- Pair("Program", EMPTY);
+ Pair("Program", EMPTY)
case UnitTree(unit) =>
- Pair("CompilationUnit", unit.toString());
+ Pair("CompilationUnit", unit.toString())
case DocDef(comment, definition) =>
- Pair("DocDef", EMPTY);
+ Pair("DocDef", EMPTY)
case ClassDef(mods, name, tparams, tpt, impl) =>
- Pair("ClassDef", name);
+ Pair("ClassDef", name)
case PackageDef(packaged, impl) =>
- Pair("PackageDef", EMPTY);
+ Pair("PackageDef", EMPTY)
case ModuleDef(mods, name, impl) =>
- Pair("ModuleDef", name);
+ Pair("ModuleDef", name)
case ValDef(mods, name, tpe, rhs) =>
- Pair("ValDef", name);
+ Pair("ValDef", name)
case DefDef(mods, name, tparams, vparams, tpe, rhs) =>
- Pair("DefDef", name);
+ Pair("DefDef", name)
case AbsTypeDef(mods, name, rhs, lobound) =>
- Pair("AbsTypeDef", name);
+ Pair("AbsTypeDef", name)
case AliasTypeDef(mods, name, tparams, rhs) =>
- Pair("AliasTypeDef", name);
+ Pair("AliasTypeDef", name)
case Import(expr, selectors) =>
- Pair("Import", EMPTY);
+ Pair("Import", EMPTY)
case CaseDef(pat, guard, body) =>
- Pair("CaseDef", EMPTY);
+ Pair("CaseDef", EMPTY)
case Template(parents, body) =>
- Pair("Template", EMPTY);
+ Pair("Template", EMPTY)
case LabelDef(name, params, rhs) =>
- Pair("LabelDef", name);
+ Pair("LabelDef", name)
case Block(stats, expr) =>
- Pair("Block", EMPTY);
+ Pair("Block", EMPTY)
case Sequence(trees) =>
- Pair("Sequence", EMPTY);
+ Pair("Sequence", EMPTY)
case Alternative(trees) =>
- Pair("Alternative", EMPTY);
+ Pair("Alternative", EMPTY)
case Bind(name, rhs) =>
- Pair("Bind", name);
+ Pair("Bind", name)
case Match(selector, cases) =>
- Pair("Visitor", EMPTY);
+ Pair("Visitor", EMPTY)
case Function(vparams, body) =>
- Pair("Function", EMPTY);
+ Pair("Function", EMPTY)
case Assign(lhs, rhs) =>
- Pair("Assign", EMPTY);
+ Pair("Assign", EMPTY)
case If(cond, thenp, elsep) =>
- Pair("If", EMPTY);
+ Pair("If", EMPTY)
case Return(expr) =>
- Pair("Return", EMPTY);
+ Pair("Return", EMPTY)
case Throw(expr) =>
- Pair("Throw", EMPTY);
+ Pair("Throw", EMPTY)
case New(init) =>
- Pair("New", EMPTY);
+ Pair("New", EMPTY)
case Typed(expr, tpe) =>
- Pair("Typed", EMPTY);
+ Pair("Typed", EMPTY)
case TypeApply(fun, args) =>
- Pair("TypeApply", EMPTY);
+ Pair("TypeApply", EMPTY)
case Apply(fun, args) =>
- Pair("Apply", EMPTY);
+ Pair("Apply", EMPTY)
case Super(qualif, mix) =>
- Pair("Super", qualif.toString() + ", mix: " + mix.toString());
+ Pair("Super", qualif.toString() + ", mix: " + mix.toString())
case This(qualifier) =>
- Pair("This", qualifier);
+ Pair("This", qualifier)
case Select(qualifier, selector) =>
- Pair("Select", selector);
+ Pair("Select", selector)
case Ident(name) =>
- Pair("Ident", name);
+ Pair("Ident", name)
case Literal(value) =>
- Pair("Literal", EMPTY);
+ Pair("Literal", EMPTY)
case TypeTree() =>
- Pair("TypeTree", EMPTY);
+ Pair("TypeTree", EMPTY)
case SingletonTypeTree(ref) =>
- Pair("SingletonType", EMPTY);
+ Pair("SingletonType", EMPTY)
case SelectFromTypeTree(qualifier, selector) =>
- Pair("SelectFromType", selector);
+ Pair("SelectFromType", selector)
case CompoundTypeTree(template) =>
- Pair("CompoundType", EMPTY);
+ Pair("CompoundType", EMPTY)
case AppliedTypeTree(tpe, args) =>
- Pair("AppliedType", EMPTY);
+ Pair("AppliedType", EMPTY)
case Try(block, catcher, finalizer) =>
- Pair("Try", EMPTY);
+ Pair("Try", EMPTY)
case EmptyTree =>
- Pair("Empty", EMPTY);
+ Pair("Empty", EMPTY)
case ArrayValue(elemtpt, trees) =>
- Pair("ArrayValue", EMPTY);
+ Pair("ArrayValue", EMPTY)
case Star(t) =>
- Pair("Star", EMPTY);
+ Pair("Star", EMPTY)
}
/** Return a list of children for the given tree node */
def children(t: Tree): List[Tree] = t match {
case ProgramTree(units) =>
- units;
+ units
case UnitTree(unit) =>
- List(unit.body);
+ List(unit.body)
case DocDef(comment, definition) =>
- List(definition);
+ List(definition)
case ClassDef(mods, name, tparams, tpt, impl) => {
- var children: List[Tree] = List();
- children = tparams ::: children;
+ var children: List[Tree] = List()
+ children = tparams ::: children
tpt :: impl :: children
}
case PackageDef(name, stats) =>
- stats;
+ stats
case ModuleDef(mods, name, impl) =>
- List(impl);
+ List(impl)
case ValDef(mods, name, tpe, rhs) =>
- List(tpe, rhs);
+ List(tpe, rhs)
case DefDef(mods, name, tparams, vparams, tpe, rhs) => {
- var children: List[Tree] = List();
- children = tparams ::: children;
- children = List.flatten(vparams) ::: children;
+ var children: List[Tree] = List()
+ children = tparams ::: children
+ children = List.flatten(vparams) ::: children
tpe :: rhs :: children
}
case AbsTypeDef(mods, name, rhs, lobound) =>
- List(rhs, lobound);
+ List(rhs, lobound)
case AliasTypeDef(mods, name, tparams, rhs) => {
- var children: List[Tree] = List();
- children = tparams ::: children;
+ var children: List[Tree] = List()
+ children = tparams ::: children
rhs :: children
}
case Import(expr, selectors) => {
- var children: List[Tree] = List(expr);
+ var children: List[Tree] = List(expr)
children
}
case CaseDef(pat, guard, body) =>
- List(pat, guard, body);
+ List(pat, guard, body)
case Template(parents, body) =>
- parents ::: body;
+ parents ::: body
case LabelDef(name, params, rhs) =>
- params ::: List(rhs);
+ params ::: List(rhs)
case Block(stats, expr) =>
- stats ::: List(expr);
+ stats ::: List(expr)
case Sequence(trees) =>
- trees;
+ trees
case Alternative(trees) =>
- trees;
+ trees
case Bind(name, rhs) =>
- List(rhs);
+ List(rhs)
case Match(selector, cases) =>
- selector :: cases;
+ selector :: cases
case Function(vparams, body) =>
- vparams ::: List(body);
+ vparams ::: List(body)
case Assign(lhs, rhs) =>
- List(lhs, rhs);
+ List(lhs, rhs)
case If(cond, thenp, elsep) =>
- List(cond, thenp, elsep);
+ List(cond, thenp, elsep)
case Return(expr) =>
- List(expr);
+ List(expr)
case Throw(expr) =>
- List(expr);
+ List(expr)
case New(init) =>
- List(init);
+ List(init)
case Typed(expr, tpe) =>
- List(expr, tpe);
+ List(expr, tpe)
case TypeApply(fun, args) =>
- List(fun) ::: args;
+ List(fun) ::: args
case Apply(fun, args) =>
- List(fun) ::: args;
+ List(fun) ::: args
case Super(qualif, mix) =>
- Nil;
+ Nil
case This(qualif) =>
Nil
case Select(qualif, selector) =>
- List(qualif);
+ List(qualif)
case Ident(name) =>
- Nil;
+ Nil
case Literal(value) =>
- Nil;
+ Nil
case TypeTree() =>
- Nil;
+ Nil
case SingletonTypeTree(ref) =>
- List(ref);
+ List(ref)
case SelectFromTypeTree(qualif, selector) =>
- List(qualif);
+ List(qualif)
case CompoundTypeTree(templ) =>
- List(templ);
+ List(templ)
case AppliedTypeTree(tpe, args) =>
- tpe :: args;
+ tpe :: args
case Try(block, catches, finalizer) =>
- block :: catches ::: List(finalizer);
+ block :: catches ::: List(finalizer)
case ArrayValue(elemtpt, elems) =>
- elemtpt :: elems;
+ elemtpt :: elems
case EmptyTree =>
- Nil;
+ Nil
case Star(t) =>
List(t)
@@ -515,38 +518,38 @@ abstract class TreeBrowsers {
/** Return a textual representation of this t's symbol */
def symbolText(t: Tree): String = {
- var prefix = "";
+ var prefix = ""
if (t.hasSymbol)
- prefix = "[has] ";
+ prefix = "[has] "
if (t.isDef)
- prefix = "[defines] ";
+ prefix = "[defines] "
prefix + t.symbol
}
/** Return t's symbol type */
def symbolTypeDoc(t: Tree): Document = {
- val s = t.symbol;
+ val s = t.symbol
if (s != null)
- TypePrinter.toDocument(s.info);
+ TypePrinter.toDocument(s.info)
else
- DocNil;
+ DocNil
}
/** Return a textual representation of (some of) the symbol's
* attributes */
def symbolAttributes(t: Tree): String = {
- val s = t.symbol;
- var att = "";
+ val s = t.symbol
+ var att = ""
if (s != null) {
- var str = flagsToString(s.flags);
+ var str = flagsToString(s.flags)
if (s.hasFlag(STATIC) || s.hasFlag(STATICMEMBER))
str = str + " isStatic ";
str
}
- else "";
+ else ""
}
}
@@ -554,44 +557,44 @@ abstract class TreeBrowsers {
///////////////// Document pretty printer ////////////////
- implicit def view(n: String): Document = DocText(n);
+ implicit def view(n: String): Document = DocText(n)
def toDocument(sym: Symbol): Document =
- toDocument(sym.info);
+ toDocument(sym.info)
def symsToDocument(syms: List[Symbol]): Document = syms match {
- case Nil => DocNil;
- case s :: Nil => Document.group(toDocument(s));
+ case Nil => DocNil
+ case s :: Nil => Document.group(toDocument(s))
case _ =>
Document.group(
syms.tail.foldLeft (toDocument(syms.head) :: ", ") (
- (d: Document, s2: Symbol) => toDocument(s2) :: ", " :/: d) );
+ (d: Document, s2: Symbol) => toDocument(s2) :: ", " :/: d) )
}
def toDocument(ts: List[Type]): Document = ts match {
- case Nil => DocNil;
- case t :: Nil => Document.group(toDocument(t));
+ case Nil => DocNil
+ case t :: Nil => Document.group(toDocument(t))
case _ =>
Document.group(
ts.tail.foldLeft (toDocument(ts.head) :: ", ") (
- (d: Document, t2: Type) => toDocument(t2) :: ", " :/: d) );
+ (d: Document, t2: Type) => toDocument(t2) :: ", " :/: d) )
}
def toDocument(t: Type): Document = t match {
- case ErrorType => "ErrorType()";
- case WildcardType => "WildcardType()";
- case NoType => "NoType()";
- case NoPrefix => "NoPrefix()";
- case ThisType(s) => "ThisType(" + s.name + ")";
+ case ErrorType => "ErrorType()"
+ case WildcardType => "WildcardType()"
+ case NoType => "NoType()"
+ case NoPrefix => "NoPrefix()"
+ case ThisType(s) => "ThisType(" + s.name + ")"
case SingleType(pre, sym) =>
Document.group(
Document.nest(4, "SingleType(" :/:
toDocument(pre) :: ", " :/: sym.name.toString() :: ")")
- );
+ )
case ConstantType(value) =>
- "ConstantType(" + value + ")";
+ "ConstantType(" + value + ")"
case TypeRef(pre, sym, args) =>
Document.group(
@@ -599,27 +602,27 @@ abstract class TreeBrowsers {
toDocument(pre) :: ", " :/:
sym.name.toString() :: ", " :/:
"[ " :: toDocument(args) ::"]" :: ")")
- );
+ )
- case TypeBounds(lo, hi) =>
- Document.group(
- Document.nest(4, "TypeBounds(" :/:
- toDocument(lo) :: ", " :/:
- toDocument(hi) :: ")")
- );
+ case TypeBounds(lo, hi) =>
+ Document.group(
+ Document.nest(4, "TypeBounds(" :/:
+ toDocument(lo) :: ", " :/:
+ toDocument(hi) :: ")")
+ )
case RefinedType(parents, defs) =>
Document.group(
Document.nest(4, "RefinedType(" :/:
toDocument(parents) :: ")")
- );
+ )
case ClassInfoType(parents, defs, clazz) =>
Document.group(
Document.nest(4,"ClassInfoType(" :/:
toDocument(parents) :: ", " :/:
clazz.name.toString() :: ")")
- );
+ )
case MethodType(paramtypes, result) =>
Document.group(
@@ -628,7 +631,7 @@ abstract class TreeBrowsers {
toDocument(paramtypes) :/:
"), ") :/:
toDocument(result) :: ")")
- );
+ )
case PolyType(tparams, result) =>
Document.group(
@@ -637,9 +640,10 @@ abstract class TreeBrowsers {
symsToDocument(tparams) :/:
"), ") :/:
toDocument(result) :: ")")
- );
+ )
- case _ => abort("Unknown case: " + t.toString());
+ case _ =>
+ abort("Unknown case: " + t.toString())
}
}
diff --git a/src/compiler/scala/tools/nsc/ast/TreeInfo.scala b/src/compiler/scala/tools/nsc/ast/TreeInfo.scala
index bf8ce11131..0ba00d49b7 100644
--- a/src/compiler/scala/tools/nsc/ast/TreeInfo.scala
+++ b/src/compiler/scala/tools/nsc/ast/TreeInfo.scala
@@ -1,11 +1,12 @@
-/* NSC -- new scala compiler
- * Copyright 2005 LAMP/EPFL
+/* NSC -- new Scala compiler
+ * Copyright 2005-2006 LAMP/EPFL
* @author Martin Odersky
*/
// $Id$
-package scala.tools.nsc.ast;
-import symtab.Flags._;
+package scala.tools.nsc.ast
+
+import symtab.Flags._
abstract class TreeInfo {
@@ -47,7 +48,6 @@ abstract class TreeInfo {
case _ => false
}
-
/** Is tree a pure (i.e. non-side-effecting) definition?
*/
def isPureDef(tree: Tree): boolean = tree match {
diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileConstants.scala b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileConstants.scala
index 025e9a0658..3c5d94485a 100644
--- a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileConstants.scala
+++ b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileConstants.scala
@@ -1,62 +1,63 @@
-/* NSC -- new scala compiler
- * Copyright 2005 LAMP/EPFL
+/* NSC -- new Scala compiler
+ * Copyright 2005-2006 LAMP/EPFL
* @author Martin Odersky
*/
// $Id$
-package scala.tools.nsc.symtab.classfile;
+
+package scala.tools.nsc.symtab.classfile
object ClassfileConstants {
- final val JAVA_MAGIC = 0xCAFEBABE;
- final val JAVA_MAJOR_VERSION = 45;
- final val JAVA_MINOR_VERSION = 3;
+ final val JAVA_MAGIC = 0xCAFEBABE
+ final val JAVA_MAJOR_VERSION = 45
+ final val JAVA_MINOR_VERSION = 3
- final val JAVA_ACC_PUBLIC = 0x0001;
- final val JAVA_ACC_PRIVATE = 0x0002;
- final val JAVA_ACC_PROTECTED = 0x0004;
- final val JAVA_ACC_STATIC = 0x0008;
- final val JAVA_ACC_FINAL = 0x0010;
- final val JAVA_ACC_SUPER = 0x0020;
- final val JAVA_ACC_SYNCHRONIZED = 0x0020;
- final val JAVA_ACC_VOLATILE = 0x0040;
- final val JAVA_ACC_BRIDGE = 0x0040;
- final val JAVA_ACC_TRANSIENT = 0x0080;
- final val JAVA_ACC_NATIVE = 0x0100;
- final val JAVA_ACC_INTERFACE = 0x0200;
- final val JAVA_ACC_ABSTRACT = 0x0400;
- final val JAVA_ACC_STRICT = 0x0800;
- final val JAVA_ACC_SYNTHETIC = 0x1000;
- final val JAVA_ACC_ANNOTATION = 0x2000;
- final val JAVA_ACC_ENUM = 0x4000;
+ final val JAVA_ACC_PUBLIC = 0x0001
+ final val JAVA_ACC_PRIVATE = 0x0002
+ final val JAVA_ACC_PROTECTED = 0x0004
+ final val JAVA_ACC_STATIC = 0x0008
+ final val JAVA_ACC_FINAL = 0x0010
+ final val JAVA_ACC_SUPER = 0x0020
+ final val JAVA_ACC_SYNCHRONIZED = 0x0020
+ final val JAVA_ACC_VOLATILE = 0x0040
+ final val JAVA_ACC_BRIDGE = 0x0040
+ final val JAVA_ACC_TRANSIENT = 0x0080
+ final val JAVA_ACC_NATIVE = 0x0100
+ final val JAVA_ACC_INTERFACE = 0x0200
+ final val JAVA_ACC_ABSTRACT = 0x0400
+ final val JAVA_ACC_STRICT = 0x0800
+ final val JAVA_ACC_SYNTHETIC = 0x1000
+ final val JAVA_ACC_ANNOTATION = 0x2000
+ final val JAVA_ACC_ENUM = 0x4000
// tags describing the type of a literal in the constant pool
- final val CONSTANT_UTF8 = 1;
- final val CONSTANT_UNICODE = 2;
- 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_INTFMETHODREF = 11;
- final val CONSTANT_NAMEANDTYPE = 12;
+ final val CONSTANT_UTF8 = 1
+ final val CONSTANT_UNICODE = 2
+ 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_INTFMETHODREF = 11
+ final val CONSTANT_NAMEANDTYPE = 12
// tags desribing the type of a literal in attribute values
- final val BYTE_TAG = 'B';
- final val CHAR_TAG = 'C';
- final val DOUBLE_TAG = 'D';
- final val FLOAT_TAG = 'F';
- final val INT_TAG = 'I';
- final val LONG_TAG = 'J';
- final val SHORT_TAG = 'S';
- final val BOOL_TAG = 'Z';
- final val STRING_TAG = 's';
- final val ENUM_TAG = 'e';
- final val CLASS_TAG = 'c';
- final val ARRAY_TAG = '[';
- final val VOID_TAG = 'V';
- final val ANNOTATION_TAG = '@';
+ final val BYTE_TAG = 'B'
+ final val CHAR_TAG = 'C'
+ final val DOUBLE_TAG = 'D'
+ final val FLOAT_TAG = 'F'
+ final val INT_TAG = 'I'
+ final val LONG_TAG = 'J'
+ final val SHORT_TAG = 'S'
+ final val BOOL_TAG = 'Z'
+ final val STRING_TAG = 's'
+ final val ENUM_TAG = 'e'
+ final val CLASS_TAG = 'c'
+ final val ARRAY_TAG = '['
+ final val VOID_TAG = 'V'
+ final val ANNOTATION_TAG = '@'
}
diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala
index 6891b87fe3..fffd79513f 100644
--- a/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala
+++ b/src/compiler/scala/tools/nsc/symtab/classfile/ClassfileParser.scala
@@ -1,20 +1,19 @@
-/* NSC -- new scala compiler
- * Copyright 2005 LAMP/EPFL
+/* NSC -- new Scala compiler
+ * Copyright 2005-2006 LAMP/EPFL
* @author Martin Odersky
*/
-
// $Id$
/* Ideas to extend this to an icode reader:
-
- 1. Parse classfile a second time, creating a hashmap `code' that associates method symbols with code.
- 2. For every method symbol `meth' in the new scope:
-
- new = oldclass.info.decl(meth.name).suchThat(old => old.tpe =:= meth.tpe)
-
- code(new) = code(meth)
-*/
-
+ *
+ * 1. Parse classfile a second time, creating a hashmap `code' that
+ * associates method symbols with code.
+ * 2. For every method symbol `meth' in the new scope:
+ *
+ * new = oldclass.info.decl(meth.name).suchThat(old => old.tpe =:= meth.tpe)
+ *
+ * code(new) = code(meth)
+ */
package scala.tools.nsc.symtab.classfile
import scala.tools.nsc.util.Position
@@ -24,7 +23,11 @@ import scala.collection.immutable.{Map, ListMap}
import java.io.IOException
-
+/** This abstract class implements a class file parser.
+ *
+ * @author Martin Odersky
+ * @version 1.0
+ */
abstract class ClassfileParser {
def sourcePath : AbstractFile = null
@@ -34,15 +37,15 @@ abstract class ClassfileParser {
import ClassfileConstants._
import Flags._
- private var in: AbstractFileReader = _; // the class file
- private var clazz: Symbol = _; // the class symbol containing dynamic members
- private var staticModule: Symbol = _; // the module symbol containing static members
- private var instanceDefs: Scope = _; // the scope of all instance definitions
- private var staticDefs: Scope = _; // the scope of all static definitions
- private var pool: ConstantPool = _; // the classfile's constant pool
- private var isScala: boolean = _; // does class file describe a scala class?
- private var hasMeta: boolean = _; // does class file contain jaco meta attribute?s
- private var busy: boolean = false; // lock to detect recursive reads
+ private var in: AbstractFileReader = _ // the class file
+ private var clazz: Symbol = _ // the class symbol containing dynamic members
+ private var staticModule: Symbol = _ // the module symbol containing static members
+ private var instanceDefs: Scope = _ // the scope of all instance definitions
+ private var staticDefs: Scope = _ // the scope of all static definitions
+ private var pool: ConstantPool = _ // the classfile's constant pool
+ private var isScala: boolean = _ // does class file describe a scala class?
+ private var hasMeta: boolean = _ // does class file contain jaco meta attribute?s
+ private var busy: boolean = false // lock to detect recursive reads
private var classTParams: Map[Name,Symbol] =
collection.immutable.ListMap.Empty[Name,Symbol]
private val fresh = new scala.tools.nsc.util.FreshNameCreator
@@ -101,7 +104,6 @@ abstract class ClassfileParser {
+ majorVersion + "." + minorVersion
+ ", should be at least "
+ JAVA_MAJOR_VERSION + "." + JAVA_MINOR_VERSION)
-
}
class ConstantPool {
@@ -112,7 +114,7 @@ abstract class ClassfileParser {
{ var i = 1
while (i < starts.length) {
starts(i) = in.bp;
- i = i + 1
+ i = i + 1
in.nextByte match {
case CONSTANT_UTF8 | CONSTANT_UNICODE =>
in.skip(in.nextChar)
@@ -228,7 +230,7 @@ abstract class ClassfileParser {
case 'L' =>
val start = index
while (name(index) != ';') { index = index + 1 }
- val end = index
+ val end = index
index = index + 1
definitions.getClass(name.subName(start, end)).tpe
case ARRAY_TAG =>
@@ -261,14 +263,14 @@ abstract class ClassfileParser {
val staticInfo = ClassInfoType(List(), staticDefs, statics)
val curbp = in.bp
- skipMembers(); // fields
- skipMembers(); // methods
+ skipMembers() // fields
+ skipMembers() // methods
parseAttributes(clazz, classInfo)
if (!isScala) {
clazz.setFlag(sflags)
setPrivateWithin(clazz, jflags)
if (!hasMeta) {
- clazz.setInfo(classInfo)
+ clazz.setInfo(classInfo)
}
statics.setInfo(staticInfo)
staticModule.setInfo(statics.tpe)
@@ -308,7 +310,7 @@ abstract class ClassfileParser {
var sflags = transFlags(jflags)
if ((sflags & FINAL) == 0) sflags = sflags | MUTABLE
if ((sflags & PRIVATE) != 0) {
- in.skip(4); skipAttributes();
+ in.skip(4); skipAttributes()
} else {
val name = pool.getName(in.nextChar)
val info = pool.getType(in.nextChar)
@@ -326,16 +328,16 @@ abstract class ClassfileParser {
var sflags = transFlags(jflags)
if ((jflags & JAVA_ACC_BRIDGE) != 0) sflags = sflags | PRIVATE
if ((sflags & PRIVATE) != 0) {
- in.skip(4); skipAttributes();
+ in.skip(4); skipAttributes()
} else {
val name = pool.getName(in.nextChar)
var info = pool.getType(in.nextChar)
if (name == nme.CONSTRUCTOR)
- info match {
- case MethodType(formals, restpe) =>
- assert(restpe.symbol == definitions.UnitClass)
- info = MethodType(formals, clazz.tpe)
- }
+ info match {
+ case MethodType(formals, restpe) =>
+ assert(restpe.symbol == definitions.UnitClass)
+ info = MethodType(formals, clazz.tpe)
+ }
val sym = getOwner(jflags)
.newMethod(Position.NOPOS, name).setFlag(sflags).setInfo(info)
setPrivateWithin(sym, jflags)
@@ -550,10 +552,11 @@ abstract class ClassfileParser {
case DOUBLE_TAG => pool.getConstant(index)
case CLASS_TAG => Constant(pool.getType(index))
case ENUM_TAG =>
- val t = pool.getType(index);
+ val t = pool.getType(index)
val n = pool.getName(in.nextChar);
val s = t.symbol.linkedModule.info.decls.lookup(n)
- assert (s != NoSymbol, "while processing " + in.file + ": " + t + "." + n + ": " + t.decls)
+ //assert (s != NoSymbol, "while processing " + in.file + ": " + t + "." + n + ": " + t.decls)
+ assert (s != NoSymbol, t) // avoid string concatenation!
Constant(s)
case ARRAY_TAG =>
val arr = new ArrayBuffer[Constant]()
@@ -581,18 +584,18 @@ abstract class ClassfileParser {
def parseInnerClasses(): unit = {
for (val i <- 0 until in.nextChar) {
- val innerIndex = in.nextChar
- val outerIndex = in.nextChar
- val nameIndex = in.nextChar
- val jflags = in.nextChar
- if (innerIndex != 0 && outerIndex != 0 && nameIndex != 0 &&
- (jflags & (JAVA_ACC_PUBLIC | JAVA_ACC_PROTECTED)) != 0 &&
- pool.getClassSymbol(outerIndex) == sym) {
- val innerAlias = getOwner(jflags)
- .newAliasType(Position.NOPOS, pool.getName(nameIndex).toTypeName)
- .setInfo(pool.getClassSymbol(innerIndex).tpe)
- getScope(jflags).enter(innerAlias)
- }
+ val innerIndex = in.nextChar
+ val outerIndex = in.nextChar
+ val nameIndex = in.nextChar
+ val jflags = in.nextChar
+ if (innerIndex != 0 && outerIndex != 0 && nameIndex != 0 &&
+ (jflags & (JAVA_ACC_PUBLIC | JAVA_ACC_PROTECTED)) != 0 &&
+ pool.getClassSymbol(outerIndex) == sym) {
+ val innerAlias = getOwner(jflags)
+ .newAliasType(Position.NOPOS, pool.getName(nameIndex).toTypeName)
+ .setInfo(pool.getClassSymbol(innerIndex).tpe)
+ getScope(jflags).enter(innerAlias)
+ }
}
}
val attrCount = in.nextChar
diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/MetaParser.scala b/src/compiler/scala/tools/nsc/symtab/classfile/MetaParser.scala
index 41490ad410..21293bd194 100644
--- a/src/compiler/scala/tools/nsc/symtab/classfile/MetaParser.scala
+++ b/src/compiler/scala/tools/nsc/symtab/classfile/MetaParser.scala
@@ -1,31 +1,32 @@
-/* NSC -- new scala compiler
- * Copyright 2005 LAMP/EPFL
+/* NSC -- new Scala compiler
+ * Copyright 2005-2006 LAMP/EPFL
* @author Martin Odersky
*/
// $Id$
-package scala.tools.nsc.symtab.classfile;
+
+package scala.tools.nsc.symtab.classfile
import java.util.{StringTokenizer, NoSuchElementException}
-import scala.collection.mutable.ListBuffer;
-import scala.tools.nsc.util.Position;
+import scala.collection.mutable.ListBuffer
+import scala.tools.nsc.util.Position
abstract class MetaParser{
- val global: Global;
- import global._;
+ val global: Global
+ import global._
- private var scanner: StringTokenizer = _;
- private var owner: Symbol = _;
- private var ownertype: Type = _;
- private var token: String = _;
- private var locals: Scope = null;
+ private var scanner: StringTokenizer = _
+ private var owner: Symbol = _
+ private var ownertype: Type = _
+ private var token: String = _
+ private var locals: Scope = null
def parse(meta: String, sym: Symbol, symtype: Type): unit = {
//System.out.println("parse meta for " + sym + ":" + meta + ", locals = " + locals);//DEBUG
- this.scanner = new StringTokenizer(meta, "()[], \t<;", true);
- this.owner = sym;
- this.ownertype = symtype;
- nextToken();
+ this.scanner = new StringTokenizer(meta, "()[], \t<;", true)
+ this.owner = sym
+ this.ownertype = symtype
+ nextToken()
if (token == "class") parseClass()
else if (token == "method") parseMethod()
else if (token == "field") parseField()
@@ -41,20 +42,20 @@ abstract class MetaParser{
}
protected def parseType(): Type = {
- val str = token;
- nextToken();
- val sym = locals.lookup(newTypeName(str));
+ val str = token
+ nextToken()
+ val sym = locals.lookup(newTypeName(str))
if (sym != NoSymbol) sym.tpe
else {
val tp = definitions.getClass(str).tpe;
if (token != "[") tp
else {
- val args = new ListBuffer[Type];
- do {
- nextToken(); args += parseType();
- } while (token == ",");
- nextToken();
- appliedType(tp, args.toList)
+ val args = new ListBuffer[Type];
+ do {
+ nextToken(); args += parseType();
+ } while (token == ",");
+ nextToken();
+ appliedType(tp, args.toList)
}
}
}
@@ -65,64 +66,68 @@ abstract class MetaParser{
else if (token == "-") { nextToken(); Flags.CONTRAVARIANT }
else 0;
assert(token.startsWith("?"));
- val sym = owner.newTypeParameter(Position.NOPOS, newTypeName(token)).setFlag(vflag);
- nextToken();
- val lo = if (token == ">") { nextToken(); parseType() } else definitions.AllClass.tpe;
- val hi = if (token == "<") { nextToken(); parseType() } else definitions.AnyClass.tpe;
- sym.setInfo(TypeBounds(lo, hi));
+ val sym = owner.newTypeParameter(Position.NOPOS, newTypeName(token)).setFlag(vflag)
+ nextToken()
+ val lo =
+ if (token == ">") { nextToken(); parseType() }
+ else definitions.AllClass.tpe
+ val hi =
+ if (token == "<") { nextToken(); parseType() }
+ else definitions.AnyClass.tpe
+ sym.setInfo(TypeBounds(lo, hi))
locals enter sym;
sym
}
protected def parseTypeParams(): List[Symbol] = {
- nextToken();
- val syms = new ListBuffer[Symbol];
+ nextToken()
+ val syms = new ListBuffer[Symbol]
if (token != "]") {
- syms += parseTypeParam();
+ syms += parseTypeParam()
while (token == ",") {
nextToken(); syms += parseTypeParam();
}
}
- assert(token == "]");
+ assert(token == "]")
syms.toList
}
protected def parseParams(): List[Type] = {
- nextToken();
- val tps = new ListBuffer[Type];
+ nextToken()
+ val tps = new ListBuffer[Type]
if (token != ")") {
- tps += parseType();
+ tps += parseType()
while (token == ",") {
- nextToken(); tps += parseType();
+ nextToken(); tps += parseType()
}
}
- assert(token == ")");
+ assert(token == ")")
tps.toList
}
protected def parseClass(): unit = {
- locals = new Scope();
+ locals = new Scope()
def parse(): Type = {
nextToken();
if (token == "[") {
- PolyType(parseTypeParams(), parse())
+ PolyType(parseTypeParams(), parse())
} else if (token == "extends") {
- val tps = new ListBuffer[Type];
- do {
+ val tps = new ListBuffer[Type];
+ do {
nextToken(); tps += parseType()
- } while (token == "with");
- ownertype match {
+ } while (token == "with");
+ ownertype match {
case ClassInfoType(parents, decls, clazz) =>
ClassInfoType(tps.toList, decls, clazz)
- }
+ }
} else ownertype
}
- owner.setInfo(parse());
+ owner.setInfo(parse())
assert(token == ";")
}
protected def parseMethod(): unit = {
- val globals = locals;
+ val globals = locals
locals = if (locals == null) new Scope() else new Scope(locals);
def parse(): Type = {
nextToken();
@@ -130,24 +135,24 @@ abstract class MetaParser{
else if (token == "(") MethodType(parseParams(), parse())
else parseType()
}
- owner.setInfo(parse());
- locals = globals;
+ owner.setInfo(parse())
+ locals = globals
assert(token == ";")
}
protected def parseField(): unit = {
- nextToken();
- owner.setInfo(parseType());
+ nextToken()
+ owner.setInfo(parseType())
assert(token == ";")
}
protected def parseConstr(): unit = {
def parse(): Type = {
- nextToken();
+ nextToken()
if (token == "(") MethodType(parseParams(), parse())
else owner.owner.tpe
}
- owner.setInfo(parse());
+ owner.setInfo(parse())
assert(token == ";")
}
}
diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/PickleBuffer.scala b/src/compiler/scala/tools/nsc/symtab/classfile/PickleBuffer.scala
index aed16bf057..b1707a995f 100644
--- a/src/compiler/scala/tools/nsc/symtab/classfile/PickleBuffer.scala
+++ b/src/compiler/scala/tools/nsc/symtab/classfile/PickleBuffer.scala
@@ -1,73 +1,78 @@
-/* NSC -- new scala compiler
- * Copyright 2005 LAMP/EPFL
+/* NSC -- new Scala compiler
+ * Copyright 2005-2006 LAMP/EPFL
* @author Martin Odersky
*/
// $Id$
-package scala.tools.nsc.symtab.classfile;
+
+package scala.tools.nsc.symtab.classfile
/** Variable length byte arrays, with methods for basic pickling and unpickling.
+ *
* @param data: The initial buffer
* @param from: The first index where defined data are found
* @param to : The first index where new data can be written
*/
class PickleBuffer(data: Array[byte], from: int, to: int) {
- var bytes = data;
- var readIndex = from;
- var writeIndex = to;
+ var bytes = data
+ var readIndex = from
+ var writeIndex = to
/** Double bytes array */
private def dble: unit = {
- val bytes1 = new Array[byte](bytes.length * 2);
- System.arraycopy(bytes, 0, bytes1, 0, writeIndex);
+ val bytes1 = new Array[byte](bytes.length * 2)
+ System.arraycopy(bytes, 0, bytes1, 0, writeIndex)
bytes = bytes1
}
- def ensureCapacity(capacity: int) = while (bytes.length < writeIndex + capacity) dble;
+ def ensureCapacity(capacity: int) =
+ while (bytes.length < writeIndex + capacity) dble
// -- Basic output routines --------------------------------------------
/** Write a byte of data */
def writeByte(b: int): unit = {
- if (writeIndex == bytes.length) dble;
- bytes(writeIndex) = b.asInstanceOf[byte];
+ if (writeIndex == bytes.length) dble
+ bytes(writeIndex) = b.asInstanceOf[byte]
writeIndex = writeIndex + 1
}
/** Write a natural number in big endian format, base 128.
- * All but the last digits have bit 0x80 set.*/
+ * All but the last digits have bit 0x80 set.
+ */
def writeNat(x: int): unit = {
def writeNatPrefix(x: int): unit = {
- val y = x >>> 7;
- if (y != 0) writeNatPrefix(y);
- writeByte((x & 0x7f) | 0x80);
+ val y = x >>> 7
+ if (y != 0) writeNatPrefix(y)
+ writeByte((x & 0x7f) | 0x80)
}
- val y = x >>> 7;
- if (y != 0) writeNatPrefix(y);
+ val y = x >>> 7
+ if (y != 0) writeNatPrefix(y)
writeByte(x & 0x7f)
}
/** Write a natural number at `pos'
- * If number is more than one byte, shift rest of array to make space. */
+ * If number is more than one byte, shift rest of array to make space.
+ */
def patchNat(pos: int, x: int): unit = {
def patchNatPrefix(x: int): unit = {
- writeByte(0);
- System.arraycopy(bytes, pos, bytes, pos+1, writeIndex - (pos+1));
- bytes(pos) = ((x & 0x7f) | 0x80).asInstanceOf[byte];
- val y = x >>> 7;
+ writeByte(0)
+ System.arraycopy(bytes, pos, bytes, pos+1, writeIndex - (pos+1))
+ bytes(pos) = ((x & 0x7f) | 0x80).asInstanceOf[byte]
+ val y = x >>> 7
if (y != 0) patchNatPrefix(y)
}
- bytes(pos) = (x & 0x7f).asInstanceOf[byte];
- val y = x >>> 7;
- if (y != 0) patchNatPrefix(y);
+ bytes(pos) = (x & 0x7f).asInstanceOf[byte]
+ val y = x >>> 7
+ if (y != 0) patchNatPrefix(y)
}
/** Write a long number in signed big endian format, base 256. */
def writeLong(x: long): unit = {
- val y = x >> 8;
- val z = x & 0xff;
- if (-y != (z >> 7)) writeLong(y);
- writeByte(z.asInstanceOf[int]);
+ val y = x >> 8
+ val z = x & 0xff
+ if (-y != (z >> 7)) writeLong(y)
+ writeByte(z.asInstanceOf[int])
}
// -- Basic input routines --------------------------------------------
@@ -80,37 +85,39 @@ class PickleBuffer(data: Array[byte], from: int, to: int) {
/** Read a natural number in big endian format, base 128.
* All but the last digits have bit 0x80 set.*/
def readNat(): int = {
- var b = 0;
- var x = 0;
+ var b = 0
+ var x = 0
do {
- b = readByte();
- x = (x << 7) + (b & 0x7f);
+ b = readByte()
+ x = (x << 7) + (b & 0x7f)
} while ((b & 0x80) != 0);
x
}
/** Read a long number in signed big endian format, base 256. */
def readLong(len: int): long = {
- var x = 0L;
- var i = 0;
+ var x = 0L
+ var i = 0
while (i < len) {
- x = (x << 8) + (readByte() & 0xff);
+ x = (x << 8) + (readByte() & 0xff)
i = i + 1
}
- val leading = 64 - (len << 3);
+ val leading = 64 - (len << 3)
x << leading >> leading
}
- /** Perform operation `op' until readIndex == end. Concatenate results into a list. */
+ /** Perform operation `op' until readIndex == end.
+ * Concatenate results into a list.
+ */
def until[T](end: int, op: () => T): List[T] =
if (readIndex == end) List() else op() :: until(end, op);
/** Create an index */
def createIndex: Array[int] = {
- val index = new Array[int](readNat());
+ val index = new Array[int](readNat())
for (val i <- Iterator.range(0, index.length)) {
- index(i) = readIndex;
- readByte();
+ index(i) = readIndex
+ readByte()
readIndex = readNat() + readIndex
}
index
diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/PickleFormat.scala b/src/compiler/scala/tools/nsc/symtab/classfile/PickleFormat.scala
index b75dbeaf39..f72089c991 100644
--- a/src/compiler/scala/tools/nsc/symtab/classfile/PickleFormat.scala
+++ b/src/compiler/scala/tools/nsc/symtab/classfile/PickleFormat.scala
@@ -1,10 +1,16 @@
-/* NSC -- new scala compiler
- * Copyright 2005 LAMP/EPFL
+/* NSC -- new Scala compiler
+ * Copyright 2005-2006 LAMP/EPFL
* @author Martin Odersky
*/
// $Id$
-package scala.tools.nsc.symtab.classfile;
+package scala.tools.nsc.symtab.classfile
+
+/** This object provides constants for pickling attributes.
+ *
+ * @author Martin Odersky
+ * @version 1.0
+ */
object PickleFormat {
/***************************************************
@@ -57,50 +63,50 @@ object PickleFormat {
*
* len is remaining length after `len'.
*/
- val MajorVersion = 4;
- val MinorVersion = 0;
+ val MajorVersion = 4
+ val MinorVersion = 0
- final val TERMname = 1;
- final val TYPEname = 2;
- final val NONEsym = 3;
- final val TYPEsym = 4;
- final val ALIASsym = 5;
- final val CLASSsym = 6;
- final val MODULEsym = 7;
- final val VALsym = 8;
- final val EXTref = 9;
- final val EXTMODCLASSref = 10;
- final val NOtpe = 11;
- final val NOPREFIXtpe = 12;
- final val THIStpe = 13;
- final val SINGLEtpe = 14;
- final val CONSTANTtpe = 15;
- final val TYPEREFtpe = 16;
- final val TYPEBOUNDStpe = 17;
- final val REFINEDtpe = 18;
- final val CLASSINFOtpe = 19;
- final val METHODtpe = 20;
- final val POLYtpe = 21;
- final val IMPLICITMETHODtpe = 22;
- final val LITERAL = 23; // base line for literals
- final val LITERALunit = 24;
- final val LITERALboolean = 25;
- final val LITERALbyte = 26;
- final val LITERALshort = 27;
- final val LITERALchar = 28;
- final val LITERALint = 29;
- final val LITERALlong = 30;
- final val LITERALfloat = 31;
- final val LITERALdouble = 32;
- final val LITERALstring = 33;
- final val LITERALnull = 34;
- final val LITERALclass = 35;
- final val ATTRIBUTE = 40;
+ final val TERMname = 1
+ final val TYPEname = 2
+ final val NONEsym = 3
+ final val TYPEsym = 4
+ final val ALIASsym = 5
+ final val CLASSsym = 6
+ final val MODULEsym = 7
+ final val VALsym = 8
+ final val EXTref = 9
+ final val EXTMODCLASSref = 10
+ final val NOtpe = 11
+ final val NOPREFIXtpe = 12
+ final val THIStpe = 13
+ final val SINGLEtpe = 14
+ final val CONSTANTtpe = 15
+ final val TYPEREFtpe = 16
+ final val TYPEBOUNDStpe = 17
+ final val REFINEDtpe = 18
+ final val CLASSINFOtpe = 19
+ final val METHODtpe = 20
+ final val POLYtpe = 21
+ final val IMPLICITMETHODtpe = 22
+ final val LITERAL = 23 // base line for literals
+ final val LITERALunit = 24
+ final val LITERALboolean = 25
+ final val LITERALbyte = 26
+ final val LITERALshort = 27
+ final val LITERALchar = 28
+ final val LITERALint = 29
+ final val LITERALlong = 30
+ final val LITERALfloat = 31
+ final val LITERALdouble = 32
+ final val LITERALstring = 33
+ final val LITERALnull = 34
+ final val LITERALclass = 35
+ final val ATTRIBUTE = 40
- final val firstSymTag = NONEsym;
- final val lastSymTag = VALsym;
- final val lastExtSymTag = EXTMODCLASSref;
- final val firstTypeTag = NOtpe;
- final val lastTypeTag = POLYtpe;
- final val PosOffset = 64;
+ final val firstSymTag = NONEsym
+ final val lastSymTag = VALsym
+ final val lastExtSymTag = EXTMODCLASSref
+ final val firstTypeTag = NOtpe
+ final val lastTypeTag = POLYtpe
+ final val PosOffset = 64
}
diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala b/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala
index 52cd9e768b..2886a5e0de 100644
--- a/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala
+++ b/src/compiler/scala/tools/nsc/symtab/classfile/Pickler.scala
@@ -1,67 +1,72 @@
-/* NSC -- new scala compiler
- * Copyright 2005 LAMP/EPFL
+/* NSC -- new Scala compiler
+ * Copyright 2005-2006 LAMP/EPFL
* @author Martin Odersky
*/
// $Id$
-package scala.tools.nsc.symtab.classfile;
-import java.io._;
+package scala.tools.nsc.symtab.classfile
+
+import java.io._
import java.lang.{Float, Double}
-import scala.collection.mutable.HashMap;
-import scala.tools.nsc.util.Position;
-import Flags._;
-import PickleFormat._;
+import scala.collection.mutable.HashMap
+import scala.tools.nsc.util.Position
+import Flags._
+import PickleFormat._
/**
* Serialize a top-level module and/or class;
+ *
+ * @author Martin Odersky
+ * @version 1.0
* @see EntryTags.scala for symbol table attribute format.
*/
abstract class Pickler extends SubComponent {
- import global._;
+ import global._
- val phaseName = "pickler";
- def newPhase(prev: Phase): StdPhase = new PicklePhase(prev);
+ val phaseName = "pickler"
+ def newPhase(prev: Phase): StdPhase = new PicklePhase(prev)
class PicklePhase(prev: Phase) extends StdPhase(prev) {
def apply(unit: CompilationUnit): unit = {
def pickle(tree: Tree): unit = {
- def add(sym: Symbol, pickle: Pickle) = {
- if (currentRun.compiles(sym) && !currentRun.symData.contains(sym)) {
- if (settings.debug.value) log("pickling " + sym);
- pickle.putSymbol(sym);
- currentRun.symData(sym) = pickle;
- }
- }
+ def add(sym: Symbol, pickle: Pickle) = {
+ if (currentRun.compiles(sym) && !currentRun.symData.contains(sym)) {
+ if (settings.debug.value) log("pickling " + sym);
+ pickle.putSymbol(sym);
+ currentRun.symData(sym) = pickle;
+ }
+ }
tree match {
- case PackageDef(_, stats) => stats foreach pickle;
- case ClassDef(_, _, _, _, _) | ModuleDef(_, _, _) =>
- val sym = tree.symbol;
- val pickle = new Pickle(sym.name.toTermName, sym.owner);
- add(sym, pickle);
- add(sym.linkedSym, pickle);
- pickle.finish
- case _ =>
+ case PackageDef(_, stats) =>
+ stats foreach pickle
+ case ClassDef(_, _, _, _, _) | ModuleDef(_, _, _) =>
+ val sym = tree.symbol
+ val pickle = new Pickle(sym.name.toTermName, sym.owner)
+ add(sym, pickle)
+ add(sym.linkedSym, pickle)
+ pickle.finish
+ case _ =>
}
}
- pickle(unit.body);
+ pickle(unit.body)
}
}
class Pickle(rootName: Name, rootOwner: Symbol) extends PickleBuffer(new Array[byte](4096), -1, 0) {
- private var entries = new Array[AnyRef](256);
- private var ep = 0;
- private val index = new HashMap[AnyRef, int];
+ private var entries = new Array[AnyRef](256)
+ private var ep = 0
+ private val index = new HashMap[AnyRef, int]
/** Is root in symbol.owner*? */
private def isLocal(sym: Symbol): boolean = (
sym.isRefinementClass ||
sym.name.toTermName == rootName && sym.owner == rootOwner ||
sym != NoSymbol && isLocal(sym.owner)
- );
+ )
// Phase 1 methods: Populate entries/index ------------------------------------
@@ -70,32 +75,32 @@ abstract class Pickler extends SubComponent {
private def putEntry(entry: AnyRef): boolean = index.get(entry) match {
case Some(_) => false
case None =>
- if (ep == entries.length) {
- val entries1 = new Array[AnyRef](ep * 2);
- System.arraycopy(entries, 0, entries1, 0, ep);
- entries = entries1;
- }
- entries(ep) = entry;
- index(entry) = ep;
- ep = ep + 1;
- true
+ if (ep == entries.length) {
+ val entries1 = new Array[AnyRef](ep * 2)
+ System.arraycopy(entries, 0, entries1, 0, ep)
+ entries = entries1
+ }
+ entries(ep) = entry
+ index(entry) = ep
+ ep = ep + 1
+ true
}
/** Store symbol in index. If symbol is local, also store everything it refers to. */
def putSymbol(sym: Symbol): unit = if (putEntry(sym)) {
if (isLocal(sym)) {
- putEntry(sym.name);
- putSymbol(sym.owner);
- putSymbol(sym.privateWithin);
- putType(sym.info);
- if (sym.thisSym != sym)
+ putEntry(sym.name)
+ putSymbol(sym.owner)
+ putSymbol(sym.privateWithin)
+ putType(sym.info)
+ if (sym.thisSym != sym)
putType(sym.typeOfThis);
- putSymbol(sym.alias);
+ putSymbol(sym.alias)
//for (val attr <- sym.attributes) putAttribute(sym, attr);
} else if (sym != NoSymbol) {
- putEntry(if (sym.isModuleClass) sym.name.toTermName else sym.name);
- if (!sym.owner.isRoot) putSymbol(sym.owner);
+ putEntry(if (sym.isModuleClass) sym.name.toTermName else sym.name)
+ if (!sym.owner.isRoot) putSymbol(sym.owner)
}
}
private def putSymbols(syms: List[Symbol]) = syms foreach putSymbol;
@@ -103,28 +108,28 @@ abstract class Pickler extends SubComponent {
/** Store type and everythig it refers to in index. */
private def putType(tp: Type): unit = if (putEntry(tp)) {
tp match {
- case NoType | NoPrefix =>
- ;
- case ThisType(sym) =>
- putSymbol(sym)
- case SingleType(pre, sym) =>
- putType(pre); putSymbol(sym)
- case ConstantType(value) =>
- putConstant(value)
- case TypeRef(pre, sym, args) =>
- putType(pre); putSymbol(sym); putTypes(args)
- case TypeBounds(lo, hi) =>
- putType(lo); putType(hi);
- case RefinedType(parents, decls) =>
- putSymbol(tp.symbol); putTypes(parents); putSymbols(decls.toList)
- case ClassInfoType(parents, decls, clazz) =>
- putSymbol(clazz); putTypes(parents); putSymbols(decls.toList)
- case MethodType(formals, restpe) =>
- putType(restpe); putTypes(formals)
- case PolyType(tparams, restpe) =>
- putType(restpe); putSymbols(tparams)
- case _ =>
- throw new FatalError("bad type: " + tp + "(" + tp.getClass() + ")")
+ case NoType | NoPrefix =>
+ ;
+ case ThisType(sym) =>
+ putSymbol(sym)
+ case SingleType(pre, sym) =>
+ putType(pre); putSymbol(sym)
+ case ConstantType(value) =>
+ putConstant(value)
+ case TypeRef(pre, sym, args) =>
+ putType(pre); putSymbol(sym); putTypes(args)
+ case TypeBounds(lo, hi) =>
+ putType(lo); putType(hi);
+ case RefinedType(parents, decls) =>
+ putSymbol(tp.symbol); putTypes(parents); putSymbols(decls.toList)
+ case ClassInfoType(parents, decls, clazz) =>
+ putSymbol(clazz); putTypes(parents); putSymbols(decls.toList)
+ case MethodType(formals, restpe) =>
+ putType(restpe); putTypes(formals)
+ case PolyType(tparams, restpe) =>
+ putType(restpe); putSymbols(tparams)
+ case _ =>
+ throw new FatalError("bad type: " + tp + "(" + tp.getClass() + ")")
}
}
private def putTypes(tps: List[Type]): unit = tps foreach putType;
@@ -151,108 +156,107 @@ abstract class Pickler extends SubComponent {
/** Write name, owner, flags, and info of a symbol */
private def writeSymInfo(sym: Symbol): int = {
- var posOffset = 0;
+ var posOffset = 0
if (sym.pos != Position.NOPOS && sym.owner.isClass) {
- writeNat(sym.pos);
+ writeNat(sym.pos)
posOffset = PosOffset
}
- writeRef(sym.name);
- writeRef(sym.owner);
+ writeRef(sym.name)
+ writeRef(sym.owner)
writeNat((sym.flags & PickledFlags).asInstanceOf[int]);
if (sym.privateWithin != NoSymbol) writeRef(sym.privateWithin);
- writeRef(sym.info);
+ writeRef(sym.info)
posOffset
}
/** Write a name in Utf8 format. */
def writeName(name: Name): unit = {
- ensureCapacity(name.length * 3);
- writeIndex = name.copyUTF8(bytes, writeIndex);
+ ensureCapacity(name.length * 3)
+ writeIndex = name.copyUTF8(bytes, writeIndex)
}
/** Write an entry */
private def writeEntry(entry: AnyRef): unit = {
def writeBody: int = entry match {
- case name: Name =>
- writeName(name);
- if (name.isTermName) TERMname else TYPEname
- case NoSymbol =>
- NONEsym
- case sym: Symbol if !isLocal(sym) =>
- val tag =
- if (sym.isModuleClass) {
- writeRef(sym.name.toTermName); EXTMODCLASSref
- } else {
- writeRef(sym.name); EXTref
- }
- if (!sym.owner.isRoot) writeRef(sym.owner);
- tag
- case sym: ClassSymbol =>
- val posOffset = writeSymInfo(sym);
- if (sym.thisSym != sym) writeRef(sym.typeOfThis);
- CLASSsym + posOffset;
- case sym: TypeSymbol =>
- val posOffset = writeSymInfo(sym);
- (if (sym.isAbstractType) TYPEsym else ALIASsym) + posOffset
- case sym: TermSymbol =>
- val posOffset = writeSymInfo(sym);
- if (sym.alias != NoSymbol) writeRef(sym.alias);
+ case name: Name =>
+ writeName(name)
+ if (name.isTermName) TERMname else TYPEname
+ case NoSymbol =>
+ NONEsym
+ case sym: Symbol if !isLocal(sym) =>
+ val tag =
+ if (sym.isModuleClass) {
+ writeRef(sym.name.toTermName); EXTMODCLASSref
+ } else {
+ writeRef(sym.name); EXTref
+ }
+ if (!sym.owner.isRoot) writeRef(sym.owner);
+ tag
+ case sym: ClassSymbol =>
+ val posOffset = writeSymInfo(sym)
+ if (sym.thisSym != sym) writeRef(sym.typeOfThis)
+ CLASSsym + posOffset
+ case sym: TypeSymbol =>
+ val posOffset = writeSymInfo(sym)
+ (if (sym.isAbstractType) TYPEsym else ALIASsym) + posOffset
+ case sym: TermSymbol =>
+ val posOffset = writeSymInfo(sym)
+ if (sym.alias != NoSymbol) writeRef(sym.alias)
(if (sym.isModule) MODULEsym else VALsym) + posOffset
- case NoType =>
- NOtpe
- case NoPrefix =>
- NOPREFIXtpe
- case ThisType(sym) =>
- writeRef(sym); THIStpe
- case SingleType(pre, sym) =>
- writeRef(pre); writeRef(sym); SINGLEtpe
- case ConstantType(value) =>
- writeRef(value);
- CONSTANTtpe
- case TypeRef(pre, sym, args) =>
- writeRef(pre); writeRef(sym); writeRefs(args); TYPEREFtpe
- case TypeBounds(lo, hi) =>
- writeRef(lo); writeRef(hi); TYPEBOUNDStpe
- case tp @ RefinedType(parents, decls) =>
- writeRef(tp.symbol); writeRefs(parents); REFINEDtpe
- case ClassInfoType(parents, decls, clazz) =>
- writeRef(clazz); writeRefs(parents); CLASSINFOtpe
- case MethodType(formals, restpe) =>
- writeRef(restpe); writeRefs(formals);
- if (entry.isInstanceOf[ImplicitMethodType]) IMPLICITMETHODtpe
- else METHODtpe
- case PolyType(tparams, restpe) =>
- writeRef(restpe); writeRefs(tparams); POLYtpe
- case c @ Constant(_) =>
- if (c.tag == BooleanTag) writeLong(if (c.booleanValue) 1 else 0)
+ case NoType =>
+ NOtpe
+ case NoPrefix =>
+ NOPREFIXtpe
+ case ThisType(sym) =>
+ writeRef(sym); THIStpe
+ case SingleType(pre, sym) =>
+ writeRef(pre); writeRef(sym); SINGLEtpe
+ case ConstantType(value) =>
+ writeRef(value); CONSTANTtpe
+ case TypeRef(pre, sym, args) =>
+ writeRef(pre); writeRef(sym); writeRefs(args); TYPEREFtpe
+ case TypeBounds(lo, hi) =>
+ writeRef(lo); writeRef(hi); TYPEBOUNDStpe
+ case tp @ RefinedType(parents, decls) =>
+ writeRef(tp.symbol); writeRefs(parents); REFINEDtpe
+ case ClassInfoType(parents, decls, clazz) =>
+ writeRef(clazz); writeRefs(parents); CLASSINFOtpe
+ case MethodType(formals, restpe) =>
+ writeRef(restpe); writeRefs(formals)
+ if (entry.isInstanceOf[ImplicitMethodType]) IMPLICITMETHODtpe
+ else METHODtpe
+ case PolyType(tparams, restpe) =>
+ writeRef(restpe); writeRefs(tparams); POLYtpe
+ case c @ Constant(_) =>
+ if (c.tag == BooleanTag) writeLong(if (c.booleanValue) 1 else 0)
else if (ByteTag <= c.tag && c.tag <= LongTag) writeLong(c.longValue)
- else if (c.tag == FloatTag) writeLong(Float.floatToIntBits(c.floatValue))
- else if (c.tag == DoubleTag) writeLong(Double.doubleToLongBits(c.doubleValue));
- else if (c.tag == StringTag) writeRef(newTermName(c.stringValue));
- else if (c.tag == ClassTag) writeRef(c.typeValue);
- LITERAL + c.tag
+ else if (c.tag == FloatTag) writeLong(Float.floatToIntBits(c.floatValue))
+ else if (c.tag == DoubleTag) writeLong(Double.doubleToLongBits(c.doubleValue));
+ else if (c.tag == StringTag) writeRef(newTermName(c.stringValue));
+ else if (c.tag == ClassTag) writeRef(c.typeValue);
+ LITERAL + c.tag
/*
case Pair(tp, cs) =>
writeRef(tp);
for (val c <- cs) writeRef(cs);
ATTRIBUTE
*/
- case _ =>
- throw new FatalError("bad entry: " + entry + " " + entry.getClass());//debug
+ case _ =>
+ throw new FatalError("bad entry: " + entry + " " + entry.getClass());//debug
}
- val startpos = writeIndex;
- writeByte(0); writeByte(0);
- patchNat(startpos, writeBody);
- patchNat(startpos + 1, writeIndex - (startpos + 2));
+ val startpos = writeIndex
+ writeByte(0); writeByte(0)
+ patchNat(startpos, writeBody)
+ patchNat(startpos + 1, writeIndex - (startpos + 2))
}
/** Write byte array */
def finish = {
- assert(writeIndex == 0);
- writeNat(MajorVersion);
- writeNat(MinorVersion);
- writeNat(ep);
- if (settings.debug.value) log("" + ep + " entries");//debug
+ assert(writeIndex == 0)
+ writeNat(MajorVersion)
+ writeNat(MinorVersion)
+ writeNat(ep)
+ if (settings.debug.value) log("" + ep + " entries")//debug
for (val i <- 0 until ep) writeEntry(entries(i));
}
diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/SymblfileParser.scala b/src/compiler/scala/tools/nsc/symtab/classfile/SymblfileParser.scala
index 83f296125f..f8fa046bf4 100644
--- a/src/compiler/scala/tools/nsc/symtab/classfile/SymblfileParser.scala
+++ b/src/compiler/scala/tools/nsc/symtab/classfile/SymblfileParser.scala
@@ -1,30 +1,37 @@
-/* NSC -- new scala compiler
- * Copyright 2005 LAMP/EPFL
+/* NSC -- new Scala compiler
+ * Copyright 2005-2006 LAMP/EPFL
* @author Martin Odersky
*/
// $Id$
-package scala.tools.nsc.symtab.classfile;
+package scala.tools.nsc.symtab.classfile
-import scala.tools.nsc.io.{AbstractFile, AbstractFileReader};
+import scala.tools.nsc.io.{AbstractFile, AbstractFileReader}
+/** This abstract class implements ..
+ *
+ * @author Martin Odersky
+ * @version 1.0
+ */
abstract class SymblfileParser {
- val global: Global;
- import global._;
+ val global: Global
+ import global._
- private var current: AbstractFile = null; // lock to detect recursive reads
+ private var current: AbstractFile = null // lock to detect recursive reads
private object unpickler extends UnPickler {
val global: SymblfileParser.this.global.type = SymblfileParser.this.global
}
def parse(file: AbstractFile, root: Symbol): unit = {
- assert(current == null, current);
- current = file;
- val in = new AbstractFileReader(file);
- if (root.isModule) unpickler.unpickle(in.buf, 0, root.linkedClass, root, file.toString())
- else unpickler.unpickle(in.buf, 0, root, root.linkedModule, file.toString());
+ assert(current == null, current)
+ current = file
+ val in = new AbstractFileReader(file)
+ if (root.isModule)
+ unpickler.unpickle(in.buf, 0, root.linkedClass, root, file.toString())
+ else
+ unpickler.unpickle(in.buf, 0, root, root.linkedModule, file.toString())
current = null
}
}
diff --git a/src/compiler/scala/tools/nsc/symtab/classfile/UnPickler.scala b/src/compiler/scala/tools/nsc/symtab/classfile/UnPickler.scala
index f531ea9643..0d295489e1 100644
--- a/src/compiler/scala/tools/nsc/symtab/classfile/UnPickler.scala
+++ b/src/compiler/scala/tools/nsc/symtab/classfile/UnPickler.scala
@@ -1,8 +1,9 @@
-/* NSC -- new scala compiler
- * Copyright 2005 LAMP/EPFL
+/* NSC -- new Scala compiler
+ * Copyright 2005-2006 LAMP/EPFL
* @author Martin Odersky
*/
// $Id$
+
package scala.tools.nsc.symtab.classfile
import scala.tools.nsc.util.Position
@@ -14,6 +15,11 @@ import PickleFormat._
import collection.mutable.HashMap
import java.io.IOException
+/** This abstract class implements ..
+ *
+ * @author Martin Odersky
+ * @version 1.0
+ */
abstract class UnPickler {
val global: Global
import global._
@@ -89,12 +95,12 @@ abstract class UnPickler {
private def at[T <: AnyRef](i: int, op: () => T): T = {
var r = entries(i)
if (r == null) {
- val savedIndex = readIndex
- readIndex = index(i)
- r = op()
- assert(entries(i) == null, entries(i))
- entries(i) = r
- readIndex = savedIndex
+ val savedIndex = readIndex
+ readIndex = index(i)
+ r = op()
+ assert(entries(i) == null, entries(i))
+ entries(i) = r
+ readIndex = savedIndex
}
r.asInstanceOf[T]
}
@@ -104,9 +110,9 @@ abstract class UnPickler {
val tag = readByte()
val len = readNat()
tag match {
- case TERMname => newTermName(bytes, readIndex, len)
- case TYPEname => newTypeName(bytes, readIndex, len)
- case _ => errorBadSignature("bad name tag: " + tag)
+ case TERMname => newTermName(bytes, readIndex, len)
+ case TYPEname => newTypeName(bytes, readIndex, len)
+ case _ => errorBadSignature("bad name tag: " + tag)
}
}
@@ -116,70 +122,70 @@ abstract class UnPickler {
val end = readNat() + readIndex
var sym: Symbol = NoSymbol
tag match {
- case EXTref | EXTMODCLASSref =>
- val name = readNameRef()
- val owner = if (readIndex == end) definitions.RootClass else readSymbolRef()
- sym = if (name.toTermName == nme.ROOT) definitions.RootClass
- else if (name == nme.ROOTPKG) definitions.RootPackage
+ case EXTref | EXTMODCLASSref =>
+ val name = readNameRef()
+ val owner = if (readIndex == end) definitions.RootClass else readSymbolRef()
+ sym = if (name.toTermName == nme.ROOT) definitions.RootClass
+ else if (name == nme.ROOTPKG) definitions.RootPackage
else if (tag == EXTref) owner.info.decl(name)
- else owner.info.decl(name).moduleClass
- if (sym == NoSymbol) {
- errorBadSignature(
- "reference " + (if (name.isTypeName) "type " else "value ") +
- name.decode + " of " + owner + " refers to nonexisting symbol.")
+ else owner.info.decl(name).moduleClass
+ if (sym == NoSymbol) {
+ errorBadSignature(
+ "reference " + (if (name.isTypeName) "type " else "value ") +
+ name.decode + " of " + owner + " refers to nonexisting symbol.")
}
- case NONEsym =>
- sym = NoSymbol
- case _ =>
+ case NONEsym =>
+ sym = NoSymbol
+ case _ =>
val pos = if (tag > PosOffset) readNat() else Position.NOPOS
- val name = readNameRef()
- val owner = readSymbolRef()
- val flags = readNat()
+ val name = readNameRef()
+ val owner = readSymbolRef()
+ val flags = readNat()
var privateWithin: Symbol = NoSymbol
var inforef = readNat()
if (isSymbolRef(inforef)) {
privateWithin = at(inforef, readSymbol)
inforef = readNat()
}
- (tag % PosOffset) match {
- case TYPEsym =>
- sym = owner.newAbstractType(pos, name)
- case ALIASsym =>
- sym = owner.newAliasType(pos, name)
- case CLASSsym =>
- sym =
+ (tag % PosOffset) match {
+ case TYPEsym =>
+ sym = owner.newAbstractType(pos, name)
+ case ALIASsym =>
+ sym = owner.newAliasType(pos, name)
+ case CLASSsym =>
+ sym =
if (name == classRoot.name && owner == classRoot.owner)
(if ((flags & MODULE) != 0) moduleRoot.moduleClass
else classRoot).setPos(pos)
- else
+ else
if ((flags & MODULE) != 0) owner.newModuleClass(pos, name)
else owner.newClass(pos, name)
- if (readIndex != end) sym.typeOfThis = new LazyTypeRef(readNat())
- case MODULEsym =>
- val clazz = at(inforef, readType).symbol
- sym =
+ if (readIndex != end) sym.typeOfThis = new LazyTypeRef(readNat())
+ case MODULEsym =>
+ val clazz = at(inforef, readType).symbol
+ sym =
if (name == moduleRoot.name && owner == moduleRoot.owner) moduleRoot
- else {
- assert(clazz.isInstanceOf[ModuleClassSymbol], clazz)
- val mclazz = clazz.asInstanceOf[ModuleClassSymbol]
+ else {
+ assert(clazz.isInstanceOf[ModuleClassSymbol], clazz)
+ val mclazz = clazz.asInstanceOf[ModuleClassSymbol]
val m = owner.newModule(pos, name, mclazz)
mclazz.setSourceModule(m)
m
}
- case VALsym =>
- sym = if (name == moduleRoot.name && owner == moduleRoot.owner) moduleRoot.resetFlag(MODULE)
- else owner.newValue(pos, name)
- case _ =>
- errorBadSignature("bad symbol tag: " + tag)
- }
- sym.setFlag(flags)
+ case VALsym =>
+ sym = if (name == moduleRoot.name && owner == moduleRoot.owner) moduleRoot.resetFlag(MODULE)
+ else owner.newValue(pos, name)
+ case _ =>
+ errorBadSignature("bad symbol tag: " + tag)
+ }
+ sym.setFlag(flags)
sym.privateWithin = privateWithin
- if (readIndex != end) assert(sym hasFlag (SUPERACCESSOR | PARAMACCESSOR))
- if (sym hasFlag SUPERACCESSOR) assert(readIndex != end)
- sym.setInfo(
- if (readIndex != end) new LazyTypeRefAndAlias(inforef, readNat())
- else new LazyTypeRef(inforef))
- if (sym.owner.isClass && sym != classRoot && sym != moduleRoot &&
+ if (readIndex != end) assert(sym hasFlag (SUPERACCESSOR | PARAMACCESSOR))
+ if (sym hasFlag SUPERACCESSOR) assert(readIndex != end)
+ sym.setInfo(
+ if (readIndex != end) new LazyTypeRefAndAlias(inforef, readNat())
+ else new LazyTypeRef(inforef))
+ if (sym.owner.isClass && sym != classRoot && sym != moduleRoot &&
!sym.isModuleClass && !sym.isRefinementClass && !sym.isTypeParameter)
symScope(sym.owner) enter sym
}
@@ -191,42 +197,42 @@ abstract class UnPickler {
val tag = readByte()
val end = readNat() + readIndex
tag match {
- case NOtpe =>
- NoType
- case NOPREFIXtpe =>
- NoPrefix
- case THIStpe =>
- ThisType(readSymbolRef())
- case SINGLEtpe =>
- singleType(readTypeRef(), readSymbolRef())
- case CONSTANTtpe =>
- ConstantType(readConstantRef())
- case TYPEREFtpe =>
- rawTypeRef(readTypeRef(), readSymbolRef(), until(end, readTypeRef))
+ case NOtpe =>
+ NoType
+ case NOPREFIXtpe =>
+ NoPrefix
+ case THIStpe =>
+ ThisType(readSymbolRef())
+ case SINGLEtpe =>
+ singleType(readTypeRef(), readSymbolRef())
+ case CONSTANTtpe =>
+ ConstantType(readConstantRef())
+ case TYPEREFtpe =>
+ rawTypeRef(readTypeRef(), readSymbolRef(), until(end, readTypeRef))
case TYPEBOUNDStpe =>
TypeBounds(readTypeRef(), readTypeRef())
- case REFINEDtpe =>
- val clazz = readSymbolRef()
+ case REFINEDtpe =>
+ val clazz = readSymbolRef()
/*
val ps = until(end, readTypeRef)
val dcls = symScope(clazz)
new RefinedType(ps, dcls) { override def symbol = clazz }
*/
- new RefinedType(until(end, readTypeRef), symScope(clazz)) { override def symbol = clazz }
- case CLASSINFOtpe =>
- val clazz = readSymbolRef()
- ClassInfoType(until(end, readTypeRef), symScope(clazz), clazz)
- case METHODtpe =>
- val restpe = readTypeRef()
- MethodType(until(end, readTypeRef), restpe)
- case IMPLICITMETHODtpe =>
- val restpe = readTypeRef()
- ImplicitMethodType(until(end, readTypeRef), restpe)
- case POLYtpe =>
- val restpe = readTypeRef()
- PolyType(until(end, readSymbolRef), restpe)
- case _ =>
- errorBadSignature("bad type tag: " + tag)
+ new RefinedType(until(end, readTypeRef), symScope(clazz)) { override def symbol = clazz }
+ case CLASSINFOtpe =>
+ val clazz = readSymbolRef()
+ ClassInfoType(until(end, readTypeRef), symScope(clazz), clazz)
+ case METHODtpe =>
+ val restpe = readTypeRef()
+ MethodType(until(end, readTypeRef), restpe)
+ case IMPLICITMETHODtpe =>
+ val restpe = readTypeRef()
+ ImplicitMethodType(until(end, readTypeRef), restpe)
+ case POLYtpe =>
+ val restpe = readTypeRef()
+ PolyType(until(end, readSymbolRef), restpe)
+ case _ =>
+ errorBadSignature("bad type tag: " + tag)
}
}
@@ -235,19 +241,19 @@ abstract class UnPickler {
val tag = readByte()
val len = readNat()
tag match {
- case LITERALunit => Constant(())
- case LITERALboolean => Constant(if (readLong(len) == 0) false else true)
- case LITERALbyte => Constant(readLong(len).asInstanceOf[byte])
- case LITERALshort => Constant(readLong(len).asInstanceOf[short])
- case LITERALchar => Constant(readLong(len).asInstanceOf[char])
- case LITERALint => Constant(readLong(len).asInstanceOf[int])
- case LITERALlong => Constant(readLong(len))
- case LITERALfloat => Constant(Float.intBitsToFloat(readLong(len).asInstanceOf[int]))
- case LITERALdouble => Constant(Double.longBitsToDouble(readLong(len)))
- case LITERALstring => Constant(readNameRef().toString())
- case LITERALnull => Constant(null)
- case LITERALclass => Constant(readTypeRef())
- case _ => errorBadSignature("bad constant tag: " + tag)
+ case LITERALunit => Constant(())
+ case LITERALboolean => Constant(if (readLong(len) == 0) false else true)
+ case LITERALbyte => Constant(readLong(len).asInstanceOf[byte])
+ case LITERALshort => Constant(readLong(len).asInstanceOf[short])
+ case LITERALchar => Constant(readLong(len).asInstanceOf[char])
+ case LITERALint => Constant(readLong(len).asInstanceOf[int])
+ case LITERALlong => Constant(readLong(len))
+ case LITERALfloat => Constant(Float.intBitsToFloat(readLong(len).asInstanceOf[int]))
+ case LITERALdouble => Constant(Double.longBitsToDouble(readLong(len)))
+ case LITERALstring => Constant(readNameRef().toString())
+ case LITERALnull => Constant(null)
+ case LITERALclass => Constant(readTypeRef())
+ case _ => errorBadSignature("bad constant tag: " + tag)
}
}
@@ -263,20 +269,20 @@ abstract class UnPickler {
private class LazyTypeRef(i: int) extends LazyType {
private val definedAtRunId = currentRunId
override def complete(sym: Symbol): unit = {
- val tp = at(i, readType)
- sym setInfo tp
- if (currentRunId != definedAtRunId) tp.complete(sym)
+ val tp = at(i, readType)
+ sym setInfo tp
+ if (currentRunId != definedAtRunId) tp.complete(sym)
}
override def load(sym: Symbol): unit = complete(sym)
}
private class LazyTypeRefAndAlias(i: int, j: int) extends LazyTypeRef(i) {
override def complete(sym: Symbol): unit = {
- super.complete(sym)
+ super.complete(sym)
var alias = at(j, readSymbol)
if (alias hasFlag OVERLOADED)
alias = alias suchThat (alt => sym.tpe =:= sym.owner.thisType.memberType(alt))
- sym.asInstanceOf[TermSymbol].setAlias(alias)
+ sym.asInstanceOf[TermSymbol].setAlias(alias)
}
}
}
diff --git a/src/compiler/scala/tools/util/AbstractTimer.scala b/src/compiler/scala/tools/util/AbstractTimer.scala
index f306fb1113..8d445ca818 100644
--- a/src/compiler/scala/tools/util/AbstractTimer.scala
+++ b/src/compiler/scala/tools/util/AbstractTimer.scala
@@ -1,18 +1,23 @@
-/* ____ ____ ____ ____ ______ *\
-** / __// __ \/ __// __ \/ ____/ SOcos COmpiles Scala **
-** __\_ \/ /_/ / /__/ /_/ /\_ \ (c) 2002-2006, LAMP/EPFL **
-** /_____/\____/\___/\____/____/ **
+/* __ *\
+** ________ ___ / / ___ Scala API **
+** / __/ __// _ | / / / _ | (c) 2002-2006, LAMP/EPFL **
+** __\ \/ /__/ __ |/ /__/ __ | **
+** /____/\___/_/ |_/____/_/ | | **
+** |/ **
\* */
// $Id$
-package scala.tools.util;
+package scala.tools.util
-import scala.collection.mutable.Stack;
+import scala.collection.mutable.Stack
/**
* 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 {
@@ -20,29 +25,28 @@ abstract class AbstractTimer {
// Private Fields
/** A stack for maintaining start times */
- private val starts = new Stack[Long]();
+ private val starts = new Stack[Long]()
//########################################################################
// Public Methods
/** Issues a timing information (duration in milliseconds). */
- def issue(message: String, duration: Long): Unit;
+ def issue(message: String, duration: Long): Unit
/** Starts a new timer. */
def start() = {
- starts += System.currentTimeMillis();
+ starts += System.currentTimeMillis()
}
/** Ends the current timer. */
def stop(message: String): Unit = {
- val stop = System.currentTimeMillis();
- issue(message, stop - starts.pop);
+ val stop = System.currentTimeMillis()
+ issue(message, stop - starts.pop)
}
/** Drops the current timer. */
- def drop(): Unit = {
- starts.pop;
- }
+ def drop(): Unit =
+ starts.pop
//########################################################################
}
diff --git a/src/compiler/scala/tools/util/SocketConnection.scala b/src/compiler/scala/tools/util/SocketConnection.scala
index 531caaf30d..df6302ab1e 100644
--- a/src/compiler/scala/tools/util/SocketConnection.scala
+++ b/src/compiler/scala/tools/util/SocketConnection.scala
@@ -1,9 +1,24 @@
+/* __ *\
+** ________ ___ / / ___ Scala API **
+** / __/ __// _ | / / / _ | (c) 2002-2006, LAMP/EPFL **
+** __\ \/ /__/ __ |/ /__/ __ | **
+** /____/\___/_/ |_/____/_/ | | **
+** |/ **
+\* */
+
+// $id: $
+
package scala.tools.util
import java.io._
import java.net._
-class SocketConnection(hostname: String, port: int) {
+/** 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)
@@ -12,7 +27,7 @@ class SocketConnection(hostname: String, port: int) {
var in: BufferedReader = _
var errorMessage: String = _
- def open(): boolean = {
+ def open(): Boolean = {
try {
socket = new Socket(hostname, port)
out = new PrintWriter(socket.getOutputStream(), true)
@@ -20,10 +35,10 @@ class SocketConnection(hostname: String, port: int) {
true
} catch {
case e: UnknownHostException =>
- errorMessage = "Don't know about host: "+hostname+"."
+ errorMessage = "Don't know about host: " + hostname + "."
false
case e: IOException =>
- errorMessage = "Couldn't get I/O for the connection to: "+hostname+"."
+ errorMessage = "Couldn't get I/O for the connection to: " + hostname + "."
false
}
}
@@ -34,4 +49,3 @@ class SocketConnection(hostname: String, port: int) {
socket.close()
}
}
-
diff --git a/src/compiler/scala/tools/util/SocketServer.scala b/src/compiler/scala/tools/util/SocketServer.scala
index 7a65290dcc..ddfeb3b679 100644
--- a/src/compiler/scala/tools/util/SocketServer.scala
+++ b/src/compiler/scala/tools/util/SocketServer.scala
@@ -1,8 +1,24 @@
+/* __ *\
+** ________ ___ / / ___ Scala API **
+** / __/ __// _ | / / / _ | (c) 2002-2006, LAMP/EPFL **
+** __\ \/ /__/ __ |/ /__/ __ | **
+** /____/\___/_/ |_/____/_/ | | **
+** |/ **
+\* */
+
+// $Id$
+
package scala.tools.util
import java.net._
import java.io._
+/** This abstract class implements the server communication for
+ * the fast Scala compiler.
+ *
+ * @author Martin Odersky
+ * @version 1.0
+ */
abstract class SocketServer {
def shutDown: boolean
@@ -11,6 +27,11 @@ abstract class SocketServer {
var out: PrintWriter = _
var in: BufferedReader = _
+ private def error(msg: String) = {
+ System.err.println(msg)
+ exit(1)
+ }
+
val port: int = try {
val s = new ServerSocket(0)
val p = s.getLocalPort()
@@ -18,8 +39,7 @@ abstract class SocketServer {
p
} catch {
case e: IOException =>
- System.err.println("Could not listen on any port; exiting.")
- exit(1)
+ error("Could not listen on any port; exiting.")
}
def run(): unit = {
@@ -28,15 +48,13 @@ abstract class SocketServer {
new ServerSocket(port)
} catch {
case e: IOException =>
- System.err.println("Could not listen on port: "+port+"; exiting.")
- exit(1)
+ error("Could not listen on port: " + port + "; exiting.")
}
val clientSocket = try {
serverSocket.accept()
} catch {
case e: IOException =>
- System.err.println("Accept on port "+port+" failed; exiting.")
- exit(1)
+ error("Accept on port " + port + " failed; exiting.")
}
out = new PrintWriter(clientSocket.getOutputStream(), true)
diff --git a/src/compiler/scala/tools/util/StringOps.scala b/src/compiler/scala/tools/util/StringOps.scala
index 0c2333ca22..b1cd5d9b1a 100644
--- a/src/compiler/scala/tools/util/StringOps.scala
+++ b/src/compiler/scala/tools/util/StringOps.scala
@@ -1,9 +1,25 @@
+/* __ *\
+** ________ ___ / / ___ Scala API **
+** / __/ __// _ | / / / _ | (c) 2002-2006, LAMP/EPFL **
+** __\ \/ /__/ __ |/ /__/ __ | **
+** /____/\___/_/ |_/____/_/ | | **
+** |/ **
+\* */
+
+// $Id$
+
package scala.tools.util
+/** This objects provides methods to extract elements from
+ * a string according to some defined character separator.
+ *
+ * @author Martin Odersky
+ * @version 1.0
+ */
object StringOps {
- def decompose(str: String, sep: char): List[String] = {
- def ws(start: int): List[String] =
+ def decompose(str: String, sep: Char): List[String] = {
+ def ws(start: Int): List[String] =
if (start == str.length) List()
else if (str.charAt(start) == sep) ws(start + 1)
else {
@@ -16,4 +32,3 @@ object StringOps {
def words(str: String): List[String] = decompose(str, ' ')
}
-
diff --git a/src/compiler/scala/tools/util/UTF8Codec.scala b/src/compiler/scala/tools/util/UTF8Codec.scala
index 3cc7200e18..d50209696a 100644
--- a/src/compiler/scala/tools/util/UTF8Codec.scala
+++ b/src/compiler/scala/tools/util/UTF8Codec.scala
@@ -1,78 +1,83 @@
-/* ____ ____ ____ ____ ______ *\
-** / __// __ \/ __// __ \/ ____/ SOcos COmpiles Scala **
-** __\_ \/ /_/ / /__/ /_/ /\_ \ (c) 2002-2006, LAMP/EPFL **
-** /_____/\____/\___/\____/____/ **
+/* __ *\
+** ________ ___ / / ___ Scala API **
+** / __/ __// _ | / / / _ | (c) 2002-2006, LAMP/EPFL **
+** __\ \/ /__/ __ |/ /__/ __ | **
+** /____/\___/_/ |_/____/_/ | | **
+** |/ **
\* */
// $Id$
+package scala.tools.util
-package scala.tools.util;
-
-
+/** This object provides methods for encoding/decoding UTF-8 characters.
+ *
+ * @author Martin Odersky
+ * @version 1.0
+ */
object UTF8Codec {
def encode(src: Array[Char], from: Int, dst: Array[Byte], to: Int, len: Int): Int = {
- var i = from;
- var j = to;
- val end = from + len;
+ var i = from
+ var j = to
+ val end = from + len
while (i < end) {
- val ch = src(i);
- i = i + 1;
+ val ch = src(i)
+ i = i + 1
if (ch < 128) {
- dst(j) = ch.toByte;
- j = j + 1;
+ dst(j) = ch.toByte
+ j = j + 1
}
else if (ch <= 0x3FF) {
- dst(j) = (0xC0 | (ch >> 6)).toByte;
- dst(j+1) = (0x80 | (ch & 0x3F)).toByte;
- j = j + 2;
+ dst(j) = (0xC0 | (ch >> 6)).toByte
+ dst(j+1) = (0x80 | (ch & 0x3F)).toByte
+ j = j + 2
} else {
- dst(j) = (0xE0 | (ch >> 12)).toByte;
- dst(j+1) = (0x80 | ((ch >> 6) & 0x3F)).toByte;
- dst(j+2) = (0x80 | (ch & 0x3F)).toByte;
- j = j + 3;
+ dst(j) = (0xE0 | (ch >> 12)).toByte
+ dst(j+1) = (0x80 | ((ch >> 6) & 0x3F)).toByte
+ dst(j+2) = (0x80 | (ch & 0x3F)).toByte
+ j = j + 3
}
}
j
}
def encode(s: String, dst: Array[Byte], to: Int): Int =
- encode(s.toCharArray(), 0, dst, to, s.length());
+ encode(s.toCharArray(), 0, dst, to, s.length())
def encode(s: String): Array[Byte] = {
- val dst = new Array[Byte](s.length() * 3);
- val len = encode(s, dst, 0);
+ val dst = new Array[Byte](s.length() * 3)
+ val len = encode(s, dst, 0)
dst.subArray(0, len)
}
def decode(src: Array[Byte], from: Int,
dst: Array[Char], to: Int, len: Int): Int =
{
- var i = from;
- var j = to;
- val end = from + len;
+ var i = from
+ var j = to
+ val end = from + len
while (i < end) {
- var b = src(i) & 0xFF;
- i = i + 1;
+ var b = src(i) & 0xFF
+ i = i + 1
if (b >= 0xE0) {
- b = ((b & 0x0F) << 12) | (src(i) & 0x3F) << 6;
- b = b | (src(i+1) & 0x3F);
- i = i + 2;
+ b = ((b & 0x0F) << 12) | (src(i) & 0x3F) << 6
+ b = b | (src(i+1) & 0x3F)
+ i = i + 2
} else if (b >= 0xC0) {
- b = ((b & 0x1F) << 6) | (src(i) & 0x3F);
- i = i + 1;
+ b = ((b & 0x1F) << 6) | (src(i) & 0x3F)
+ i = i + 1
}
- dst(j) = b.toChar;
- j = j + 1;
+ dst(j) = b.toChar
+ j = j + 1
}
j
}
def decode(src: Array[Byte], from: Int, len: Int): String = {
- val cs = new Array[Char](len);
- String.copyValueOf(cs, 0, decode(src, 0, cs, 0, len));
+ val cs = new Array[Char](len)
+ String.copyValueOf(cs, 0, decode(src, 0, cs, 0, len))
}
}