diff options
Diffstat (limited to 'src/scalap')
28 files changed, 551 insertions, 630 deletions
diff --git a/src/scalap/scala/tools/scalap/Arguments.scala b/src/scalap/scala/tools/scalap/Arguments.scala index 9f139cb5ea..123516bb2d 100644 --- a/src/scalap/scala/tools/scalap/Arguments.scala +++ b/src/scalap/scala/tools/scalap/Arguments.scala @@ -5,7 +5,6 @@ ** */ - package scala.tools.scalap import scala.collection.mutable diff --git a/src/scalap/scala/tools/scalap/ByteArrayReader.scala b/src/scalap/scala/tools/scalap/ByteArrayReader.scala index 9c72bdbf1e..59f083ee76 100644 --- a/src/scalap/scala/tools/scalap/ByteArrayReader.scala +++ b/src/scalap/scala/tools/scalap/ByteArrayReader.scala @@ -5,13 +5,9 @@ ** */ - -package scala -package tools.scalap - +package scala.tools.scalap class ByteArrayReader(content: Array[Byte]) { - import java.io._ /** the buffer containing the file */ @@ -105,9 +101,6 @@ class ByteArrayReader(content: Array[Byte]) { def getDouble(bp: Int): Double = java.lang.Double.longBitsToDouble(getLong(bp)) /** skip next 'n' bytes - */ - def skip(n: Int) { - bp += n - } - + */ + def skip(n: Int): Unit = bp += n } diff --git a/src/scalap/scala/tools/scalap/Classfile.scala b/src/scalap/scala/tools/scalap/Classfile.scala index f62df285f9..d9d264bbbf 100644 --- a/src/scalap/scala/tools/scalap/Classfile.scala +++ b/src/scalap/scala/tools/scalap/Classfile.scala @@ -5,10 +5,8 @@ ** */ - package scala.tools.scalap - class Classfile(in: ByteArrayReader) { import Classfiles._ diff --git a/src/scalap/scala/tools/scalap/Classfiles.scala b/src/scalap/scala/tools/scalap/Classfiles.scala index 9295dd7aff..982a83cfa0 100644 --- a/src/scalap/scala/tools/scalap/Classfiles.scala +++ b/src/scalap/scala/tools/scalap/Classfiles.scala @@ -5,10 +5,8 @@ ** */ - package scala.tools.scalap - object Classfiles { final val JAVA_MAGIC = 0xCAFEBABE final val JAVA_MAJOR_VERSION = 45 diff --git a/src/scalap/scala/tools/scalap/CodeWriter.scala b/src/scalap/scala/tools/scalap/CodeWriter.scala index 168050096d..21c4399d5c 100644 --- a/src/scalap/scala/tools/scalap/CodeWriter.scala +++ b/src/scalap/scala/tools/scalap/CodeWriter.scala @@ -6,13 +6,9 @@ */ -package scala -package tools.scalap +package scala.tools.scalap -import java.io._ - - -class CodeWriter(writer: Writer) { +class CodeWriter(writer: java.io.Writer) { private val nl = scala.compat.Platform.EOL private var step = " " diff --git a/src/scalap/scala/tools/scalap/Decode.scala b/src/scalap/scala/tools/scalap/Decode.scala index 76ce3f4173..69325c1ec8 100644 --- a/src/scalap/scala/tools/scalap/Decode.scala +++ b/src/scalap/scala/tools/scalap/Decode.scala @@ -5,17 +5,14 @@ ** */ -// $Id$ - package scala.tools.scalap -import scala.tools.scalap.scalax.rules.scalasig._ -import scala.tools.nsc.util.ScalaClassLoader -import scala.tools.nsc.util.ScalaClassLoader.appLoader +import scala.tools.scalap.scalasig._ + +import scala.reflect.internal.util.ScalaClassLoader import scala.reflect.internal.pickling.ByteCodecs import ClassFileParser.{ ConstValueIndex, Annotation } -import Main.{ SCALA_SIG, SCALA_SIG_ANNOTATION, BYTES_VALUE } /** Temporary decoder. This would be better off in the scala.tools.nsc * but right now the compiler won't acknowledge scala.tools.scalap @@ -31,7 +28,7 @@ object Decode { /** Return the classfile bytes representing the scala sig classfile attribute. * This has been obsoleted by the switch to annotations. */ - def scalaSigBytes(name: String): Option[Array[Byte]] = scalaSigBytes(name, appLoader) + def scalaSigBytes(name: String): Option[Array[Byte]] = scalaSigBytes(name, ScalaClassLoader.appLoader) def scalaSigBytes(name: String, classLoader: ScalaClassLoader): Option[Array[Byte]] = { val bytes = classLoader.classBytes(name) val reader = new ByteArrayReader(bytes) @@ -39,17 +36,16 @@ object Decode { cf.scalaSigAttribute map (_.data) } - /** Return the bytes representing the annotation - */ - def scalaSigAnnotationBytes(name: String): Option[Array[Byte]] = scalaSigAnnotationBytes(name, appLoader) + /** Return the bytes representing the annotation. */ + def scalaSigAnnotationBytes(name: String): Option[Array[Byte]] = scalaSigAnnotationBytes(name, ScalaClassLoader.appLoader) def scalaSigAnnotationBytes(name: String, classLoader: ScalaClassLoader): Option[Array[Byte]] = { val bytes = classLoader.classBytes(name) val byteCode = ByteCode(bytes) val classFile = ClassFileParser.parse(byteCode) import classFile._ - classFile annotation SCALA_SIG_ANNOTATION map { case Annotation(_, els) => - val bytesElem = els find (x => constant(x.elementNameIndex) == BYTES_VALUE) getOrElse null + classFile annotation Main.SCALA_SIG_ANNOTATION map { case Annotation(_, els) => + val bytesElem = els find (x => constant(x.elementNameIndex) == Main.BYTES_VALUE) getOrElse null val _bytes = bytesElem.elementValue match { case ConstValueIndex(x) => constantWrapped(x) } val bytes = _bytes.asInstanceOf[StringBytesPair].bytes val length = ByteCodecs.decode(bytes) @@ -58,8 +54,7 @@ object Decode { } } - /** private[scala] so nobody gets the idea this is a supported interface. - */ + /** private[scala] so nobody gets the idea this is a supported interface. */ private[scala] def caseParamNames(path: String): Option[List[String]] = { val (outer, inner) = (path indexOf '$') match { case -1 => (path, "") @@ -67,7 +62,7 @@ object Decode { } for { - clazz <- appLoader.tryToLoadClass[AnyRef](outer) + clazz <- ScalaClassLoader.appLoader.tryToLoadClass[AnyRef](outer) ssig <- ScalaSigParser.parse(clazz) } yield { @@ -85,11 +80,10 @@ object Decode { } } - /** Returns a map of Alias -> Type for the given package. - */ + /** Returns a map of Alias -> Type for the given package. */ private[scala] def typeAliases(pkg: String) = { for { - clazz <- appLoader.tryToLoadClass[AnyRef](pkg + ".package") + clazz <- ScalaClassLoader.appLoader.tryToLoadClass[AnyRef](pkg + ".package") ssig <- ScalaSigParser.parse(clazz) } yield { diff --git a/src/scalap/scala/tools/scalap/JavaWriter.scala b/src/scalap/scala/tools/scalap/JavaWriter.scala index 772cf6eacd..1ba89e4702 100644 --- a/src/scalap/scala/tools/scalap/JavaWriter.scala +++ b/src/scalap/scala/tools/scalap/JavaWriter.scala @@ -5,13 +5,11 @@ ** */ - package scala.tools.scalap -import java.io._ import scala.reflect.NameTransformer -class JavaWriter(classfile: Classfile, writer: Writer) extends CodeWriter(writer) { +class JavaWriter(classfile: Classfile, writer: java.io.Writer) extends CodeWriter(writer) { val cf = classfile diff --git a/src/scalap/scala/tools/scalap/Main.scala b/src/scalap/scala/tools/scalap/Main.scala index 5da4227e53..44d7ef6a41 100644 --- a/src/scalap/scala/tools/scalap/Main.scala +++ b/src/scalap/scala/tools/scalap/Main.scala @@ -5,16 +5,16 @@ ** */ -package scala -package tools.scalap +package scala.tools.scalap import java.io.{ PrintStream, OutputStreamWriter, ByteArrayOutputStream } -import scala.reflect.NameTransformer -import scalax.rules.scalasig._ + import scala.tools.nsc.util.{ ClassPath, JavaClassPath } -import scala.tools.util.PathResolver -import ClassPath.DefaultJavaContext -import scala.tools.nsc.io.{ PlainFile, AbstractFile } +import scala.tools.nsc.util.ClassPath.DefaultJavaContext +import scala.tools.nsc.io.AbstractFile + +import scala.tools.scalap.scalasig._ + /**The main object used to execute scalap on the command-line. * @@ -104,7 +104,7 @@ class Main { // we have to encode every fragment of a name separately, otherwise the NameTransformer // will encode using unicode escaping dot separators as well // we can afford allocations because this is not a performance critical code - classname.split('.').map(NameTransformer.encode).mkString(".") + classname.split('.').map(scala.reflect.NameTransformer.encode).mkString(".") } val cls = path.findClass(encName) if (cls.isDefined && cls.get.binary.isDefined) { @@ -185,7 +185,7 @@ object Main extends Main { val cparg = List("-classpath", "-cp") map (arguments getArgument _) reduceLeft (_ orElse _) val path = cparg match { case Some(cp) => new JavaClassPath(DefaultJavaContext.classesInExpandedPath(cp), DefaultJavaContext) - case _ => PathResolver.fromPathString(".") // include '.' in the default classpath SI-6669 + case _ => scala.tools.util.PathResolver.fromPathString(".") // include '.' in the default classpath SI-6669 } // print the classpath if output is verbose if (verbose) diff --git a/src/scalap/scala/tools/scalap/MetaParser.scala b/src/scalap/scala/tools/scalap/MetaParser.scala index 8b4ffb3efd..324330466f 100644 --- a/src/scalap/scala/tools/scalap/MetaParser.scala +++ b/src/scalap/scala/tools/scalap/MetaParser.scala @@ -6,18 +6,15 @@ */ -package scala -package tools.scalap +package scala.tools.scalap -import java.io._ -import java.util._ /** a parser class for parsing meta type information in classfiles * generated by pico. */ class MetaParser(meta: String) { - val scanner = new StringTokenizer(meta, "()[], \t<;", true) + val scanner = new java.util.StringTokenizer(meta, "()[], \t<;", true) var token: String = _ val res = new StringBuffer diff --git a/src/scalap/scala/tools/scalap/Properties.scala b/src/scalap/scala/tools/scalap/Properties.scala index 8f9a9d8606..432dd495e9 100644 --- a/src/scalap/scala/tools/scalap/Properties.scala +++ b/src/scalap/scala/tools/scalap/Properties.scala @@ -9,8 +9,7 @@ package scala.tools.scalap /** Loads decoder.properties from the jar. */ -object Properties extends scala.util.PropertiesTrait -{ +object Properties extends scala.util.PropertiesTrait { protected def propCategory = "decoder" protected def pickJarBasedOn = classOf[Classfile] } diff --git a/src/scalap/scala/tools/scalap/scalax/rules/Memoisable.scala b/src/scalap/scala/tools/scalap/rules/Memoisable.scala index b4ce8cab23..418141bee7 100644 --- a/src/scalap/scala/tools/scalap/scalax/rules/Memoisable.scala +++ b/src/scalap/scala/tools/scalap/rules/Memoisable.scala @@ -10,26 +10,24 @@ // // ----------------------------------------------------------------------------- -package scala.tools.scalap -package scalax -package rules +package scala.tools.scalap.rules import scala.collection.mutable trait MemoisableRules extends Rules { - def memo[In <: Memoisable, Out, A, X](key : AnyRef)(toRule : => In => Result[Out, A, X]) = { + def memo[In <: Memoisable, Out, A, X](key: AnyRef)(toRule: => In => Result[Out, A, X]) = { lazy val rule = toRule from[In] { in => in.memo(key, rule(in)) } } - override def ruleWithName[In, Out, A, X](name : String, f : In => rules.Result[Out, A, X]) = super.ruleWithName(name, (in : In) => in match { - case s : Memoisable => s.memo(name, f(in)) + override def ruleWithName[In, Out, A, X](name: String, f: In => Result[Out, A, X]) = super.ruleWithName(name, (in: In) => in match { + case s: Memoisable => s.memo(name, f(in)) case _ => f(in) }) } trait Memoisable { - def memo[A](key : AnyRef, a : => A) : A + def memo[A](key: AnyRef, a: => A): A } @@ -40,22 +38,19 @@ object DefaultMemoisable { trait DefaultMemoisable extends Memoisable { protected val map = new mutable.HashMap[AnyRef, Any] - def memo[A](key : AnyRef, a : => A) = { + def memo[A](key: AnyRef, a: => A) = { map.getOrElseUpdate(key, compute(key, a)).asInstanceOf[A] } - protected def compute[A](key : AnyRef, a : => A): Any = a match { - case success : Success[_, _] => onSuccess(key, success); success + protected def compute[A](key: AnyRef, a: => A): Any = a match { + case success: Success[_, _] => onSuccess(key, success); success case other => if(DefaultMemoisable.debug) println(key + " -> " + other) other } - protected def onSuccess[S, T](key : AnyRef, result : Success[S, T]) { + protected def onSuccess[S, T](key: AnyRef, result: Success[S, T]) { val Success(out, t) = result if(DefaultMemoisable.debug) println(key + " -> " + t + " (" + out + ")") } } - - - diff --git a/src/scalap/scala/tools/scalap/rules/Result.scala b/src/scalap/scala/tools/scalap/rules/Result.scala new file mode 100644 index 0000000000..ae05416d7a --- /dev/null +++ b/src/scalap/scala/tools/scalap/rules/Result.scala @@ -0,0 +1,69 @@ +// ----------------------------------------------------------------------------- +// +// Scalax - The Scala Community Library +// Copyright (c) 2005-8 The Scalax Project. All rights reserved. +// +// The primary distribution site is http://scalax.scalaforge.org/ +// +// This software is released under the terms of the Revised BSD License. +// There is NO WARRANTY. See the file LICENSE for the full text. +// +// ----------------------------------------------------------------------------- + +package scala.tools.scalap.rules; + +/** Represents the combined value of two rules applied in sequence. + * + * @see the Scala parser combinator + */ +case class ~[+A, +B](_1: A, _2: B) { + override def toString = "(" + _1 + " ~ " + _2 + ")" +} + + +sealed abstract class Result[+Out, +A, +X] { + def out: Out + def value: A + def error: X + + implicit def toOption: Option[A] + + def map[B](f: A => B): Result[Out, B, X] + def mapOut[Out2](f: Out => Out2): Result[Out2, A, X] + def map[Out2, B](f: (Out, A) => (Out2, B)): Result[Out2, B, X] + def flatMap[Out2, B](f: (Out, A) => Result[Out2, B, Nothing]): Result[Out2, B, X] + def orElse[Out2 >: Out, B >: A](other: => Result[Out2, B, Nothing]): Result[Out2, B, X] +} + +case class Success[+Out, +A](out: Out, value: A) extends Result[Out, A, Nothing] { + def error = throw new ScalaSigParserError("No error") + + def toOption = Some(value) + + def map[B](f: A => B): Result[Out, B, Nothing] = Success(out, f(value)) + def mapOut[Out2](f: Out => Out2): Result[Out2, A, Nothing] = Success(f(out), value) + def map[Out2, B](f: (Out, A) => (Out2, B)): Success[Out2, B] = f(out, value) match { case (out2, b) => Success(out2, b) } + def flatMap[Out2, B](f: (Out, A) => Result[Out2, B, Nothing]): Result[Out2, B, Nothing]= f(out, value) + def orElse[Out2 >: Out, B >: A](other: => Result[Out2, B, Nothing]): Result[Out2, B, Nothing] = this +} + +sealed abstract class NoSuccess[+X] extends Result[Nothing, Nothing, X] { + def out = throw new ScalaSigParserError("No output") + def value = throw new ScalaSigParserError("No value") + + def toOption = None + + def map[B](f: Nothing => B) = this + def mapOut[Out2](f: Nothing => Out2) = this + def map[Out2, B](f: (Nothing, Nothing) => (Out2, B)) = this + def flatMap[Out2, B](f: (Nothing, Nothing) => Result[Out2, B, Nothing]) = this + def orElse[Out2, B](other: => Result[Out2, B, Nothing]) = other +} + +case object Failure extends NoSuccess[Nothing] { + def error = throw new ScalaSigParserError("No error") +} + +case class ScalaSigParserError(msg: String) extends RuntimeException(msg) + +case class Error[+X](error: X) extends NoSuccess[X] diff --git a/src/scalap/scala/tools/scalap/rules/Rule.scala b/src/scalap/scala/tools/scalap/rules/Rule.scala new file mode 100644 index 0000000000..0a00111f7a --- /dev/null +++ b/src/scalap/scala/tools/scalap/rules/Rule.scala @@ -0,0 +1,172 @@ +// ----------------------------------------------------------------------------- +// +// Scalax - The Scala Community Library +// Copyright (c) 2005-8 The Scalax Project. All rights reserved. +// +// The primary distribution site is http://scalax.scalaforge.org/ +// +// This software is released under the terms of the Revised BSD License. +// There is NO WARRANTY. See the file LICENSE for the full text. +// +// ----------------------------------------------------------------------------- + +package scala.tools.scalap.rules + +/** A Rule is a function from some input to a Result. The result may be: + * <ul> + * <li>Success, with a value of some type and an output that may serve as the input to subsequent rules.</li> + * <li>Failure. A failure may result in some alternative rule being applied.</li> + * <li>Error. No further rules should be attempted.</li> + * </ul> + * + * @author Andrew Foggin + * + * Inspired by the Scala parser combinator. + */ +trait Rule[-In, +Out, +A, +X] extends (In => Result[Out, A, X]) { + val factory: Rules + import factory._ + + def as(name: String) = ruleWithName(name, this) + + def flatMap[Out2, B, X2 >: X](fa2ruleb: A => Out => Result[Out2, B, X2]) = mapResult { + case Success(out, a) => fa2ruleb(a)(out) + case Failure => Failure + case err @ Error(_) => err + } + + def map[B](fa2b: A => B) = flatMap { a => out => Success(out, fa2b(a)) } + + def filter(f: A => Boolean) = flatMap { a => out => if(f(a)) Success(out, a) else Failure } + + def mapResult[Out2, B, Y](f: Result[Out, A, X] => Result[Out2, B, Y]) = rule { + in: In => f(apply(in)) + } + + def orElse[In2 <: In, Out2 >: Out, A2 >: A, X2 >: X](other: => Rule[In2, Out2, A2, X2]): Rule[In2, Out2, A2, X2] = new Choice[In2, Out2, A2, X2] { + val factory = Rule.this.factory + lazy val choices = Rule.this :: other :: Nil + } + + def orError[In2 <: In] = this orElse error[Any] + + def |[In2 <: In, Out2 >: Out, A2 >: A, X2 >: X](other: => Rule[In2, Out2, A2, X2]) = orElse(other) + + def ^^[B](fa2b: A => B) = map(fa2b) + + def ^^?[B](pf: PartialFunction[A, B]) = filter (pf.isDefinedAt(_)) ^^ pf + + def ??(pf: PartialFunction[A, Any]) = filter (pf.isDefinedAt(_)) + + def -^[B](b: B) = map { any => b } + + /** Maps an Error */ + def !^[Y](fx2y: X => Y) = mapResult { + case s @ Success(_, _) => s + case Failure => Failure + case Error(x) => Error(fx2y(x)) + } + + def >>[Out2, B, X2 >: X](fa2ruleb: A => Out => Result[Out2, B, X2]) = flatMap(fa2ruleb) + + def >->[Out2, B, X2 >: X](fa2resultb: A => Result[Out2, B, X2]) = flatMap { a => any => fa2resultb(a) } + + def >>?[Out2, B, X2 >: X](pf: PartialFunction[A, Rule[Out, Out2, B, X2]]) = filter(pf isDefinedAt _) flatMap pf + + def >>&[B, X2 >: X](fa2ruleb: A => Out => Result[Any, B, X2]) = flatMap { a => out => fa2ruleb(a)(out) mapOut { any => out } } + + def ~[Out2, B, X2 >: X](next: => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next) yield new ~(a, b) + + def ~-[Out2, B, X2 >: X](next: => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next) yield a + + def -~[Out2, B, X2 >: X](next: => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next) yield b + + def ~++[Out2, B >: A, X2 >: X](next: => Rule[Out, Out2, Seq[B], X2]) = for (a <- this; b <- next) yield a :: b.toList + + /** Apply the result of this rule to the function returned by the next rule */ + def ~>[Out2, B, X2 >: X](next: => Rule[Out, Out2, A => B, X2]) = for (a <- this; fa2b <- next) yield fa2b(a) + + /** Apply the result of this rule to the function returned by the previous rule */ + def <~:[InPrev, B, X2 >: X](prev: => Rule[InPrev, In, A => B, X2]) = for (fa2b <- prev; a <- this) yield fa2b(a) + + def ~![Out2, B, X2 >: X](next: => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next.orError) yield new ~(a, b) + + def ~-![Out2, B, X2 >: X](next: => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next.orError) yield a + + def -~![Out2, B, X2 >: X](next: => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next.orError) yield b + + def -[In2 <: In](exclude: => Rule[In2, Any, Any, Any]) = !exclude -~ this + + /** ^~^(f) is equivalent to ^^ { case b1 ~ b2 => f(b1, b2) } + */ + def ^~^[B1, B2, B >: A <% B1 ~ B2, C](f: (B1, B2) => C) = map { a => + (a: B1 ~ B2) match { case b1 ~ b2 => f(b1, b2) } + } + + /** ^~~^(f) is equivalent to ^^ { case b1 ~ b2 ~ b3 => f(b1, b2, b3) } + */ + def ^~~^[B1, B2, B3, B >: A <% B1 ~ B2 ~ B3, C](f: (B1, B2, B3) => C) = map { a => + (a: B1 ~ B2 ~ B3) match { case b1 ~ b2 ~ b3 => f(b1, b2, b3) } + } + + /** ^~~~^(f) is equivalent to ^^ { case b1 ~ b2 ~ b3 ~ b4 => f(b1, b2, b3, b4) } + */ + def ^~~~^[B1, B2, B3, B4, B >: A <% B1 ~ B2 ~ B3 ~ B4, C](f: (B1, B2, B3, B4) => C) = map { a => + (a: B1 ~ B2 ~ B3 ~ B4) match { case b1 ~ b2 ~ b3 ~ b4 => f(b1, b2, b3, b4) } + } + + /** ^~~~~^(f) is equivalent to ^^ { case b1 ~ b2 ~ b3 ~ b4 ~ b5 => f(b1, b2, b3, b4, b5) } + */ + def ^~~~~^[B1, B2, B3, B4, B5, B >: A <% B1 ~ B2 ~ B3 ~ B4 ~ B5, C](f: (B1, B2, B3, B4, B5) => C) = map { a => + (a: B1 ~ B2 ~ B3 ~ B4 ~ B5) match { case b1 ~ b2 ~ b3 ~ b4 ~ b5 => f(b1, b2, b3, b4, b5) } + } + + /** ^~~~~~^(f) is equivalent to ^^ { case b1 ~ b2 ~ b3 ~ b4 ~ b5 ~ b6 => f(b1, b2, b3, b4, b5, b6) } + */ + def ^~~~~~^[B1, B2, B3, B4, B5, B6, B >: A <% B1 ~ B2 ~ B3 ~ B4 ~ B5 ~ B6, C](f: (B1, B2, B3, B4, B5, B6) => C) = map { a => + (a: B1 ~ B2 ~ B3 ~ B4 ~ B5 ~ B6) match { case b1 ~ b2 ~ b3 ~ b4 ~ b5 ~ b6 => f(b1, b2, b3, b4, b5, b6) } + } + + /** ^~~~~~~^(f) is equivalent to ^^ { case b1 ~ b2 ~ b3 ~ b4 ~ b5 ~ b6 => f(b1, b2, b3, b4, b5, b6) } + */ + def ^~~~~~~^[B1, B2, B3, B4, B5, B6, B7, B >: A <% B1 ~ B2 ~ B3 ~ B4 ~ B5 ~ B6 ~ B7, C](f: (B1, B2, B3, B4, B5, B6, B7) => C) = map { a => + (a: B1 ~ B2 ~ B3 ~ B4 ~ B5 ~ B6 ~ B7) match { case b1 ~ b2 ~ b3 ~ b4 ~ b5 ~ b6 ~b7 => f(b1, b2, b3, b4, b5, b6, b7) } + } + + /** >~>(f) is equivalent to >> { case b1 ~ b2 => f(b1, b2) } + */ + def >~>[Out2, B1, B2, B >: A <% B1 ~ B2, C, X2 >: X](f: (B1, B2) => Out => Result[Out2, C, X2]) = flatMap { a => + (a: B1 ~ B2) match { case b1 ~ b2 => f(b1, b2) } + } + + /** ^-^(f) is equivalent to ^^ { b2 => b1 => f(b1, b2) } + */ + def ^-^ [B1, B2 >: A, C](f: (B1, B2) => C) = map { b2: B2 => b1: B1 => f(b1, b2) } + + /** ^~>~^(f) is equivalent to ^^ { case b2 ~ b3 => b1 => f(b1, b2, b3) } + */ + def ^~>~^ [B1, B2, B3, B >: A <% B2 ~ B3, C](f: (B1, B2, B3) => C) = map { a => + (a: B2 ~ B3) match { case b2 ~ b3 => b1: B1 => f(b1, b2, b3) } + } +} + + +trait Choice[-In, +Out, +A, +X] extends Rule[In, Out, A, X] { + def choices: List[Rule[In, Out, A, X]] + + def apply(in: In) = { + def oneOf(list: List[Rule[In, Out, A, X]]): Result[Out, A, X] = list match { + case Nil => Failure + case first :: rest => first(in) match { + case Failure => oneOf(rest) + case result => result + } + } + oneOf(choices) + } + + override def orElse[In2 <: In, Out2 >: Out, A2 >: A, X2 >: X](other: => Rule[In2, Out2, A2, X2]): Rule[In2, Out2, A2, X2] = new Choice[In2, Out2, A2, X2] { + val factory = Choice.this.factory + lazy val choices = Choice.this.choices ::: other :: Nil + } +} diff --git a/src/scalap/scala/tools/scalap/scalax/rules/Rules.scala b/src/scalap/scala/tools/scalap/rules/Rules.scala index 70926208b3..bdcc81c22d 100644 --- a/src/scalap/scala/tools/scalap/scalax/rules/Rules.scala +++ b/src/scalap/scala/tools/scalap/rules/Rules.scala @@ -11,11 +11,10 @@ // ----------------------------------------------------------------------------- package scala.tools.scalap -package scalax package rules trait Name { - def name : String + def name: String override def toString = name } @@ -26,13 +25,18 @@ trait Name { * Inspired by the Scala parser combinator. */ trait Rules { - implicit def rule[In, Out, A, X](f : In => Result[Out, A, X]) : Rule[In, Out, A, X] = new DefaultRule(f) - implicit def inRule[In, Out, A, X](rule : Rule[In, Out, A, X]) : InRule[In, Out, A, X] = new InRule(rule) - implicit def seqRule[In, A, X](rule : Rule[In, In, A, X]) : SeqRule[In, A, X] = new SeqRule(rule) + import scala.language.implicitConversions + implicit def rule[In, Out, A, X](f: In => Result[Out, A, X]): Rule[In, Out, A, X] = new DefaultRule(f) + implicit def inRule[In, Out, A, X](rule: Rule[In, Out, A, X]): InRule[In, Out, A, X] = new InRule(rule) + implicit def seqRule[In, A, X](rule: Rule[In, In, A, X]): SeqRule[In, A, X] = new SeqRule(rule) - def from[In] = new { - def apply[Out, A, X](f : In => Result[Out, A, X]) = rule(f) + trait FromRule[In] { + def apply[Out, A, X](f: In => Result[Out, A, X]): Rule[In, Out, A, X] + } + + def from[In] = new FromRule[In] { + def apply[Out, A, X](f: In => Result[Out, A, X]) = rule(f) } def state[s] = new StateRules { @@ -40,30 +44,30 @@ trait Rules { val factory = Rules.this } - def success[Out, A](out : Out, a : A) = rule { in : Any => Success(out, a) } + def success[Out, A](out: Out, a: A) = rule { in: Any => Success(out, a) } - def failure = rule { in : Any => Failure } + def failure = rule { in: Any => Failure } - def error[In] = rule { in : In => Error(in) } - def error[X](err : X) = rule { in : Any => Error(err) } + def error[In] = rule { in: In => Error(in) } + def error[X](err: X) = rule { in: Any => Error(err) } - def oneOf[In, Out, A, X](rules : Rule[In, Out, A, X] *) : Rule[In, Out, A, X] = new Choice[In, Out, A, X] { + def oneOf[In, Out, A, X](rules: Rule[In, Out, A, X] *): Rule[In, Out, A, X] = new Choice[In, Out, A, X] { val factory = Rules.this val choices = rules.toList } - def ruleWithName[In, Out, A, X](_name : String, f : In => Result[Out, A, X]) : Rule[In, Out, A, X] with Name = + def ruleWithName[In, Out, A, X](_name: String, f: In => Result[Out, A, X]): Rule[In, Out, A, X] with Name = new DefaultRule(f) with Name { val name = _name } - class DefaultRule[In, Out, A, X](f : In => Result[Out, A, X]) extends Rule[In, Out, A, X] { + class DefaultRule[In, Out, A, X](f: In => Result[Out, A, X]) extends Rule[In, Out, A, X] { val factory = Rules.this - def apply(in : In) = f(in) + def apply(in: In) = f(in) } /** Converts a rule into a function that throws an Exception on failure. */ - def expect[In, Out, A, Any](rule : Rule[In, Out, A, Any]) : In => A = (in) => rule(in) match { + def expect[In, Out, A, Any](rule: Rule[In, Out, A, Any]): In => A = (in) => rule(in) match { case Success(_, a) => a case Failure => throw new ScalaSigParserError("Unexpected failure") case Error(x) => throw new ScalaSigParserError("Unexpected error: " + x) @@ -82,30 +86,30 @@ trait StateRules { type S type Rule[+A, +X] = rules.Rule[S, S, A, X] - val factory : Rules + val factory: Rules import factory._ - def apply[A, X](f : S => Result[S, A, X]) = rule(f) + def apply[A, X](f: S => Result[S, A, X]) = rule(f) - def unit[A](a : => A) = apply { s => Success(s, a) } - def read[A](f : S => A) = apply { s => Success(s, f(s)) } + def unit[A](a: => A) = apply { s => Success(s, a) } + def read[A](f: S => A) = apply { s => Success(s, f(s)) } def get = apply { s => Success(s, s) } - def set(s : => S) = apply { oldS => Success(s, oldS) } + def set(s: => S) = apply { oldS => Success(s, oldS) } - def update(f : S => S) = apply { s => Success(s, f(s)) } + def update(f: S => S) = apply { s => Success(s, f(s)) } def nil = unit(Nil) def none = unit(None) /** Create a rule that identities if f(in) is true. */ - def cond(f : S => Boolean) = get filter f + def cond(f: S => Boolean) = get filter f /** Create a rule that succeeds if all of the given rules succeed. @param rules the rules to apply in sequence. */ - def allOf[A, X](rules : Seq[Rule[A, X]]) = { - def rep(in : S, rules : List[Rule[A, X]], results : List[A]) : Result[S, List[A], X] = { + def allOf[A, X](rules: Seq[Rule[A, X]]) = { + def rep(in: S, rules: List[Rule[A, X]], results: List[A]): Result[S, List[A], X] = { rules match { case Nil => Success(in, results.reverse) case rule::tl => rule(in) match { @@ -115,19 +119,19 @@ trait StateRules { } } } - in : S => rep(in, rules.toList, Nil) + in: S => rep(in, rules.toList, Nil) } /** Create a rule that succeeds with a list of all the provided rules that succeed. @param rules the rules to apply in sequence. */ - def anyOf[A, X](rules : Seq[Rule[A, X]]) = allOf(rules.map(_ ?)) ^^ { opts => opts.flatMap(x => x) } + def anyOf[A, X](rules: Seq[Rule[A, X]]) = allOf(rules.map(_ ?)) ^^ { opts => opts.flatMap(x => x) } /** Repeatedly apply a rule from initial value until finished condition is met. */ - def repeatUntil[T, X](rule : Rule[T => T, X])(finished : T => Boolean)(initial : T) = apply { + def repeatUntil[T, X](rule: Rule[T => T, X])(finished: T => Boolean)(initial: T) = apply { // more compact using HoF but written this way so it's tail-recursive - def rep(in : S, t : T) : Result[S, T, X] = { + def rep(in: S, t: T): Result[S, T, X] = { if (finished(t)) Success(in, t) else rule(in) match { case Success(out, f) => rep(out, f(t)) // SI-5189 f.asInstanceOf[T => T] diff --git a/src/scalap/scala/tools/scalap/scalax/rules/SeqRule.scala b/src/scalap/scala/tools/scalap/rules/SeqRule.scala index 51a789e041..e96a38b6be 100644 --- a/src/scalap/scala/tools/scalap/scalax/rules/SeqRule.scala +++ b/src/scalap/scala/tools/scalap/rules/SeqRule.scala @@ -10,81 +10,79 @@ // // ----------------------------------------------------------------------------- -package scala.tools.scalap -package scalax -package rules +package scala.tools.scalap.rules /** * A workaround for the difficulties of dealing with * a contravariant 'In' parameter type... */ -class InRule[In, +Out, +A, +X](rule : Rule[In, Out, A, X]) { +class InRule[In, +Out, +A, +X](rule: Rule[In, Out, A, X]) { - def mapRule[Out2, B, Y](f : Result[Out, A, X] => In => Result[Out2, B, Y]) : Rule[In, Out2, B, Y] = rule.factory.rule { - in : In => f(rule(in))(in) + def mapRule[Out2, B, Y](f: Result[Out, A, X] => In => Result[Out2, B, Y]): Rule[In, Out2, B, Y] = rule.factory.rule { + in: In => f(rule(in))(in) } /** Creates a rule that succeeds only if the original rule would fail on the given context. */ def unary_! : Rule[In, In, Unit, Nothing] = mapRule { - case Success(_, _) => in : In => Failure - case _ => in : In => Success(in, ()) + case Success(_, _) => in: In => Failure + case _ => in: In => Success(in, ()) } /** Creates a rule that succeeds if the original rule succeeds, but returns the original input. */ def & : Rule[In, In, A, X] = mapRule { - case Success(_, a) => in : In => Success(in, a) - case Failure => in : In => Failure - case Error(x) => in : In => Error(x) + case Success(_, a) => in: In => Success(in, a) + case Failure => in: In => Failure + case Error(x) => in: In => Error(x) } } -class SeqRule[S, +A, +X](rule : Rule[S, S, A, X]) { +class SeqRule[S, +A, +X](rule: Rule[S, S, A, X]) { import rule.factory._ def ? = rule mapRule { - case Success(out, a) => in : S => Success(out, Some(a)) - case Failure => in : S => Success(in, None) - case Error(x) => in : S => Error(x) + case Success(out, a) => in: S => Success(out, Some(a)) + case Failure => in: S => Success(in, None) + case Error(x) => in: S => Error(x) } /** Creates a rule that always succeeds with a Boolean value. * Value is 'true' if this rule succeeds, 'false' otherwise */ - def -? = ? map { _ isDefined } + def -? = ? map { _.isDefined } def * = from[S] { // tail-recursive function with reverse list accumulator - def rep(in : S, acc : List[A]) : Result[S, List[A], X] = rule(in) match { + def rep(in: S, acc: List[A]): Result[S, List[A], X] = rule(in) match { case Success(out, a) => rep(out, a :: acc) case Failure => Success(in, acc.reverse) - case err : Error[_] => err + case err: Error[_] => err } in => rep(in, Nil) } def + = rule ~++ * - def ~>?[B >: A, X2 >: X](f : => Rule[S, S, B => B, X2]) = for (a <- rule; fs <- f?) yield fs.foldLeft[B](a) { (b, f) => f(b) } + def ~>?[B >: A, X2 >: X](f: => Rule[S, S, B => B, X2]) = for (a <- rule; fs <- f?) yield fs.foldLeft[B](a) { (b, f) => f(b) } - def ~>*[B >: A, X2 >: X](f : => Rule[S, S, B => B, X2]) = for (a <- rule; fs <- f*) yield fs.foldLeft[B](a) { (b, f) => f(b) } + def ~>*[B >: A, X2 >: X](f: => Rule[S, S, B => B, X2]) = for (a <- rule; fs <- f*) yield fs.foldLeft[B](a) { (b, f) => f(b) } - def ~*~[B >: A, X2 >: X](join : => Rule[S, S, (B, B) => B, X2]) = { - this ~>* (for (f <- join; a <- rule) yield f(_ : B, a)) + def ~*~[B >: A, X2 >: X](join: => Rule[S, S, (B, B) => B, X2]) = { + this ~>* (for (f <- join; a <- rule) yield f(_: B, a)) } /** Repeats this rule one or more times with a separator (which is discarded) */ - def +/[X2 >: X](sep : => Rule[S, S, Any, X2]) = rule ~++ (sep -~ rule *) + def +/[X2 >: X](sep: => Rule[S, S, Any, X2]) = rule ~++ (sep -~ rule *) /** Repeats this rule zero or more times with a separator (which is discarded) */ - def */[X2 >: X](sep : => Rule[S, S, Any, X2]) = +/(sep) | state[S].nil + def */[X2 >: X](sep: => Rule[S, S, Any, X2]) = +/(sep) | state[S].nil - def *~-[Out, X2 >: X](end : => Rule[S, Out, Any, X2]) = (rule - end *) ~- end - def +~-[Out, X2 >: X](end : => Rule[S, Out, Any, X2]) = (rule - end +) ~- end + def *~-[Out, X2 >: X](end: => Rule[S, Out, Any, X2]) = (rule - end *) ~- end + def +~-[Out, X2 >: X](end: => Rule[S, Out, Any, X2]) = (rule - end +) ~- end /** Repeats this rule num times */ - def times(num : Int) : Rule[S, S, Seq[A], X] = from[S] { + def times(num: Int): Rule[S, S, Seq[A], X] = from[S] { val result = new scala.collection.mutable.ArraySeq[A](num) // more compact using HoF but written this way so it's tail-recursive - def rep(i : Int, in : S) : Result[S, Seq[A], X] = { + def rep(i: Int, in: S): Result[S, Seq[A], X] = { if (i == num) Success(in, result) else rule(in) match { case Success(out, a) => { @@ -92,10 +90,9 @@ class SeqRule[S, +A, +X](rule : Rule[S, S, A, X]) { rep(i + 1, out) } case Failure => Failure - case err : Error[_] => err + case err: Error[_] => err } } in => rep(0, in) } } - diff --git a/src/scalap/scala/tools/scalap/rules/package.scala b/src/scalap/scala/tools/scalap/rules/package.scala new file mode 100644 index 0000000000..dcd5f7ac00 --- /dev/null +++ b/src/scalap/scala/tools/scalap/rules/package.scala @@ -0,0 +1,6 @@ +package scala.tools.scalap + +package object rules { + // make some language features in this package compile without warning + implicit def postfixOps = scala.language.postfixOps +} diff --git a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/ClassFileParser.scala b/src/scalap/scala/tools/scalap/scalasig/ClassFileParser.scala index 1a4b3456b8..9bd8402ccc 100644 --- a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/ClassFileParser.scala +++ b/src/scalap/scala/tools/scalap/scalasig/ClassFileParser.scala @@ -1,18 +1,11 @@ -package scala.tools.scalap -package scalax -package rules -package scalasig +package scala.tools.scalap.scalasig - -import java.io.IOException - -import scala._ -import scala.Predef._ +import scala.tools.scalap.rules.{ Success, Failure, ~, RulesWithState } object ByteCode { - def apply(bytes : Array[Byte]) = new ByteCode(bytes, 0, bytes.length) + def apply(bytes: Array[Byte]) = new ByteCode(bytes, 0, bytes.length) - def forClass(clazz : Class[_]) = { + def forClass(clazz: Class[_]) = { val name = clazz.getName val subPath = name.substring(name.lastIndexOf('.') + 1) + ".class" val in = clazz.getResourceAsStream(subPath) @@ -22,7 +15,7 @@ object ByteCode { val bytes = new Array[Byte](rest) while (rest > 0) { val res = in.read(bytes, bytes.length - rest, rest) - if (res == -1) throw new IOException("read error") + if (res == -1) throw new java.io.IOException("read error") rest -= res } ByteCode(bytes) @@ -33,19 +26,18 @@ object ByteCode { } } -/** Represents a chunk of raw bytecode. Used as input for the parsers - */ -class ByteCode(val bytes : Array[Byte], val pos : Int, val length : Int) { +/** Represents a chunk of raw bytecode. Used as input for the parsers. */ +class ByteCode(val bytes: Array[Byte], val pos: Int, val length: Int) { assert(pos >= 0 && length >= 0 && pos + length <= bytes.length) def nextByte = if (length == 0) Failure else Success(drop(1), bytes(pos)) - def next(n : Int) = if (length >= n) Success(drop(n), take(n)) else Failure + def next(n: Int) = if (length >= n) Success(drop(n), take(n)) else Failure - def take(n : Int) = new ByteCode(bytes, pos, n) - def drop(n : Int) = new ByteCode(bytes, pos + n, length - n) + def take(n: Int) = new ByteCode(bytes, pos, n) + def drop(n: Int) = new ByteCode(bytes, pos + n, length - n) - def fold[X](x : X)(f : (X, Byte) => X) : X = { + def fold[X](x: X)(f: (X, Byte) => X): X = { var result = x var i = pos while (i < pos + length) { @@ -72,7 +64,7 @@ class ByteCode(val bytes : Array[Byte], val pos : Int, val length : Int) { StringBytesPair(str, chunk) } - def byte(i : Int) = bytes(pos) & 0xFF + def byte(i: Int) = bytes(pos) & 0xFF } /** @@ -86,22 +78,22 @@ trait ByteCodeReader extends RulesWithState { type S = ByteCode type Parser[A] = Rule[A, String] - val byte = apply(_ nextByte) + val byte = apply(_.nextByte) val u1 = byte ^^ (_ & 0xFF) - val u2 = bytes(2) ^^ (_ toInt) - val u4 = bytes(4) ^^ (_ toInt) // should map to Long?? + val u2 = bytes(2) ^^ (_.toInt) + val u4 = bytes(4) ^^ (_.toInt) // should map to Long?? - def bytes(n : Int) = apply(_ next n) + def bytes(n: Int) = apply(_ next n) } object ClassFileParser extends ByteCodeReader { - def parse(byteCode : ByteCode) = expect(classFile)(byteCode) + def parse(byteCode: ByteCode) = expect(classFile)(byteCode) def parseAnnotations(byteCode: ByteCode) = expect(annotations)(byteCode) val magicNumber = (u4 filter (_ == 0xCAFEBABE)) | error("Not a valid class file") val version = u2 ~ u2 ^^ { case minor ~ major => (major, minor) } - val constantPool = (u2 ^^ ConstantPool) >> repeatUntil(constantPoolEntry)(_ isFull) + val constantPool = (u2 ^^ ConstantPool) >> repeatUntil(constantPoolEntry)(_.isFull) // NOTE currently most constants just evaluate to a string description // TODO evaluate to useful values @@ -169,19 +161,19 @@ object ClassFileParser extends ByteCodeReader { val classFile = header ~ fields ~ methods ~ attributes ~- !u1 ^~~~^ ClassFile // TODO create a useful object, not just a string - def memberRef(description : String) = u2 ~ u2 ^^ add1 { + def memberRef(description: String) = u2 ~ u2 ^^ add1 { case classRef ~ nameAndTypeRef => pool => description + ": " + pool(classRef) + ", " + pool(nameAndTypeRef) } - def add1[T](f : T => ConstantPool => Any)(raw : T)(pool : ConstantPool) = pool add f(raw) - def add2[T](f : T => ConstantPool => Any)(raw : T)(pool : ConstantPool) = pool add f(raw) add { pool => "<empty>" } + def add1[T](f: T => ConstantPool => Any)(raw: T)(pool: ConstantPool) = pool add f(raw) + def add2[T](f: T => ConstantPool => Any)(raw: T)(pool: ConstantPool) = pool add f(raw) add { pool => "<empty>" } } case class ClassFile( - header : ClassFileHeader, - fields : Seq[Field], - methods : Seq[Method], - attributes : Seq[Attribute]) { + header: ClassFileHeader, + fields: Seq[Field], + methods: Seq[Method], + attributes: Seq[Attribute]) { def majorVersion = header.major def minorVersion = header.minor @@ -190,14 +182,14 @@ case class ClassFile( def superClass = constant(header.superClassIndex) def interfaces = header.interfaces.map(constant) - def constant(index : Int) = header.constants(index) match { + def constant(index: Int) = header.constants(index) match { case StringBytesPair(str, _) => str case z => z } def constantWrapped(index: Int) = header.constants(index) - def attribute(name : String) = attributes.find {attrib => constant(attrib.nameIndex) == name } + def attribute(name: String) = attributes.find {attrib => constant(attrib.nameIndex) == name } val RUNTIME_VISIBLE_ANNOTATIONS = "RuntimeVisibleAnnotations" def annotations = (attributes.find(attr => constant(attr.nameIndex) == RUNTIME_VISIBLE_ANNOTATIONS) @@ -206,23 +198,23 @@ case class ClassFile( def annotation(name: String) = annotations.flatMap(seq => seq.find(annot => constant(annot.typeIndex) == name)) } -case class Attribute(nameIndex : Int, byteCode : ByteCode) -case class Field(flags : Int, nameIndex : Int, descriptorIndex : Int, attributes : Seq[Attribute]) -case class Method(flags : Int, nameIndex : Int, descriptorIndex : Int, attributes : Seq[Attribute]) +case class Attribute(nameIndex: Int, byteCode: ByteCode) +case class Field(flags: Int, nameIndex: Int, descriptorIndex: Int, attributes: Seq[Attribute]) +case class Method(flags: Int, nameIndex: Int, descriptorIndex: Int, attributes: Seq[Attribute]) case class ClassFileHeader( - minor : Int, - major : Int, - constants : ConstantPool, - flags : Int, - classIndex : Int, - superClassIndex : Int, - interfaces : Seq[Int]) { - - def constant(index : Int) = constants(index) + minor: Int, + major: Int, + constants: ConstantPool, + flags: Int, + classIndex: Int, + superClassIndex: Int, + interfaces: Seq[Int]) { + + def constant(index: Int) = constants(index) } -case class ConstantPool(len : Int) { +case class ConstantPool(len: Int) { val size = len - 1 private val buffer = new scala.collection.mutable.ArrayBuffer[ConstantPool => Any] @@ -230,7 +222,7 @@ case class ConstantPool(len : Int) { def isFull = buffer.length >= size - def apply(index : Int) = { + def apply(index: Int) = { // Note constant pool indices are 1-based val i = index - 1 values(i) getOrElse { @@ -241,9 +233,8 @@ case class ConstantPool(len : Int) { } } - def add(f : ConstantPool => Any) = { + def add(f: ConstantPool => Any) = { buffer += f this } } - diff --git a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/Flags.scala b/src/scalap/scala/tools/scalap/scalasig/Flags.scala index 218639e4a2..b9925150d2 100644 --- a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/Flags.scala +++ b/src/scalap/scala/tools/scalap/scalasig/Flags.scala @@ -1,10 +1,7 @@ -package scala.tools.scalap -package scalax -package rules -package scalasig +package scala.tools.scalap.scalasig trait Flags { - def hasFlag(flag : Long) : Boolean + def hasFlag(flag: Long): Boolean def isImplicit = hasFlag(0x00000001) def isFinal = hasFlag(0x00000002) diff --git a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/ScalaSig.scala b/src/scalap/scala/tools/scalap/scalasig/ScalaSig.scala index fd70e0de35..311e4acd6f 100644 --- a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/ScalaSig.scala +++ b/src/scalap/scala/tools/scalap/scalasig/ScalaSig.scala @@ -5,24 +5,25 @@ ** */ +package scala.tools.scalap.scalasig -package scala.tools.scalap -package scalax -package rules -package scalasig +import scala.language.implicitConversions -import ClassFileParser.{ ConstValueIndex, Annotation } import scala.reflect.internal.pickling.ByteCodecs +import scala.tools.scalap.Main +import scala.tools.scalap.rules._ + +import ClassFileParser.{ ConstValueIndex, Annotation } + object ScalaSigParser { - import Main.{ SCALA_SIG, SCALA_SIG_ANNOTATION, BYTES_VALUE } def scalaSigFromAnnotation(classFile: ClassFile): Option[ScalaSig] = { import classFile._ - classFile.annotation(SCALA_SIG_ANNOTATION) map { + classFile.annotation(Main.SCALA_SIG_ANNOTATION) map { case Annotation(_, elements) => - val bytesElem = elements.find(elem => constant(elem.elementNameIndex) == BYTES_VALUE).get + val bytesElem = elements.find(elem => constant(elem.elementNameIndex) == Main.BYTES_VALUE).get val bytes = ((bytesElem.elementValue match {case ConstValueIndex(index) => constantWrapped(index)}) .asInstanceOf[StringBytesPair].bytes) val length = ByteCodecs.decode(bytes) @@ -31,8 +32,8 @@ object ScalaSigParser { } } - def scalaSigFromAttribute(classFile: ClassFile) : Option[ScalaSig] = - classFile.attribute(SCALA_SIG).map(_.byteCode).map(ScalaSigAttributeParsers.parse) + def scalaSigFromAttribute(classFile: ClassFile): Option[ScalaSig] = + classFile.attribute(Main.SCALA_SIG).map(_.byteCode).map(ScalaSigAttributeParsers.parse) def parse(classFile: ClassFile): Option[ScalaSig] = { val scalaSig = scalaSigFromAttribute(classFile) @@ -45,7 +46,7 @@ object ScalaSigParser { } } - def parse(clazz : Class[_]): Option[ScalaSig] = { + def parse(clazz: Class[_]): Option[ScalaSig] = { val byteCode = ByteCode.forClass(clazz) val classFile = ClassFileParser.parse(byteCode) @@ -54,10 +55,10 @@ object ScalaSigParser { } object ScalaSigAttributeParsers extends ByteCodeReader { - def parse(byteCode : ByteCode) = expect(scalaSig)(byteCode) + def parse(byteCode: ByteCode) = expect(scalaSig)(byteCode) val nat = apply { - def natN(in : ByteCode, x : Int) : Result[ByteCode, Int, Nothing] = in.nextByte match { + def natN(in: ByteCode, x: Int): Result[ByteCode, Int, Nothing] = in.nextByte match { case Success(out, b) => { val y = (x << 7) + (b & 0x7f) if ((b & 0x80) == 0) Success(out, y) else natN(out, y) @@ -76,33 +77,33 @@ object ScalaSigAttributeParsers extends ByteCodeReader { val longValue = read(_ toLong) } -case class ScalaSig(majorVersion : Int, minorVersion : Int, table : Seq[Int ~ ByteCode]) extends DefaultMemoisable { +case class ScalaSig(majorVersion: Int, minorVersion: Int, table: Seq[Int ~ ByteCode]) extends DefaultMemoisable { - case class Entry(index : Int, entryType : Int, byteCode : ByteCode) extends DefaultMemoisable { + case class Entry(index: Int, entryType: Int, byteCode: ByteCode) extends DefaultMemoisable { def scalaSig = ScalaSig.this - def setByteCode(byteCode : ByteCode) = Entry(index, entryType, byteCode) + def setByteCode(byteCode: ByteCode) = Entry(index, entryType, byteCode) } - def hasEntry(index : Int) = table isDefinedAt index + def hasEntry(index: Int) = table isDefinedAt index - def getEntry(index : Int) = { + def getEntry(index: Int) = { val entryType ~ byteCode = table(index) Entry(index, entryType, byteCode) } - def parseEntry(index : Int) = applyRule(ScalaSigParsers.parseEntry(ScalaSigEntryParsers.entry)(index)) + def parseEntry(index: Int) = applyRule(ScalaSigParsers.parseEntry(ScalaSigEntryParsers.entry)(index)) - implicit def applyRule[A](parser : ScalaSigParsers.Parser[A]) = ScalaSigParsers.expect(parser)(this) + implicit def applyRule[A](parser: ScalaSigParsers.Parser[A]) = ScalaSigParsers.expect(parser)(this) override def toString = "ScalaSig version " + majorVersion + "." + minorVersion + { for (i <- 0 until table.size) yield i + ":\t" + parseEntry(i) // + "\n\t" + getEntry(i) }.mkString("\n", "\n", "") - lazy val symbols : Seq[Symbol] = ScalaSigParsers.symbols + lazy val symbols: Seq[Symbol] = ScalaSigParsers.symbols - lazy val topLevelClasses : List[ClassSymbol] = ScalaSigParsers.topLevelClasses - lazy val topLevelObjects : List[ObjectSymbol] = ScalaSigParsers.topLevelObjects + lazy val topLevelClasses: List[ClassSymbol] = ScalaSigParsers.topLevelClasses + lazy val topLevelObjects: List[ObjectSymbol] = ScalaSigParsers.topLevelObjects } object ScalaSigParsers extends RulesWithState with MemoisableRules { @@ -112,14 +113,14 @@ object ScalaSigParsers extends RulesWithState with MemoisableRules { val symTab = read(_.table) val size = symTab ^^ (_.size) - def entry(index : Int) = memo(("entry", index)) { + def entry(index: Int) = memo(("entry", index)) { cond(_ hasEntry index) -~ read(_ getEntry index) >-> { entry => Success(entry, entry.entryType) } } - def parseEntry[A](parser : ScalaSigEntryParsers.EntryParser[A])(index : Int) : Parser[A] = + def parseEntry[A](parser: ScalaSigEntryParsers.EntryParser[A])(index: Int): Parser[A] = entry(index) -~ parser >> { a => entry => Success(entry.scalaSig, a) } - def allEntries[A](f : ScalaSigEntryParsers.EntryParser[A]) = size >> { n => anyOf((0 until n) map parseEntry(f)) } + def allEntries[A](f: ScalaSigEntryParsers.EntryParser[A]) = size >> { n => anyOf((0 until n) map parseEntry(f)) } lazy val entries = allEntries(ScalaSigEntryParsers.entry) as "entries" lazy val symbols = allEntries(ScalaSigEntryParsers.symbol) as "symbols" @@ -136,20 +137,20 @@ object ScalaSigEntryParsers extends RulesWithState with MemoisableRules { type S = ScalaSig#Entry type EntryParser[A] = Rule[A, String] - implicit def byteCodeEntryParser[A](rule : ScalaSigAttributeParsers.Parser[A]) : EntryParser[A] = apply { entry => + implicit def byteCodeEntryParser[A](rule: ScalaSigAttributeParsers.Parser[A]): EntryParser[A] = apply { entry => rule(entry.byteCode) mapOut (entry setByteCode _) } - def toEntry[A](index : Int) = apply { sigEntry => ScalaSigParsers.entry(index)(sigEntry.scalaSig) } + def toEntry[A](index: Int) = apply { sigEntry => ScalaSigParsers.entry(index)(sigEntry.scalaSig) } - def parseEntry[A](parser : EntryParser[A])(index : Int) = (toEntry(index) -~ parser) + def parseEntry[A](parser: EntryParser[A])(index: Int) = (toEntry(index) -~ parser) - implicit def entryType(code : Int) = key filter (_ == code) + implicit def entryType(code: Int) = key filter (_ == code) val index = read(_.index) val key = read(_.entryType) - lazy val entry : EntryParser[Any] = symbol | typeEntry | literal | name | attributeInfo | annotInfo | children | get + lazy val entry: EntryParser[Any] = symbol | typeEntry | literal | name | attributeInfo | annotInfo | children | get val ref = byteCodeEntryParser(nat) @@ -158,7 +159,7 @@ object ScalaSigEntryParsers extends RulesWithState with MemoisableRules { val name = termName | typeName as "name" - def refTo[A](rule : EntryParser[A]) : EntryParser[A] = ref >>& parseEntry(rule) + def refTo[A](rule: EntryParser[A]): EntryParser[A] = ref >>& parseEntry(rule) lazy val nameRef = refTo(name) lazy val symbolRef = refTo(symbol) @@ -169,7 +170,7 @@ object ScalaSigEntryParsers extends RulesWithState with MemoisableRules { def symHeader(key: Int): EntryParser[Any] = (key -~ none | (key + 64) -~ nat) - def symbolEntry(key : Int) = symHeader(key) -~ symbolInfo + def symbolEntry(key: Int) = symHeader(key) -~ symbolInfo val noSymbol = 3 -^ NoSymbol val typeSymbol = symbolEntry(4) ^^ TypeSymbol as "typeSymbol" @@ -180,7 +181,7 @@ object ScalaSigEntryParsers extends RulesWithState with MemoisableRules { val extRef = 9 -~ nameRef ~ (symbolRef?) ~ get ^~~^ ExternalSymbol as "extRef" val extModClassRef = 10 -~ nameRef ~ (symbolRef?) ~ get ^~~^ ExternalSymbol as "extModClassRef" - lazy val symbol : EntryParser[Symbol] = oneOf( + lazy val symbol: EntryParser[Symbol] = oneOf( noSymbol, typeSymbol, aliasSymbol, @@ -195,7 +196,7 @@ object ScalaSigEntryParsers extends RulesWithState with MemoisableRules { val typeLevel = nat val typeIndex = nat - lazy val typeEntry : EntryParser[Type] = oneOf( + lazy val typeEntry: EntryParser[Type] = oneOf( 11 -^ NoType, 12 -^ NoPrefixType, 13 -~ symbolRef ^^ ThisType, @@ -236,17 +237,17 @@ object ScalaSigEntryParsers extends RulesWithState with MemoisableRules { lazy val topLevelClass = classSymbol filter isTopLevelClass lazy val topLevelObject = objectSymbol filter isTopLevel - def isTopLevel(symbol : Symbol) = symbol.parent match { - case Some(ext : ExternalSymbol) => true + def isTopLevel(symbol: Symbol) = symbol.parent match { + case Some(ext: ExternalSymbol) => true case _ => false } - def isTopLevelClass (symbol : Symbol) = !symbol.isModule && isTopLevel(symbol) + def isTopLevelClass (symbol: Symbol) = !symbol.isModule && isTopLevel(symbol) } - case class AttributeInfo(symbol : Symbol, typeRef : Type, value : Option[Any], values : Seq[String ~ Any]) // sym_Ref info_Ref {constant_Ref} {nameRef constantRef} - case class Children(symbolRefs : Seq[Int]) //sym_Ref {sym_Ref} +case class AttributeInfo(symbol: Symbol, typeRef: Type, value: Option[Any], values: Seq[String ~ Any]) // sym_Ref info_Ref {constant_Ref} {nameRef constantRef} +case class Children(symbolRefs: Seq[Int]) //sym_Ref {sym_Ref} - case class AnnotInfo(refs : Seq[Int]) // attarg_Ref {constant_Ref attarg_Ref} +case class AnnotInfo(refs: Seq[Int]) // attarg_Ref {constant_Ref attarg_Ref} /*************************************************** * | 49 TREE len_Nat 1 EMPTYtree diff --git a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/ScalaSigPrinter.scala b/src/scalap/scala/tools/scalap/scalasig/ScalaSigPrinter.scala index e5a4ff649e..5929e0f59f 100644 --- a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/ScalaSigPrinter.scala +++ b/src/scalap/scala/tools/scalap/scalasig/ScalaSigPrinter.scala @@ -5,17 +5,14 @@ ** */ +package scala.tools.scalap.scalasig -package scala.tools.scalap -package scalax -package rules -package scalasig +import scala.language.implicitConversions import java.io.{PrintStream, ByteArrayOutputStream} import java.util.regex.Pattern -import scala.tools.scalap.scalax.util.StringUtil -import scala.reflect.NameTransformer -import java.lang.String + +import scala.tools.scalap.rules.~ class ScalaSigPrinter(stream: PrintStream, printPrivates: Boolean) { import stream._ @@ -136,7 +133,7 @@ class ScalaSigPrinter(stream: PrintStream, printPrivates: Boolean) { print(" {") //Print class selftype c.selfType match { - case Some(t: Type) => print("\n"); print(" this : " + toString(t) + " =>") + case Some(t: Type) => print("\n"); print(" this: " + toString(t) + " =>") case None => } print("\n") @@ -186,22 +183,12 @@ class ScalaSigPrinter(stream: PrintStream, printPrivates: Boolean) { printWithIndent(level, "}\n") } - def genParamNames(t: {def paramTypes: Seq[Type]}): List[String] = t.paramTypes.toList.map(x => { - var str = toString(x) - val j = str.indexOf("[") - if (j > 0) str = str.substring(0, j) - str = StringUtil.trimStart(str, "=> ") - val i = str.lastIndexOf(".") - val res = if (i > 0) str.substring(i + 1) else str - if (res.length > 1) StringUtil.decapitalize(res.substring(0, 1)) else res.toLowerCase - }) - def printMethodType(t: Type, printResult: Boolean)(cont: => Unit): Unit = { - def _pmt(mt: Type {def resultType: Type; def paramSymbols: Seq[Symbol]}) = { + def _pmt(mt: MethodType) = { val paramEntries = mt.paramSymbols.map({ - case ms: MethodSymbol => ms.name + " : " + toString(ms.infoType)(TypeFlags(true)) + case ms: MethodSymbol => ms.name + ": " + toString(ms.infoType)(TypeFlags(true)) case _ => "^___^" }) val implicitWord = mt.paramSymbols.headOption match { @@ -216,21 +203,21 @@ class ScalaSigPrinter(stream: PrintStream, printPrivates: Boolean) { mt.resultType match { case mt: MethodType => printMethodType(mt, printResult)({}) case x => if (printResult) { - print(" : "); + print(": "); printType(x) } } } t match { - case NullaryMethodType(resType) => if (printResult) { print(" : "); printType(resType) } + case NullaryMethodType(resType) => if (printResult) { print(": "); printType(resType) } case mt@MethodType(resType, paramSymbols) => _pmt(mt) case pt@PolyType(mt, typeParams) => { print(typeParamString(typeParams)) printMethodType(mt, printResult)({}) } //todo consider another method types - case x => print(" : "); printType(x) + case x => print(": "); printType(x) } // Print rest of the symbol output @@ -356,8 +343,8 @@ class ScalaSigPrinter(stream: PrintStream, printPrivates: Boolean) { } case "scala.<byname>" => "=> " + toString(typeArgs.head) case _ => { - val path = StringUtil.cutSubstring(symbol.path)(".package") //remove package object reference - StringUtil.trimStart(processName(path) + typeArgString(typeArgs), "<empty>.") + val path = cutSubstring(symbol.path)(".package") //remove package object reference + trimStart(processName(path) + typeArgString(typeArgs), "<empty>.") } }) case TypeBoundsType(lower, upper) => { @@ -402,7 +389,7 @@ class ScalaSigPrinter(stream: PrintStream, printPrivates: Boolean) { def typeArgString(typeArgs: Seq[Type]): String = if (typeArgs.isEmpty) "" - else typeArgs.map(toString).map(StringUtil.trimStart(_, "=> ")).mkString("[", ", ", "]") + else typeArgs.map(toString).map(trimStart(_, "=> ")).mkString("[", ", ", "]") def typeParamString(params: Seq[Symbol]): String = if (params.isEmpty) "" @@ -423,7 +410,7 @@ class ScalaSigPrinter(stream: PrintStream, printPrivates: Boolean) { if (i > 0) name.substring(i + 2) else name } - def processName(name: String) = { + private def processName(name: String) = { val stripped = stripPrivatePrefix(name) val m = pattern.matcher(stripped) var temp = stripped @@ -433,7 +420,15 @@ class ScalaSigPrinter(stream: PrintStream, printPrivates: Boolean) { temp = temp.replaceAll(re, _syms(re)) } val result = temp.replaceAll(placeholderPattern, "_") - NameTransformer.decode(result) + scala.reflect.NameTransformer.decode(result) } + private def trimStart(s: String, prefix: String) = + if (s != null && s.startsWith(prefix)) s.substring(prefix.length) else s + + private def decapitalize(s: String) = + java.beans.Introspector.decapitalize(s) + + private def cutSubstring(dom: String)(s: String) = + if (dom != null && s != null) dom.replace(s, "") else dom } diff --git a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/SourceFileAttributeParser.scala b/src/scalap/scala/tools/scalap/scalasig/SourceFileAttributeParser.scala index fc5a75c046..88d3d3b8b0 100644 --- a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/SourceFileAttributeParser.scala +++ b/src/scalap/scala/tools/scalap/scalasig/SourceFileAttributeParser.scala @@ -1,7 +1,4 @@ -package scala.tools.scalap -package scalax -package rules -package scalasig +package scala.tools.scalap.scalasig /** * @author ilyas @@ -16,13 +13,12 @@ object SourceFileAttributeParser extends ByteCodeReader { /** * * SourceFile_attribute { - u2 attribute_name_index; - u4 attribute_length; - u2 sourcefile_index; + u2 attribute_name_index; + u4 attribute_length; + u2 sourcefile_index; } * * Contains only file index in ConstantPool, first two fields are already treated * by {@link scalax.rules.scalasig.ClassFile.attribute#attribute} */ case class SourceFileInfo(sourceFileIndex: Int) - diff --git a/src/scalap/scala/tools/scalap/scalasig/Symbol.scala b/src/scalap/scala/tools/scalap/scalasig/Symbol.scala new file mode 100644 index 0000000000..0656938150 --- /dev/null +++ b/src/scalap/scala/tools/scalap/scalasig/Symbol.scala @@ -0,0 +1,70 @@ +package scala.tools.scalap.scalasig + +import ScalaSigEntryParsers._ + +trait Symbol extends Flags { + def name: String + def parent: Option[Symbol] + def children: Seq[Symbol] + + def path: String = parent.map(_.path + ".").getOrElse("") + name +} + +case object NoSymbol extends Symbol { + def name = "<no symbol>" + def parent = None + def hasFlag(flag: Long) = false + def children = Nil +} + +abstract class ScalaSigSymbol extends Symbol { + def applyRule[A](rule: EntryParser[A]): A = expect(rule)(entry) + def applyScalaSigRule[A](rule: ScalaSigParsers.Parser[A]) = ScalaSigParsers.expect(rule)(entry.scalaSig) + + def entry: ScalaSig#Entry + def index = entry.index + + lazy val children: Seq[Symbol] = applyScalaSigRule(ScalaSigParsers.symbols) filter (_.parent == Some(this)) + lazy val attributes: Seq[AttributeInfo] = applyScalaSigRule(ScalaSigParsers.attributes) filter (_.symbol == this) +} + +case class ExternalSymbol(name: String, parent: Option[Symbol], entry: ScalaSig#Entry) extends ScalaSigSymbol { + override def toString = path + def hasFlag(flag: Long) = false +} + +case class SymbolInfo(name: String, owner: Symbol, flags: Int, privateWithin: Option[AnyRef], info: Int, entry: ScalaSig#Entry) { + def symbolString(any: AnyRef) = any match { + case sym: SymbolInfoSymbol => sym.index.toString + case other => other.toString + } + + override def toString = name + ", owner=" + symbolString(owner) + ", flags=" + flags.toHexString + ", info=" + info + (privateWithin match { + case Some(any) => ", privateWithin=" + symbolString(any) + case None => " " + }) +} + +abstract class SymbolInfoSymbol extends ScalaSigSymbol { + def symbolInfo: SymbolInfo + + def entry = symbolInfo.entry + def name = symbolInfo.name + def parent = Some(symbolInfo.owner) + def hasFlag(flag: Long) = (symbolInfo.flags & flag) != 0L + + lazy val infoType = applyRule(parseEntry(typeEntry)(symbolInfo.info)) +} + +case class TypeSymbol(symbolInfo: SymbolInfo) extends SymbolInfoSymbol{ + override def path = name +} + +case class AliasSymbol(symbolInfo: SymbolInfo) extends SymbolInfoSymbol{ + override def path = name +} +case class ClassSymbol(symbolInfo: SymbolInfo, thisTypeRef: Option[Int]) extends SymbolInfoSymbol { + lazy val selfType = thisTypeRef.map{(x: Int) => applyRule(parseEntry(typeEntry)(x))} +} +case class ObjectSymbol(symbolInfo: SymbolInfo) extends SymbolInfoSymbol +case class MethodSymbol(symbolInfo: SymbolInfo, aliasRef: Option[Int]) extends SymbolInfoSymbol diff --git a/src/scalap/scala/tools/scalap/scalasig/Type.scala b/src/scalap/scala/tools/scalap/scalasig/Type.scala new file mode 100644 index 0000000000..97dc28d223 --- /dev/null +++ b/src/scalap/scala/tools/scalap/scalasig/Type.scala @@ -0,0 +1,22 @@ +package scala.tools.scalap.scalasig + +abstract class Type + +case object NoType extends Type +case object NoPrefixType extends Type + +case class ThisType(symbol: Symbol) extends Type +case class SingleType(typeRef: Type, symbol: Symbol) extends Type +case class ConstantType(constant: Any) extends Type +case class TypeRefType(prefix: Type, symbol: Symbol, typeArgs: Seq[Type]) extends Type +case class TypeBoundsType(lower: Type, upper: Type) extends Type +case class RefinedType(classSym: Symbol, typeRefs: List[Type]) extends Type +case class ClassInfoType(symbol: Symbol, typeRefs: Seq[Type]) extends Type +case class ClassInfoTypeWithCons(symbol: Symbol, typeRefs: Seq[Type], cons: String) extends Type +case class MethodType(resultType: Type, paramSymbols: Seq[Symbol]) extends Type +case class NullaryMethodType(resultType: Type) extends Type +case class PolyType(typeRef: Type, symbols: Seq[TypeSymbol]) extends Type +case class PolyTypeWithCons(typeRef: Type, symbols: Seq[TypeSymbol], cons: String) extends Type +case class AnnotatedType(typeRef: Type, attribTreeRefs: List[Int]) extends Type +case class AnnotatedWithSelfType(typeRef: Type, symbol: Symbol, attribTreeRefs: List[Int]) extends Type +case class ExistentialType(typeRef: Type, symbols: Seq[Symbol]) extends Type diff --git a/src/scalap/scala/tools/scalap/scalax/rules/Result.scala b/src/scalap/scala/tools/scalap/scalax/rules/Result.scala deleted file mode 100644 index 17ad4bd053..0000000000 --- a/src/scalap/scala/tools/scalap/scalax/rules/Result.scala +++ /dev/null @@ -1,72 +0,0 @@ -// ----------------------------------------------------------------------------- -// -// Scalax - The Scala Community Library -// Copyright (c) 2005-8 The Scalax Project. All rights reserved. -// -// The primary distribution site is http://scalax.scalaforge.org/ -// -// This software is released under the terms of the Revised BSD License. -// There is NO WARRANTY. See the file LICENSE for the full text. -// -// ----------------------------------------------------------------------------- - -package scala.tools.scalap -package scalax -package rules; - -/** Represents the combined value of two rules applied in sequence. - * - * @see the Scala parser combinator - */ -case class ~[+A, +B](_1 : A, _2 : B) { - override def toString = "(" + _1 + " ~ " + _2 + ")" -} - - -sealed abstract class Result[+Out, +A, +X] { - def out : Out - def value : A - def error : X - - implicit def toOption : Option[A] - - def map[B](f : A => B) : Result[Out, B, X] - def mapOut[Out2](f : Out => Out2) : Result[Out2, A, X] - def map[Out2, B](f : (Out, A) => (Out2, B)) : Result[Out2, B, X] - def flatMap[Out2, B](f : (Out, A) => Result[Out2, B, Nothing]) : Result[Out2, B, X] - def orElse[Out2 >: Out, B >: A](other : => Result[Out2, B, Nothing]) : Result[Out2, B, X] -} - -case class Success[+Out, +A](out : Out, value : A) extends Result[Out, A, Nothing] { - def error = throw new ScalaSigParserError("No error") - - def toOption = Some(value) - - def map[B](f : A => B) : Result[Out, B, Nothing] = Success(out, f(value)) - def mapOut[Out2](f : Out => Out2) : Result[Out2, A, Nothing] = Success(f(out), value) - def map[Out2, B](f : (Out, A) => (Out2, B)) : Success[Out2, B] = f(out, value) match { case (out2, b) => Success(out2, b) } - def flatMap[Out2, B](f : (Out, A) => Result[Out2, B, Nothing]) : Result[Out2, B, Nothing]= f(out, value) - def orElse[Out2 >: Out, B >: A](other : => Result[Out2, B, Nothing]) : Result[Out2, B, Nothing] = this -} - -sealed abstract class NoSuccess[+X] extends Result[Nothing, Nothing, X] { - def out = throw new ScalaSigParserError("No output") - def value = throw new ScalaSigParserError("No value") - - def toOption = None - - def map[B](f : Nothing => B) = this - def mapOut[Out2](f : Nothing => Out2) = this - def map[Out2, B](f : (Nothing, Nothing) => (Out2, B)) = this - def flatMap[Out2, B](f : (Nothing, Nothing) => Result[Out2, B, Nothing]) = this - def orElse[Out2, B](other : => Result[Out2, B, Nothing]) = other -} - -case object Failure extends NoSuccess[Nothing] { - def error = throw new ScalaSigParserError("No error") -} - -case class ScalaSigParserError(msg: String) extends RuntimeException(msg) - -case class Error[+X](error : X) extends NoSuccess[X] { -} diff --git a/src/scalap/scala/tools/scalap/scalax/rules/Rule.scala b/src/scalap/scala/tools/scalap/scalax/rules/Rule.scala deleted file mode 100644 index 489a05ecd0..0000000000 --- a/src/scalap/scala/tools/scalap/scalax/rules/Rule.scala +++ /dev/null @@ -1,177 +0,0 @@ -// ----------------------------------------------------------------------------- -// -// Scalax - The Scala Community Library -// Copyright (c) 2005-8 The Scalax Project. All rights reserved. -// -// The primary distribution site is http://scalax.scalaforge.org/ -// -// This software is released under the terms of the Revised BSD License. -// There is NO WARRANTY. See the file LICENSE for the full text. -// -// ----------------------------------------------------------------------------- - -package scala.tools.scalap -package scalax -package rules - -/** A Rule is a function from some input to a Result. The result may be: - * <ul> - * <li>Success, with a value of some type and an output that may serve as the input to subsequent rules.</li> - * <li>Failure. A failure may result in some alternative rule being applied.</li> - * <li>Error. No further rules should be attempted.</li> - * </ul> - * - * @author Andrew Foggin - * - * Inspired by the Scala parser combinator. - */ -trait Rule[-In, +Out, +A, +X] extends (In => Result[Out, A, X]) { - val factory : Rules - import factory._ - - def as(name : String) = ruleWithName(name, this) - - def flatMap[Out2, B, X2 >: X](fa2ruleb : A => Out => Result[Out2, B, X2]) = mapResult { - case Success(out, a) => fa2ruleb(a)(out) - case Failure => Failure - case err @ Error(_) => err - } - - def map[B](fa2b : A => B) = flatMap { a => out => Success(out, fa2b(a)) } - - def filter(f : A => Boolean) = flatMap { a => out => if(f(a)) Success(out, a) else Failure } - - def mapResult[Out2, B, Y](f : Result[Out, A, X] => Result[Out2, B, Y]) = rule { - in : In => f(apply(in)) - } - - def orElse[In2 <: In, Out2 >: Out, A2 >: A, X2 >: X](other : => Rule[In2, Out2, A2, X2]) : Rule[In2, Out2, A2, X2] = new Choice[In2, Out2, A2, X2] { - val factory = Rule.this.factory - lazy val choices = Rule.this :: other :: Nil - } - - def orError[In2 <: In] = this orElse error[Any] - - def |[In2 <: In, Out2 >: Out, A2 >: A, X2 >: X](other : => Rule[In2, Out2, A2, X2]) = orElse(other) - - def ^^[B](fa2b : A => B) = map(fa2b) - - def ^^?[B](pf : PartialFunction[A, B]) = filter (pf.isDefinedAt(_)) ^^ pf - - def ??(pf : PartialFunction[A, Any]) = filter (pf.isDefinedAt(_)) - - def -^[B](b : B) = map { any => b } - - /** Maps an Error */ - def !^[Y](fx2y : X => Y) = mapResult { - case s @ Success(_, _) => s - case Failure => Failure - case Error(x) => Error(fx2y(x)) - } - - def >>[Out2, B, X2 >: X](fa2ruleb : A => Out => Result[Out2, B, X2]) = flatMap(fa2ruleb) - - def >->[Out2, B, X2 >: X](fa2resultb : A => Result[Out2, B, X2]) = flatMap { a => any => fa2resultb(a) } - - def >>?[Out2, B, X2 >: X](pf : PartialFunction[A, Rule[Out, Out2, B, X2]]) = filter(pf isDefinedAt _) flatMap pf - - def >>&[B, X2 >: X](fa2ruleb : A => Out => Result[Any, B, X2]) = flatMap { a => out => fa2ruleb(a)(out) mapOut { any => out } } - - def ~[Out2, B, X2 >: X](next : => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next) yield new ~(a, b) - - def ~-[Out2, B, X2 >: X](next : => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next) yield a - - def -~[Out2, B, X2 >: X](next : => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next) yield b - - def ~++[Out2, B >: A, X2 >: X](next : => Rule[Out, Out2, Seq[B], X2]) = for (a <- this; b <- next) yield a :: b.toList - - /** Apply the result of this rule to the function returned by the next rule */ - def ~>[Out2, B, X2 >: X](next : => Rule[Out, Out2, A => B, X2]) = for (a <- this; fa2b <- next) yield fa2b(a) - - /** Apply the result of this rule to the function returned by the previous rule */ - def <~:[InPrev, B, X2 >: X](prev : => Rule[InPrev, In, A => B, X2]) = for (fa2b <- prev; a <- this) yield fa2b(a) - - def ~![Out2, B, X2 >: X](next : => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next orError) yield new ~(a, b) - - def ~-![Out2, B, X2 >: X](next : => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next orError) yield a - - def -~![Out2, B, X2 >: X](next : => Rule[Out, Out2, B, X2]) = for (a <- this; b <- next orError) yield b - - def -[In2 <: In](exclude : => Rule[In2, Any, Any, Any]) = !exclude -~ this - - /** ^~^(f) is equivalent to ^^ { case b1 ~ b2 => f(b1, b2) } - */ - def ^~^[B1, B2, B >: A <% B1 ~ B2, C](f : (B1, B2) => C) = map { a => - (a : B1 ~ B2) match { case b1 ~ b2 => f(b1, b2) } - } - - /** ^~~^(f) is equivalent to ^^ { case b1 ~ b2 ~ b3 => f(b1, b2, b3) } - */ - def ^~~^[B1, B2, B3, B >: A <% B1 ~ B2 ~ B3, C](f : (B1, B2, B3) => C) = map { a => - (a : B1 ~ B2 ~ B3) match { case b1 ~ b2 ~ b3 => f(b1, b2, b3) } - } - - /** ^~~~^(f) is equivalent to ^^ { case b1 ~ b2 ~ b3 ~ b4 => f(b1, b2, b3, b4) } - */ - def ^~~~^[B1, B2, B3, B4, B >: A <% B1 ~ B2 ~ B3 ~ B4, C](f : (B1, B2, B3, B4) => C) = map { a => - (a : B1 ~ B2 ~ B3 ~ B4) match { case b1 ~ b2 ~ b3 ~ b4 => f(b1, b2, b3, b4) } - } - - /** ^~~~~^(f) is equivalent to ^^ { case b1 ~ b2 ~ b3 ~ b4 ~ b5 => f(b1, b2, b3, b4, b5) } - */ - def ^~~~~^[B1, B2, B3, B4, B5, B >: A <% B1 ~ B2 ~ B3 ~ B4 ~ B5, C](f : (B1, B2, B3, B4, B5) => C) = map { a => - (a : B1 ~ B2 ~ B3 ~ B4 ~ B5) match { case b1 ~ b2 ~ b3 ~ b4 ~ b5 => f(b1, b2, b3, b4, b5) } - } - - /** ^~~~~~^(f) is equivalent to ^^ { case b1 ~ b2 ~ b3 ~ b4 ~ b5 ~ b6 => f(b1, b2, b3, b4, b5, b6) } - */ - def ^~~~~~^[B1, B2, B3, B4, B5, B6, B >: A <% B1 ~ B2 ~ B3 ~ B4 ~ B5 ~ B6, C](f : (B1, B2, B3, B4, B5, B6) => C) = map { a => - (a : B1 ~ B2 ~ B3 ~ B4 ~ B5 ~ B6) match { case b1 ~ b2 ~ b3 ~ b4 ~ b5 ~ b6 => f(b1, b2, b3, b4, b5, b6) } - } - - /** ^~~~~~~^(f) is equivalent to ^^ { case b1 ~ b2 ~ b3 ~ b4 ~ b5 ~ b6 => f(b1, b2, b3, b4, b5, b6) } - */ - def ^~~~~~~^[B1, B2, B3, B4, B5, B6, B7, B >: A <% B1 ~ B2 ~ B3 ~ B4 ~ B5 ~ B6 ~ B7, C](f : (B1, B2, B3, B4, B5, B6, B7) => C) = map { a => - (a : B1 ~ B2 ~ B3 ~ B4 ~ B5 ~ B6 ~ B7) match { case b1 ~ b2 ~ b3 ~ b4 ~ b5 ~ b6 ~b7 => f(b1, b2, b3, b4, b5, b6, b7) } - } - - /** >~>(f) is equivalent to >> { case b1 ~ b2 => f(b1, b2) } - */ - def >~>[Out2, B1, B2, B >: A <% B1 ~ B2, C, X2 >: X](f : (B1, B2) => Out => Result[Out2, C, X2]) = flatMap { a => - (a : B1 ~ B2) match { case b1 ~ b2 => f(b1, b2) } - } - - /** ^-^(f) is equivalent to ^^ { b2 => b1 => f(b1, b2) } - */ - def ^-^ [B1, B2 >: A, C](f : (B1, B2) => C) = map { b2 : B2 => b1 : B1 => f(b1, b2) } - - /** ^~>~^(f) is equivalent to ^^ { case b2 ~ b3 => b1 => f(b1, b2, b3) } - */ - def ^~>~^ [B1, B2, B3, B >: A <% B2 ~ B3, C](f : (B1, B2, B3) => C) = map { a => - (a : B2 ~ B3) match { case b2 ~ b3 => b1 : B1 => f(b1, b2, b3) } - } -} - - -trait Choice[-In, +Out, +A, +X] extends Rule[In, Out, A, X] { - def choices : List[Rule[In, Out, A, X]] - - def apply(in : In) = { - def oneOf(list : List[Rule[In, Out, A, X]]) : Result[Out, A, X] = list match { - case Nil => Failure - case first :: rest => first(in) match { - case Failure => oneOf(rest) - case result => result - } - } - oneOf(choices) - } - - override def orElse[In2 <: In, Out2 >: Out, A2 >: A, X2 >: X](other : => Rule[In2, Out2, A2, X2]) : Rule[In2, Out2, A2, X2] = new Choice[In2, Out2, A2, X2] { - val factory = Choice.this.factory - lazy val choices = Choice.this.choices ::: other :: Nil - } -} - - - diff --git a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/Symbol.scala b/src/scalap/scala/tools/scalap/scalax/rules/scalasig/Symbol.scala deleted file mode 100644 index dee1cf84ac..0000000000 --- a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/Symbol.scala +++ /dev/null @@ -1,73 +0,0 @@ -package scala.tools.scalap -package scalax -package rules -package scalasig - -import ScalaSigEntryParsers._ - -trait Symbol extends Flags { - def name : String - def parent : Option[Symbol] - def children : Seq[Symbol] - - def path : String = parent.map(_.path + ".").getOrElse("") + name -} - -case object NoSymbol extends Symbol { - def name = "<no symbol>" - def parent = None - def hasFlag(flag : Long) = false - def children = Nil -} - -abstract class ScalaSigSymbol extends Symbol { - def applyRule[A](rule : EntryParser[A]) : A = expect(rule)(entry) - def applyScalaSigRule[A](rule : ScalaSigParsers.Parser[A]) = ScalaSigParsers.expect(rule)(entry.scalaSig) - - def entry : ScalaSig#Entry - def index = entry.index - - lazy val children : Seq[Symbol] = applyScalaSigRule(ScalaSigParsers.symbols) filter (_.parent == Some(this)) - lazy val attributes : Seq[AttributeInfo] = applyScalaSigRule(ScalaSigParsers.attributes) filter (_.symbol == this) -} - -case class ExternalSymbol(name : String, parent : Option[Symbol], entry : ScalaSig#Entry) extends ScalaSigSymbol { - override def toString = path - def hasFlag(flag : Long) = false -} - -case class SymbolInfo(name : String, owner : Symbol, flags : Int, privateWithin : Option[AnyRef], info : Int, entry : ScalaSig#Entry) { - def symbolString(any : AnyRef) = any match { - case sym : SymbolInfoSymbol => sym.index.toString - case other => other.toString - } - - override def toString = name + ", owner=" + symbolString(owner) + ", flags=" + flags.toHexString + ", info=" + info + (privateWithin match { - case Some(any) => ", privateWithin=" + symbolString(any) - case None => " " - }) -} - -abstract class SymbolInfoSymbol extends ScalaSigSymbol { - def symbolInfo : SymbolInfo - - def entry = symbolInfo.entry - def name = symbolInfo.name - def parent = Some(symbolInfo.owner) - def hasFlag(flag : Long) = (symbolInfo.flags & flag) != 0L - - lazy val infoType = applyRule(parseEntry(typeEntry)(symbolInfo.info)) -} - -case class TypeSymbol(symbolInfo : SymbolInfo) extends SymbolInfoSymbol{ - override def path = name -} - -case class AliasSymbol(symbolInfo : SymbolInfo) extends SymbolInfoSymbol{ - override def path = name -} -case class ClassSymbol(symbolInfo : SymbolInfo, thisTypeRef : Option[Int]) extends SymbolInfoSymbol { - lazy val selfType = thisTypeRef.map{(x: Int) => applyRule(parseEntry(typeEntry)(x))} -} -case class ObjectSymbol(symbolInfo : SymbolInfo) extends SymbolInfoSymbol -case class MethodSymbol(symbolInfo : SymbolInfo, aliasRef : Option[Int]) extends SymbolInfoSymbol diff --git a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/Type.scala b/src/scalap/scala/tools/scalap/scalax/rules/scalasig/Type.scala deleted file mode 100644 index 0444e701f2..0000000000 --- a/src/scalap/scala/tools/scalap/scalax/rules/scalasig/Type.scala +++ /dev/null @@ -1,25 +0,0 @@ -package scala.tools.scalap -package scalax -package rules -package scalasig - -abstract class Type - -case object NoType extends Type -case object NoPrefixType extends Type - -case class ThisType(symbol : Symbol) extends Type -case class SingleType(typeRef : Type, symbol : Symbol) extends Type -case class ConstantType(constant : Any) extends Type -case class TypeRefType(prefix : Type, symbol : Symbol, typeArgs : Seq[Type]) extends Type -case class TypeBoundsType(lower : Type, upper : Type) extends Type -case class RefinedType(classSym : Symbol, typeRefs : List[Type]) extends Type -case class ClassInfoType(symbol : Symbol, typeRefs : Seq[Type]) extends Type -case class ClassInfoTypeWithCons(symbol : Symbol, typeRefs : Seq[Type], cons: String) extends Type -case class MethodType(resultType : Type, paramSymbols : Seq[Symbol]) extends Type -case class NullaryMethodType(resultType : Type) extends Type -case class PolyType(typeRef : Type, symbols : Seq[TypeSymbol]) extends Type -case class PolyTypeWithCons(typeRef : Type, symbols : Seq[TypeSymbol], cons: String) extends Type -case class AnnotatedType(typeRef : Type, attribTreeRefs : List[Int]) extends Type -case class AnnotatedWithSelfType(typeRef : Type, symbol : Symbol, attribTreeRefs : List[Int]) extends Type -case class ExistentialType(typeRef : Type, symbols : Seq[Symbol]) extends Type diff --git a/src/scalap/scala/tools/scalap/scalax/util/StringUtil.scala b/src/scalap/scala/tools/scalap/scalax/util/StringUtil.scala deleted file mode 100644 index 6077eded0f..0000000000 --- a/src/scalap/scala/tools/scalap/scalax/util/StringUtil.scala +++ /dev/null @@ -1,19 +0,0 @@ -package scala.tools.scalap -package scalax -package util - -import java.beans.Introspector - -/** - * @author ilyas - */ - -object StringUtil { - - def trimStart(s: String, prefix: String) = if (s != null && s.startsWith(prefix)) s.substring(prefix.length) else s - - def decapitalize(s: String) = Introspector.decapitalize(s) - - def cutSubstring(dom: String)(s: String) = if (dom != null && s != null) dom.replace(s, "") else dom - -} |